返回 DeepSeek-Reasonix
remote_projects.go
根目录 / desktop / remote_projects.go
1 package main
2
3 import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "net/http"
8 "strings"
9 "sync"
10 "sync/atomic"
11 "time"
12
13 "reasonix/internal/config"
14 "reasonix/internal/event"
15 )
16
17 // remoteTabModelSeq stamps every remote-tab model assignment; the credential
18 // proxy uses the stamps to resolve "most recently set" without relying on map
19 // iteration order.
20 var remoteTabModelSeq atomic.Uint64
21
22 // ── View structs mirrored in frontend/src/lib/types.ts ──
23
24 // RemoteTabRef marks a tab as remote and binds it to a host+workspace pair.
25 type RemoteTabRef struct {
26 HostID string `json:"hostId"`
27 Workspace string `json:"workspace"`
28 }
29
30 type RemoteProjectView struct {
31 HostID string `json:"hostId"`
32 Workspace string `json:"workspace"`
33 Title string `json:"title,omitempty"`
34 Color string `json:"color,omitempty"`
35 // Merged marks that an overlapping pin already existed and the returned
36 // Workspace is that existing group's canonical path — no new pin was added.
37 Merged bool `json:"merged,omitempty"`
38 }
39
40 // RemoteTabOpenOptions mirrors the frontend opts bag: NewSession lands the
41 // tab in a fresh serve session; SessionName resumes a listed one.
42 type RemoteTabOpenOptions struct {
43 NewSession bool `json:"newSession,omitempty"`
44 SessionName string `json:"sessionName,omitempty"`
45 SessionPath string `json:"sessionPath,omitempty"`
46 SessionID string `json:"sessionId,omitempty"`
47 SessionTitle string `json:"sessionTitle,omitempty"`
48 }
49
50 // RemoteTabStateView is the payload on the remote-tab:{id}:state channel.
51 // State: connecting | ready | reconnecting | serve_down | error.
52 type RemoteTabStateView struct {
53 State string `json:"state"`
54 Error string `json:"error,omitempty"`
55 HydrationRevision uint64 `json:"hydrationRevision,omitempty"`
56 }
57
58 // remoteTab is one open remote project tab.
59 type remoteTab struct {
60 selectionMu sync.Mutex // orders resume outcomes and queued registrations
61 sessionMu sync.Mutex
62 // routeEventMu orders foreground-route adoption with route-scoped frames.
63 // It stays separate from remoteTabMu so frontend callbacks run unlocked;
64 // lock order is routeEventMu, then App.remoteTabMu.
65 routeEventMu sync.Mutex
66 id string
67 ref RemoteTabRef
68 state string
69 err string
70 session remoteTabSessionState
71 hostLabel string
72 // topicTitle starts as the workspace name and adopts the generated title.
73 topicTitle string
74 titleRefresh remoteTabTitleRefreshState
75 // model is the desktop-owned current model ref for this remote tab.
76 // modelSeq orders concurrent writes for deterministic proxy registration.
77 model string
78 modelSeq uint64
79 settings remoteModelApplicationState // guarded by remoteTabMu
80
81 // Bridge fields are protected by App.remoteTabMu. gen fences old pumps;
82 // client preserves cookies and token permits a new handshake.
83 client *http.Client
84 base string
85 token string
86 // capabilities are fixed by the authenticated serve handshake. Missing
87 // permission-presets-v1 means history-only compatibility with an old serve.
88 capabilities map[string]bool
89 gen uint64
90 cancel context.CancelFunc
91 publication remoteTabPublicationState
92 // Pending approval/ask frames are retained while the frontend surface is
93 // inactive. RemoteTabSnapshot replays them when that surface mounts again.
94 pendingEvents map[string]json.RawMessage
95 persistenceExtra map[string]json.RawMessage
96
97 // Transient runtime state is projected into TabMeta even while this tab is
98 // inactive, matching the local tab strip's running/prompt/job indicators.
99 runtime remoteTabRuntimeState
100 runtimeStates map[string]event.RuntimeStateSnapshot
101 runtimeUnknown map[string]uint64
102 runtimeConflicts map[string]event.RuntimeStateSnapshot
103 // routing fences all-session SSE and retains background project-tree state.
104 routing remoteTabSessionRouting
105 // selectionRevision fences async OpenRemoteProjectTab resumes so an older
106 // rejected request cannot restore metadata over a newer user selection.
107 selectionRevision uint64
108 pendingSelection *remoteTabPendingOpenSelection
109 // ownership fences the handback of this session's writer; see
110 // remoteTabOwnershipState in remote_tab_reclaim.go.
111 ownership remoteTabOwnershipState
112 }
113
114 type remoteTabRuntimeState struct {
115 syncFailed bool
116 snapshot event.RuntimeStateSnapshot
117 // revision orders asynchronous /status snapshots against newer requests
118 // and SSE-derived runtime mutations within the same connection generation.
119 revision uint64
120 running bool
121 turnStartedAt int64
122 pendingPrompt bool
123 backgroundJobs int
124 cancelRequested bool
125 cancellable bool
126 }
127
128 // Publication counters belong to the tab, not a rollbackable Serve snapshot.
129 // Both are guarded by remoteTabMu and ordered by routeEventMu.
130 type remoteTabPublicationState struct {
131 attachedGen uint64 // pump that survived the open/session-entry barrier
132 hydrationRevision uint64
133 }
134
135 type remoteTabTitleRefreshState struct {
136 path string
137 seq uint64
138 }
139
140 type remoteTabSessionState struct {
141 newSession bool
142 name string
143 path string
144 sessionID string
145 reset bool
146 // takenOver marks a session a local runtime on the serve host took over:
147 // this tab is a read-only spectator until it reclaims the session.
148 takenOver bool
149 // instanceID identifies the Serve process that owns this session. A
150 // changed id requires explicit /new or /resume re-entry before ready.
151 instanceID string
152 }
153
154 type remoteTabLayoutState struct {
155 order []string
156 stripOrder []string
157 activeID string
158 }
159
160 // ── Remote project tabs ──
161
162 type remoteTabOpenRegistration struct {
163 reuseID string
164 reuseBlank bool
165 revive bool
166 commitSelection bool
167 selection *remoteTabPendingOpenSelection
168 previousSelection *remoteTabOpenSelection
169 retired []context.CancelFunc
170 }
171
172 type remoteTabOpenSelection struct {
173 session remoteTabSessionState
174 topicTitle string
175 currentPath string
176 pending map[string]json.RawMessage
177 runtime remoteTabRuntimeState
178 revision uint64
179 }
180
181 // registerRemoteTabOpen serializes reuse, error-shell retirement, and insert.
182 func (a *App) registerRemoteTabOpen(tab *remoteTab, hostLabel string, opts RemoteTabOpenOptions) remoteTabOpenRegistration {
183 a.remoteTabMu.Lock()
184 defer a.remoteTabMu.Unlock()
185 if a.remoteTabs == nil {
186 a.remoteTabs = map[string]*remoteTab{}
187 }
188 var result remoteTabOpenRegistration
189 for _, existing := range a.remoteTabs {
190 if existing.ref != tab.ref || existing.state == "error" {
191 continue
192 }
193 result.reuseID = existing.id
194 result.reuseBlank = existing.session.reset
195 result.revive = existing.state == "disconnected" || existing.state == "serve_down"
196 // A ready tab keeps its current route until /new succeeds. Revived shells
197 // still need the requested blank identity committed before bootstrap so
198 // their first attach enters the requested session.
199 result.commitSelection = strings.TrimSpace(opts.SessionName) != "" || strings.TrimSpace(opts.SessionPath) != "" || strings.TrimSpace(opts.SessionID) != "" || opts.NewSession && result.revive
200 if strings.TrimSpace(opts.SessionName) != "" || strings.TrimSpace(opts.SessionPath) != "" || strings.TrimSpace(opts.SessionID) != "" || opts.NewSession {
201 result.selection = newRemoteTabPendingOpenSelection(opts)
202 result.previousSelection = &remoteTabOpenSelection{
203 session: existing.session, topicTitle: existing.topicTitle,
204 currentPath: existing.routing.currentPath,
205 pending: cloneRemotePendingEvents(existing.pendingEvents), runtime: existing.runtime,
206 }
207 }
208 return result
209 }
210 for id, existing := range a.remoteTabs {
211 if existing.ref != tab.ref || existing.state != "error" {
212 continue
213 }
214 if existing.cancel != nil {
215 result.retired = append(result.retired, existing.cancel)
216 }
217 delete(a.remoteTabs, id)
218 a.remoteTabLayout.order = removeRemoteTabOrderID(a.remoteTabLayout.order, id)
219 a.forgetRemoteBrowserExecutor(id)
220 }
221 tab.modelSeq = remoteTabModelSeq.Add(1)
222 a.remoteTabs[tab.id] = tab
223 a.remoteTabLayout.order = append(a.remoteTabLayout.order, tab.id)
224 return result
225 }
226
227 // commitRemoteTabOpenRegistration applies a reused shell's requested identity
228 // only after the single-surface visibility transaction has succeeded. Until
229 // then the persisted shell and Serve remain aligned on the previous session.
230 func (a *App) commitRemoteTabOpenRegistration(registration *remoteTabOpenRegistration, hostLabel string, opts RemoteTabOpenOptions) bool {
231 if registration.reuseID == "" {
232 return false
233 }
234 a.remoteTabMu.Lock()
235 existing := a.remoteTabs[registration.reuseID]
236 if existing == nil {
237 a.remoteTabMu.Unlock()
238 return false
239 }
240 a.remoteTabMu.Unlock()
241 if !existing.selectionMu.TryLock() {
242 a.remoteTabMu.Lock()
243 defer a.remoteTabMu.Unlock()
244 if a.remoteTabs[registration.reuseID] != existing {
245 return false
246 }
247 existing.hostLabel = hostLabel
248 if registration.selection != nil {
249 registration.selection.deferred = true
250 registration.selection.revision = 0
251 registration.selection.identityCommitted = false
252 registration.selection.previous = nil
253 existing.pendingSelection = registration.selection
254 }
255 return true
256 }
257 defer existing.selectionMu.Unlock()
258 existing.routeEventMu.Lock()
259 defer existing.routeEventMu.Unlock()
260 a.remoteTabMu.Lock()
261 defer a.remoteTabMu.Unlock()
262 if a.remoteTabs[registration.reuseID] != existing {
263 return false
264 }
265 existing.hostLabel = hostLabel
266 if registration.selection != nil {
267 registration.reuseBlank = existing.session.reset
268 registration.previousSelection = &remoteTabOpenSelection{
269 session: existing.session, topicTitle: existing.topicTitle,
270 currentPath: existing.routing.currentPath,
271 pending: cloneRemotePendingEvents(existing.pendingEvents), runtime: existing.runtime,
272 }
273 // A ready selection commits its provisional identity before its async
274 // /resume starts. If another click wins first, restore the snapshot Serve
275 // still owns before committing the newer provisional identity.
276 pending := existing.pendingSelection
277 if pending != nil && pending.identityCommitted && pending.previous != nil {
278 restoreRemoteTabOpenSelectionLocked(existing, pending.previous)
279 registration.previousSelection = pending.previous
280 registration.reuseBlank = pending.previous.session.reset
281 }
282 existing.selectionRevision++
283 registration.selection.revision = existing.selectionRevision
284 registration.selection.reuseBlank = registration.reuseBlank
285 registration.selection.previous = registration.previousSelection
286 if registration.previousSelection != nil {
287 registration.previousSelection.revision = existing.selectionRevision
288 }
289 if existing.state == "connecting" || existing.state == "reconnecting" {
290 registration.selection.deferred = true
291 existing.pendingSelection = registration.selection
292 return true
293 }
294 existing.pendingSelection = nil
295 }
296 if registration.commitSelection {
297 existing.session.newSession = opts.NewSession
298 existing.session.name = strings.TrimSpace(opts.SessionName)
299 existing.session.path = strings.TrimSpace(opts.SessionPath)
300 existing.session.sessionID = strings.TrimSpace(opts.SessionID)
301 if title := strings.TrimSpace(opts.SessionTitle); title != "" {
302 existing.topicTitle = title
303 }
304 if existing.session.newSession {
305 commitRemoteTabAttachRoute(existing, "", true)
306 } else if route := remoteSessionIdentityRoute(existing.session.path, existing.session.sessionID); route != "" {
307 // A ready tab commits the route ahead of its async /resume; gate
308 // commands until that resume settles. Re-selecting the confirmed
309 // current session is not a switch and must not enter the gate.
310 switching := existing.state == "ready" && existing.routing.currentPath != route
311 commitRemoteTabAttachRoute(existing, route, false)
312 if switching {
313 existing.routing.rehydratingPath = route
314 }
315 }
316 if existing.state == "ready" {
317 registration.selection.identityCommitted = true
318 existing.pendingSelection = registration.selection
319 }
320 existing.err = ""
321 }
322 if registration.revive {
323 existing.state = "connecting"
324 existing.err = ""
325 }
326 return true
327 }
328
329 // OpenRemoteProjectTab registers the project (idempotent), opens an in-app
330 // tab for the remote workspace, and returns its meta immediately. The remote
331 // Serve bootstrap runs in the background: a first run downloads/installs the
332 // CLI and can take minutes, so the surface follows progress through
333 // remote-tab:{id}:state events instead of this promise.
334 func (a *App) OpenRemoteProjectTab(hostID, workspace string, opts RemoteTabOpenOptions) (TabMeta, error) {
335 a.singleSurfaceMu.Lock()
336 defer a.singleSurfaceMu.Unlock()
337 a.tabSelectionMu.Lock()
338 defer a.tabSelectionMu.Unlock()
339
340 hostID = strings.TrimSpace(hostID)
341 workspace = strings.TrimSpace(workspace)
342 if hostID == "" || workspace == "" {
343 return TabMeta{}, fmt.Errorf("remote project tab: host and workspace are required")
344 }
345 cfg, err := config.Load()
346 if err != nil {
347 return TabMeta{}, err
348 }
349 host, ok := cfg.RemoteHost(hostID)
350 if !ok {
351 return TabMeta{}, fmt.Errorf("remote host %q is not configured", hostID)
352 }
353 if err := a.snapshotActiveLocalBeforeRemote(); err != nil {
354 return TabMeta{}, err
355 }
356 // The pin registry collapses overlapping paths into the existing group:
357 // whatever nested path the caller asked for, the tab must land on the
358 // canonical workspace so tabs and serves stay one-per-group.
359 proj, err := a.AddRemoteProject(hostID, workspace)
360 if err != nil {
361 return TabMeta{}, err
362 }
363 workspace = proj.Workspace
364
365 ref := RemoteTabRef{HostID: hostID, Workspace: workspace}
366 tabID := newTabID()
367 model := ""
368 if host.CredentialProxyEnabled() {
369 model = resolveNewSessionModel(cfg)
370 }
371 title := strings.TrimSpace(opts.SessionTitle)
372 if title == "" {
373 title = remoteWorkspaceName(workspace)
374 }
375 tab := &remoteTab{
376 id: tabID, ref: ref, state: "connecting",
377 session: remoteTabSessionState{newSession: opts.NewSession, name: strings.TrimSpace(opts.SessionName), path: strings.TrimSpace(opts.SessionPath), sessionID: strings.TrimSpace(opts.SessionID)},
378 hostLabel: host.Name, topicTitle: title, model: model,
379 routing: remoteTabSessionRouting{currentPath: remoteSessionIdentityRoute(opts.SessionPath, opts.SessionID), running: map[string]bool{}},
380 }
381
382 // Reuse-or-insert is atomic so concurrent opens cannot create two sessions.
383 registration := a.registerRemoteTabOpen(tab, host.Name, opts)
384 for _, cancel := range registration.retired {
385 cancel()
386 }
387 if registration.reuseID != "" {
388 _, ok := a.remoteTabMetaSnapshot(registration.reuseID)
389 if !ok {
390 return TabMeta{}, fmt.Errorf("remote tab %q closed while opening", registration.reuseID)
391 }
392 _, err = a.keepOnlyRemoteVisibleTab(registration.reuseID)
393 if err != nil {
394 return TabMeta{}, err
395 }
396 if !a.commitRemoteTabOpenRegistration(&registration, host.Name, opts) {
397 return TabMeta{}, fmt.Errorf("remote tab %q closed while opening", registration.reuseID)
398 }
399
400 // Apply the requested session transition only after the visible-surface
401 // transaction succeeds. A snapshot failure must leave the remote Serve's
402 // current conversation untouched so retrying the navigation is safe.
403 if registration.revive {
404 a.emitRemoteTabState(registration.reuseID, "connecting", "")
405 a.goRemoteTabSafe("remoteTabServe", func() { a.bootstrapRemoteTab(registration.reuseID, hostID, workspace) })
406 } else if registration.selection != nil && registration.selection.deferred {
407 // The reconnect/attach path applies the latest selection after ready.
408 } else if name := strings.TrimSpace(opts.SessionName); name != "" || strings.TrimSpace(opts.SessionPath) != "" || strings.TrimSpace(opts.SessionID) != "" {
409 a.resumeRemoteTabOpenAsync(registration.reuseID, name, opts.SessionPath, opts.SessionTitle, registration.previousSelection)
410 } else {
411 // Reuse the pending blank like EnsureBlankTab does locally; only
412 // reset again once the current session earned content.
413 if opts.NewSession && !registration.reuseBlank {
414 if err := a.resetRemoteTabSession(registration.reuseID); err != nil {
415 return TabMeta{}, err
416 }
417 }
418 }
419 meta, ok := a.remoteTabMetaSnapshot(registration.reuseID)
420 if !ok {
421 return TabMeta{}, fmt.Errorf("remote tab %q closed while opening", registration.reuseID)
422 }
423 a.activateRemoteTab(registration.reuseID, meta)
424 a.saveTabsFromRemote()
425 return meta, nil
426 }
427
428 a.emitRemoteTabState(tabID, "connecting", "")
429 _, ok = a.remoteTabMetaSnapshot(tabID)
430 if !ok {
431 return TabMeta{}, fmt.Errorf("remote tab %q closed while opening", tabID)
432 }
433 meta, err := a.keepOnlyRemoteVisibleTab(tabID)
434 if err != nil {
435 _ = a.closeRemoteTabRegistration(tabID, true)
436 return TabMeta{}, err
437 }
438 a.activateRemoteTab(tabID, meta)
439 a.goRemoteTabSafe("remoteTabServe", func() { a.bootstrapRemoteTab(tabID, hostID, workspace) })
440 // Persist after activation so the file records the highlighted remote id.
441 a.saveTabsFromRemote()
442 return meta, nil
443 }
444
445 // restoreRemoteTabShells rebuilds disconnected registry entries from the
446 // persisted tab file so remote tabs survive a restart. Shells never connect
447 // on their own: activating one (SetActiveTab) or opening its project
448 // bootstraps the reconnect, which lands in a fresh blank session.
449 func (a *App) restoreRemoteTabShells(f desktopTabsFile) {
450 if len(f.RemoteTabs) == 0 {
451 return
452 }
453 // Local ids are snapshotted under a.mu BEFORE taking remoteTabMu — the
454 // save path locks in the a.mu → tabsSaveMu → remoteTabMu order, so this
455 // function must never hold remoteTabMu while wanting a.mu.
456 a.mu.RLock()
457 localIDs := make(map[string]bool, len(a.tabs))
458 for id := range a.tabs {
459 localIDs[id] = true
460 }
461 a.mu.RUnlock()
462
463 cfg, cfgErr := config.Load()
464 a.remoteTabMu.Lock()
465 if a.remoteTabs == nil {
466 a.remoteTabs = map[string]*remoteTab{}
467 }
468 a.remoteTabLayout.stripOrder = append([]string(nil), f.TabOrder...)
469 restoredIDs := make(map[string]bool, len(f.RemoteTabs))
470 for _, entry := range f.RemoteTabs {
471 id := strings.TrimSpace(entry.ID)
472 hostID := strings.TrimSpace(entry.HostID)
473 ws := strings.TrimSpace(entry.Workspace)
474 if id == "" || hostID == "" || ws == "" || localIDs[id] || a.remoteTabs[id] != nil {
475 continue
476 }
477 hostLabel, model := hostID, ""
478 if cfgErr == nil {
479 if host, ok := cfg.RemoteHost(hostID); ok {
480 if name := strings.TrimSpace(host.Name); name != "" {
481 hostLabel = name
482 }
483 if host.CredentialProxyEnabled() {
484 model = strings.TrimSpace(entry.Model)
485 }
486 }
487 }
488 sessionName := strings.TrimSpace(entry.SessionName)
489 sessionPath := strings.TrimSpace(entry.SessionPath)
490 sessionID := strings.TrimSpace(entry.SessionID)
491 title := strings.TrimSpace(entry.TopicTitle)
492 // Older builds persisted the canonical session ID as the tab title, and
493 // a legacy row's name is its basename, which the sidebar shows as the
494 // title too. Both are opaque, so drop them once an ID is present.
495 if sessionID != "" && (title == sessionID || title == sessionName) {
496 title = ""
497 }
498 if title == "" {
499 title = remoteWorkspaceName(ws)
500 }
501 route := remoteSessionIdentityRoute(sessionPath, sessionID)
502 restored := &remoteTab{
503 id: id, ref: RemoteTabRef{HostID: hostID, Workspace: ws},
504 state: "disconnected",
505 session: remoteTabSessionState{
506 newSession: entry.SessionReset || sessionName == "" && sessionPath == "",
507 name: sessionName,
508 path: sessionPath,
509 sessionID: sessionID,
510 reset: entry.SessionReset,
511 },
512 hostLabel: hostLabel, topicTitle: title, model: model, persistenceExtra: cloneDesktopJSONFields(entry.extra),
513 routing: remoteTabSessionRouting{currentPath: route, running: map[string]bool{}},
514 }
515 restored.modelSeq = remoteTabModelSeq.Add(1)
516 a.remoteTabs[id] = restored
517 restoredIDs[id] = true
518 }
519 seen := make(map[string]bool, len(restoredIDs))
520 for _, id := range f.RemoteTabOrder {
521 if restoredIDs[id] && !seen[id] {
522 a.remoteTabLayout.order = append(a.remoteTabLayout.order, id)
523 seen[id] = true
524 }
525 }
526 for _, entry := range f.RemoteTabs {
527 id := strings.TrimSpace(entry.ID)
528 if restoredIDs[id] && !seen[id] {
529 a.remoteTabLayout.order = append(a.remoteTabLayout.order, id)
530 seen[id] = true
531 }
532 }
533 a.remoteTabMu.Unlock()
534 }
535
536 // removeRemoteTabOrderID drops one id from the remote strip order.
537 func removeRemoteTabOrderID(order []string, id string) []string {
538 out := order[:0]
539 for _, existing := range order {
540 if existing != id {
541 out = append(out, existing)
542 }
543 }
544 return out
545 }
546
547 // activateRemoteTab highlights the tab in the strip and tells the frontend
548 // chrome to adopt it.
549 func (a *App) activateRemoteTab(tabID string, meta TabMeta) {
550 a.remoteTabMu.Lock()
551 a.remoteTabLayout.activeID = tabID
552 a.remoteTabMu.Unlock()
553 a.emitRemoteEvent("remote-tab:opened", meta)
554 }
555
556 // snapshotActiveLocalBeforeRemote preserves the same data-loss barrier used
557 // by local-to-local tab switches. The caller serializes cross-registry tab
558 // selection with tabSelectionMu.
559 func (a *App) snapshotActiveLocalBeforeRemote() error {
560 a.remoteTabMu.Lock()
561 remoteActive := a.remoteTabLayout.activeID != ""
562 a.remoteTabMu.Unlock()
563 if remoteActive {
564 return nil
565 }
566 a.mu.RLock()
567 active := a.tabs[a.activeTabID]
568 a.mu.RUnlock()
569 return a.snapshotTabForAction(active, "switching tabs")
570 }
571
572 // remoteTabMeta builds the frontend-facing shape of one remote tab; the
573 // create and reuse paths share it so both return identical metas. RemoteState
574 // seeds the surface before any state event arrives this run (restored shells).
575 func remoteTabMetaLocked(tab *remoteTab) TabMeta {
576 label := tab.hostLabel
577 if strings.TrimSpace(tab.model) != "" {
578 label = tab.model
579 }
580 ref := tab.ref
581 return TabMeta{
582 ID: tab.id,
583 Scope: "project",
584 WorkspaceRoot: tab.ref.Workspace,
585 WorkspaceName: remoteWorkspaceName(tab.ref.Workspace),
586 TopicID: remoteTabTopicID(tab),
587 TopicTitle: tab.topicTitle,
588 SessionPath: tab.session.path,
589 SessionID: tab.session.sessionID,
590 SessionGeneration: tab.gen,
591 Label: label,
592 Mode: "normal",
593 Active: true,
594 Cwd: tab.ref.Workspace,
595 Remote: &ref,
596 RemoteState: tab.state,
597 // Every remote tab's view is built here, so the capability answer cannot
598 // be forgotten on one path. Local tabs never reach this helper and keep
599 // the false zero value.
600 ForkTargetsSupported: remoteForkTargetsSupported(tab),
601 InteractionTargetSupported: tab.capabilities[serveCapabilityInteractionTargetV1],
602 ExtensionFormInstanceSupported: tab.capabilities[serveCapabilityExtensionFormInstanceV1],
603 Ready: tab.state == "ready",
604 Running: tab.runtime.running || tab.runtime.pendingPrompt || tab.runtime.backgroundJobs > 0,
605 TurnStartedAt: tab.runtime.turnStartedAt,
606 PendingPrompt: tab.runtime.pendingPrompt,
607 BackgroundJobs: tab.runtime.backgroundJobs,
608 CancelRequested: tab.runtime.cancelRequested,
609 Cancellable: tab.runtime.cancellable,
610 ReadOnly: tab.session.takenOver,
611 TakenOver: tab.session.takenOver,
612 }
613 }
614
615 func remoteTabTopicID(tab *remoteTab) string {
616 if tab == nil {
617 return ""
618 }
619 identity := tab.session.name
620 if sessionID := strings.TrimSpace(tab.session.sessionID); sessionID != "" {
621 identity = sessionID
622 }
623 return tab.ref.HostID + "\x00" + tab.ref.Workspace + "\x00" + identity
624 }
625
626 func (a *App) remoteTabMetaSnapshot(tabID string) (TabMeta, bool) {
627 a.remoteTabMu.Lock()
628 defer a.remoteTabMu.Unlock()
629 tab := a.remoteTabs[tabID]
630 if tab == nil {
631 return TabMeta{}, false
632 }
633 return remoteTabMetaLocked(tab), true
634 }
635
636 // bootstrapRemoteTab drives one remote tab to a terminal state: ensure the
637 // SSH connection, ensure the remote Serve + loopback tunnel, then report
638 // ready (or the failure) on the tab's state channel.
639 func (a *App) bootstrapRemoteTab(tabID, hostID, workspace string) {
640 // Idempotence guard: a concurrent reattach may have brought this tab to
641 // ready while the open call was still in flight — bootstrapping again
642 // would re-enter the session and stack a second pump.
643 a.remoteTabMu.Lock()
644 tabState := ""
645 if tab := a.remoteTabs[tabID]; tab != nil {
646 tabState = tab.state
647 }
648 a.remoteTabMu.Unlock()
649 if tabState == "ready" {
650 return
651 }
652 rt, err := a.remoteRT()
653 if err != nil {
654 a.emitRemoteTabState(tabID, "error", err.Error())
655 return
656 }
657 // Connect is idempotent: an already connecting/connected host returns
658 // nil, a stopped generation is replaced with a fresh dial.
659 if err := rt.Connect(hostID); err != nil {
660 a.emitRemoteTabState(tabID, "error", err.Error())
661 return
662 }
663 if err := waitForRemoteHost(rt, hostID, 60*time.Second); err != nil {
664 a.emitRemoteTabState(tabID, "error", err.Error())
665 return
666 }
667 ctx := a.bootContext()
668 if ctx == nil {
669 ctx = context.Background()
670 }
671 view, token, err := rt.EnsureServer(ctx, hostID, workspace)
672 if err != nil {
673 a.emitRemoteTabState(tabID, "error", err.Error())
674 return
675 }
676 if view.State != "ready" || view.LocalURL == "" {
677 msg := view.Error
678 if msg == "" {
679 msg = view.Message
680 }
681 if msg == "" {
682 msg = "remote serve did not report a local URL"
683 }
684 a.emitRemoteTabState(tabID, "serve_down", msg)
685 return
686 }
687 a.remoteTabMu.Lock()
688 openTab := a.remoteTabs[tabID]
689 if openTab == nil {
690 a.remoteTabMu.Unlock()
691 return // closed while the bootstrap was in flight
692 }
693 opts := RemoteTabOpenOptions{NewSession: openTab.session.newSession, SessionName: openTab.session.name, SessionPath: openTab.session.path, SessionID: openTab.session.sessionID, SessionTitle: openTab.topicTitle}
694 a.remoteTabMu.Unlock()
695 // ctx outlives the call: the pump derives from it, while the handshake
696 // and session entry inside run under a bounded sub-context.
697 entered, err := a.attachRemoteTabServe(ctx, tabID, view.LocalURL, token, view.InstanceID, opts)
698 if err != nil {
699 // Pump failures publish their own reconnecting/error state. Only a
700 // pre-attach failure should transition the original connecting shell.
701 a.remoteTabMu.Lock()
702 current := a.remoteTabs[tabID]
703 connecting := current != nil && current.state == "connecting"
704 a.remoteTabMu.Unlock()
705 if connecting {
706 a.emitRemoteTabState(tabID, "error", err.Error())
707 }
708 return
709 }
710 a.remoteTabMu.Lock()
711 openTab = a.remoteTabs[tabID]
712 if openTab == nil {
713 a.remoteTabMu.Unlock()
714 return
715 }
716 gen := openTab.gen
717 if openTab.publication.attachedGen != gen || openTab.state != "connecting" {
718 a.remoteTabMu.Unlock()
719 return
720 }
721 openTab.session.reset = entered && opts.NewSession
722 freshSession := openTab.session.reset
723 if freshSession {
724 // A bootstrapped fresh session carries the localized default title,
725 // same as the live-tab reset path.
726 openTab.topicTitle = a.localizedDefaultTopicTitle()
727 }
728 a.remoteTabMu.Unlock()
729 if !a.publishRemoteTabAttachedReady(tabID, gen) {
730 return
731 }
732 if freshSession {
733 // A fresh session has no transcript in /sessions until its first save.
734 // The ready-only event does not refresh that listing, so publish the
735 // current ready meta in route/status order to prevent stale overwrites.
736 openTab.routeEventMu.Lock()
737 a.remoteTabMu.Lock()
738 current := a.remoteTabs[tabID]
739 if current != openTab || current.gen != gen || current.state != "ready" {
740 a.remoteTabMu.Unlock()
741 openTab.routeEventMu.Unlock()
742 return
743 }
744 meta := remoteTabMetaLocked(current)
745 a.remoteTabMu.Unlock()
746 a.emitRemoteEvent("remote-tab:updated", meta)
747 openTab.routeEventMu.Unlock()
748 }
749 // The confirmed /events pump makes the session usable without losing prompts.
750 // Saving the explorer default is auxiliary and cannot downgrade a healthy tab.
751 _ = a.saveLastRemoteWorkspace(hostID, workspace)
752 }
753
754 // waitForRemoteHost polls the kernel until the host is usable. The frontend
755 // has waitForRemoteConnection over status events; this is the same contract
756 // server-side for cold OpenRemoteProjectTab calls.
757 func waitForRemoteHost(rt remoteKernel, hostID string, timeout time.Duration) error {
758 deadline := time.Now().Add(timeout)
759 for {
760 for _, s := range rt.Statuses() {
761 if s.HostID != hostID {
762 continue
763 }
764 switch s.State {
765 case "connected", "degraded":
766 return nil
767 case "stopped":
768 if s.Error != "" {
769 return fmt.Errorf("remote host %q: %s", hostID, s.Error)
770 }
771 return fmt.Errorf("remote host %q stopped", hostID)
772 }
773 }
774 if time.Now().After(deadline) {
775 return fmt.Errorf("remote host %q: connection timed out", hostID)
776 }
777 time.Sleep(250 * time.Millisecond)
778 }
779 }
780
781 // remoteWorkspaceName is posix-safe (remote paths on a Windows host must not
782 // go through filepath).
783 func remoteWorkspaceName(ws string) string {
784 trimmed := strings.TrimRight(strings.TrimSpace(ws), "/")
785 if trimmed == "" || trimmed == "~" {
786 return "~"
787 }
788 if i := strings.LastIndex(trimmed, "/"); i >= 0 {
789 return trimmed[i+1:]
790 }
791 return trimmed
792 }
793
793 lines GO