返回 DeepSeek-Reasonix
remote_tab_review_regressions_test.go
根目录 / desktop / remote_tab_review_regressions_test.go
1 package main
2
3 import (
4 "encoding/json"
5 "errors"
6 "io"
7 "net/http"
8 "net/http/httptest"
9 "strings"
10 "sync"
11 "testing"
12 "time"
13
14 "reasonix/internal/config"
15 )
16
17 func TestRemoteTabServeDownSavedSessionClearsPendingBeforeDelayedMarker(t *testing.T) {
18 const oldPath = "/sessions/old.jsonl"
19 const savedPath = "/sessions/saved.jsonl"
20 feed := make(chan string, 1)
21 fs := newFakeServe(t, "s3cret", []serveSessionEntry{
22 {Name: "old", Path: oldPath, Title: "Old", Current: true},
23 {Name: "saved", Path: savedPath, Title: "Saved"},
24 })
25 kernel := &fakeRemoteKernel{
26 statuses: []RemoteConnectionStatusView{{HostID: "box", State: "connected"}},
27 ensureView: RemoteServerView{HostID: "box", State: "ready", LocalURL: fs.server.URL}, ensureToken: "s3cret",
28 }
29 seedBridgeTestHost(t, "box")
30 log := &eventLog{}
31 a := &App{remoteRuntime: kernel, remoteEventHook: log.add}
32 cleanupRemoteTabPumps(t, a)
33 meta := openReadyRemoteTab(t, a, RemoteTabOpenOptions{SessionName: "old", SessionPath: oldPath})
34
35 a.remoteTabMu.Lock()
36 tab := a.remoteTabs[meta.ID]
37 if tab.cancel != nil {
38 tab.cancel()
39 }
40 tab.gen++
41 tab.cancel, tab.client, tab.base, tab.token = nil, nil, "", ""
42 tab.state = "serve_down"
43 tab.pendingEvents = map[string]json.RawMessage{
44 "approval_request:old": json.RawMessage(`{"kind":"approval_request","approval":{"id":"old"}}`),
45 }
46 tab.runtime = remoteTabRuntimeState{pendingPrompt: true, cancellable: true}
47 a.remoteTabMu.Unlock()
48 fs.mu.Lock()
49 fs.eventFeed = feed
50 fs.mu.Unlock()
51
52 if _, err := a.OpenRemoteProjectTab("box", "~/app", RemoteTabOpenOptions{SessionName: "saved", SessionPath: savedPath, SessionTitle: "Saved"}); err != nil {
53 t.Fatal(err)
54 }
55 waitForTabState(t, a, meta.ID, "ready")
56 a.remoteTabMu.Lock()
57 path, pending, prompt := tab.routing.currentPath, len(tab.pendingEvents), tab.runtime.pendingPrompt
58 a.remoteTabMu.Unlock()
59 if path != savedPath || pending != 0 || prompt {
60 t.Fatalf("saved attach route/pending/prompt = %q/%d/%v, want %q/0/false", path, pending, prompt, savedPath)
61 }
62
63 eventPrefix := "remote-tab:" + meta.ID + ":event"
64 before := log.count(eventPrefix)
65 feed <- `{"kind":"session_changed","sessionPath":"/sessions/saved.jsonl","sessionCurrent":true}`
66 waitForRemoteEventCount(t, log, eventPrefix, before+1)
67 a.remoteTabMu.Lock()
68 pending, prompt = len(tab.pendingEvents), tab.runtime.pendingPrompt
69 a.remoteTabMu.Unlock()
70 if pending != 0 || prompt {
71 t.Fatalf("delayed saved-session marker restored stale prompt: pending=%d prompt=%v", pending, prompt)
72 }
73 }
74
75 func TestExternalResumeRefreshesAdoptedSessionTitle(t *testing.T) {
76 const firstPath = "/sessions/first.jsonl"
77 const nextPath = "/sessions/next.jsonl"
78 feed := make(chan string, 1)
79 fs := newFakeServe(t, "s3cret", []serveSessionEntry{{Name: "first", Path: firstPath, Title: "First title", Current: true}})
80 kernel := &fakeRemoteKernel{
81 statuses: []RemoteConnectionStatusView{{HostID: "box", State: "connected"}},
82 ensureView: RemoteServerView{HostID: "box", State: "ready", LocalURL: fs.server.URL}, ensureToken: "s3cret",
83 }
84 seedBridgeTestHost(t, "box")
85 log := &eventLog{}
86 a := &App{remoteRuntime: kernel, remoteEventHook: log.add}
87 cleanupRemoteTabPumps(t, a)
88 fs.mu.Lock()
89 fs.eventFeed = feed
90 fs.mu.Unlock()
91 meta := openReadyRemoteTab(t, a, RemoteTabOpenOptions{SessionName: "first", SessionPath: firstPath})
92 fs.mu.Lock()
93 fs.sessions = []serveSessionEntry{{Name: "next", Path: nextPath, Title: "Next title", Current: true}}
94 fs.mu.Unlock()
95
96 eventPrefix := "remote-tab:" + meta.ID + ":event"
97 before := log.count(eventPrefix)
98 feed <- `{"kind":"session_changed","sessionPath":"/sessions/next.jsonl","sessionCurrent":true}`
99 waitForRemoteEventCount(t, log, eventPrefix, before+1)
100 deadline := time.Now().Add(2 * time.Second)
101 for {
102 a.remoteTabMu.Lock()
103 title, path := a.remoteTabs[meta.ID].topicTitle, a.remoteTabs[meta.ID].routing.currentPath
104 a.remoteTabMu.Unlock()
105 if title == "Next title" && path == nextPath {
106 break
107 }
108 if time.Now().After(deadline) {
109 t.Fatalf("externally adopted title/path = %q/%q, want Next title/%q", title, path, nextPath)
110 }
111 time.Sleep(time.Millisecond)
112 }
113 }
114
115 func TestRemoteAttachRetiringSessionConflictKeepsCurrentReady(t *testing.T) {
116 const currentPath = "/sessions/current.jsonl"
117 fs := newFakeServe(t, "s3cret", []serveSessionEntry{
118 {Name: "current", Path: currentPath, Title: "Current title", Current: true},
119 {Name: "retiring", Path: "/sessions/retiring.jsonl", Title: "Retiring title"},
120 })
121 fs.mu.Lock()
122 fs.failEnter = "session is finishing background teardown; retry shortly"
123 fs.mu.Unlock()
124 kernel := &fakeRemoteKernel{
125 statuses: []RemoteConnectionStatusView{{HostID: "box", State: "connected"}},
126 ensureView: RemoteServerView{HostID: "box", State: "ready", LocalURL: fs.server.URL}, ensureToken: "s3cret",
127 }
128 seedBridgeTestHost(t, "box")
129 a := &App{remoteRuntime: kernel}
130 cleanupRemoteTabPumps(t, a)
131 meta := openReadyRemoteTab(t, a, RemoteTabOpenOptions{SessionName: "retiring", SessionPath: "/sessions/retiring.jsonl"})
132 a.remoteTabMu.Lock()
133 tab := a.remoteTabs[meta.ID]
134 state, path, title := tab.state, tab.routing.currentPath, tab.topicTitle
135 a.remoteTabMu.Unlock()
136 if state != "ready" || path != currentPath || title != "Current title" {
137 t.Fatalf("soft attach state/path/title = %q/%q/%q, want ready/%q/Current title", state, path, title, currentPath)
138 }
139 }
140
141 func TestRemoteResumeTransportFailureReconcilesCommittedTarget(t *testing.T) {
142 const oldPath = "/sessions/old.jsonl"
143 const targetPath = "/sessions/target.jsonl"
144 seedBridgeTestHost(t, "box")
145 postCalls := 0
146 client := &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
147 switch {
148 case req.Method == http.MethodPost && req.URL.Path == "/resume":
149 postCalls++
150 // Model a response lost after Serve has already committed targetPath.
151 return nil, io.ErrUnexpectedEOF
152 case req.Method == http.MethodGet && req.URL.Path == "/sessions":
153 body := `[{"name":"target","path":"/sessions/target.jsonl","title":"Target","current":true}]`
154 return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
155 default:
156 return nil, errors.New("unexpected request")
157 }
158 })}
159 tab := &remoteTab{
160 id: "remote-1", ref: RemoteTabRef{HostID: "box", Workspace: "~/app"}, state: "ready",
161 client: client, base: "http://127.0.0.1:43210", gen: 7,
162 topicTitle: "Old",
163 session: remoteTabSessionState{name: "old", path: oldPath},
164 routing: remoteTabSessionRouting{currentPath: oldPath, running: map[string]bool{}},
165 }
166 a := &App{remoteTabs: map[string]*remoteTab{tab.id: tab}}
167 a.resumeRemoteTabSessionPath(tab.id, "target", targetPath, "Target")
168 a.remoteTabMu.Lock()
169 state, path, sessionPath, title := tab.state, tab.routing.currentPath, tab.session.path, tab.topicTitle
170 rehydrating := tab.routing.rehydratingPath
171 a.remoteTabMu.Unlock()
172 if postCalls != 1 || state != "ready" || path != targetPath || sessionPath != targetPath || title != "Target" || rehydrating != "" {
173 t.Fatalf("reconciled resume calls/state/route/session/title/rehydrating = %d/%q/%q/%q/%q/%q", postCalls, state, path, sessionPath, title, rehydrating)
174 }
175 }
176
177 func TestRemoteResumeReplayStopsAfterLaterSessionAdoption(t *testing.T) {
178 const oldPath = "/sessions/old.jsonl"
179 const targetPath = "/sessions/target.jsonl"
180 const laterPath = "/sessions/later.jsonl"
181 client := &http.Client{}
182 tab := &remoteTab{
183 id: "remote-1", state: "ready", client: client, gen: 7,
184 session: remoteTabSessionState{name: "target", path: targetPath},
185 routing: remoteTabSessionRouting{
186 currentPath: targetPath, rehydratingPath: targetPath, running: map[string]bool{},
187 rehydratingFrames: []json.RawMessage{
188 json.RawMessage(`{"kind":"text","text":"target-first","sessionPath":"/sessions/target.jsonl"}`),
189 json.RawMessage(`{"kind":"text","text":"target-second","sessionPath":"/sessions/target.jsonl"}`),
190 },
191 },
192 }
193 log := &eventLog{}
194 a := &App{remoteTabs: map[string]*remoteTab{tab.id: tab}}
195 firstFrameEntered := make(chan struct{})
196 releaseFirstFrame := make(chan struct{})
197 var firstFrameOnce sync.Once
198 a.remoteEventHook = func(name string, payload any) {
199 log.add(name, payload)
200 if name == "remote-tab:"+tab.id+":event" {
201 data, _ := json.Marshal(payload)
202 if strings.Contains(string(data), "target-first") {
203 firstFrameOnce.Do(func() { close(firstFrameEntered) })
204 <-releaseFirstFrame
205 }
206 }
207 }
208 route := remoteTabProvisionalResume{targetPath: targetPath, previousPath: oldPath, active: true}
209 resumeDone := make(chan struct{})
210 go func() {
211 a.publishRemoteTabResumeReady(tab.id, tab, client, tab.gen, route)
212 close(resumeDone)
213 }()
214 select {
215 case <-firstFrameEntered:
216 case <-time.After(2 * time.Second):
217 t.Fatal("first replay frame did not reach publication")
218 }
219 adoptDone := make(chan struct{})
220 go func() {
221 a.adoptRemoteTabFrameCurrent(tab.id, tab.gen, laterPath, true)
222 close(adoptDone)
223 }()
224 select {
225 case <-adoptDone:
226 t.Fatal("later route adoption overtook an in-flight frame publication")
227 case <-time.After(100 * time.Millisecond):
228 }
229 close(releaseFirstFrame)
230 select {
231 case <-adoptDone:
232 case <-time.After(2 * time.Second):
233 t.Fatal("later route adoption did not complete after publication")
234 }
235 select {
236 case <-resumeDone:
237 case <-time.After(2 * time.Second):
238 t.Fatal("resume replay did not stop after later adoption")
239 }
240 events := strings.Join(log.recorded(), "\n")
241 secondFrame := strings.Index(events, "target-second")
242 laterReady := strings.LastIndex(events, "remote-tab:"+tab.id+":state")
243 if !strings.Contains(events, "target-first") || secondFrame < 0 || laterReady < secondFrame {
244 t.Fatalf("later adoption overtook the ordered replay: %s", events)
245 }
246 a.remoteTabMu.Lock()
247 path, rehydrating := tab.routing.currentPath, tab.routing.rehydratingPath
248 a.remoteTabMu.Unlock()
249 if path != laterPath || rehydrating != "" {
250 t.Fatalf("later route/rehydration = %q/%q, want %q/empty", path, rehydrating, laterPath)
251 }
252 }
253
254 func TestRemoteResumeReplaysPromptArrivingDuringDrain(t *testing.T) {
255 const targetPath = "/sessions/target.jsonl"
256 client := &http.Client{}
257 tab := &remoteTab{
258 id: "remote-1", state: "ready", client: client, gen: 7,
259 routing: remoteTabSessionRouting{
260 currentPath: targetPath, rehydratingPath: targetPath, running: map[string]bool{},
261 rehydratingFrames: []json.RawMessage{
262 json.RawMessage(`{"kind":"text","text":"drain-start","sessionPath":"/sessions/target.jsonl"}`),
263 },
264 },
265 }
266 firstPublished := make(chan struct{})
267 release := make(chan struct{})
268 log := &eventLog{}
269 a := &App{remoteTabs: map[string]*remoteTab{tab.id: tab}}
270 a.remoteEventHook = func(name string, payload any) {
271 log.add(name, payload)
272 data, _ := json.Marshal(payload)
273 if name == "remote-tab:"+tab.id+":event" && strings.Contains(string(data), "drain-start") {
274 close(firstPublished)
275 <-release
276 }
277 }
278 done := make(chan struct{})
279 go func() {
280 a.publishRemoteTabResumeReady(tab.id, tab, client, tab.gen, remoteTabProvisionalResume{targetPath: targetPath, active: true})
281 close(done)
282 }()
283 select {
284 case <-firstPublished:
285 case <-time.After(time.Second):
286 t.Fatal("resume drain did not publish its first frame")
287 }
288 // The aggregate snapshot has already copied an empty prompt set. A prompt
289 // arriving now must therefore reach the frontend through the fenced drain.
290 a.remoteTabMu.Lock()
291 snapshotPending := len(tab.pendingEvents)
292 a.remoteTabMu.Unlock()
293 if snapshotPending != 0 {
294 t.Fatalf("snapshot pending events = %d, want 0", snapshotPending)
295 }
296 approval := json.RawMessage(`{"kind":"approval_request","approval":{"id":"during-drain"},"sessionPath":"/sessions/target.jsonl","sessionCurrent":true}`)
297 if !a.bufferRemoteTabResumeFrame(tab.id, tab.gen, targetPath, "approval_request", approval) {
298 t.Fatal("prompt arriving during drain was not buffered")
299 }
300 close(release)
301 select {
302 case <-done:
303 case <-time.After(time.Second):
304 t.Fatal("resume drain did not finish")
305 }
306 events := strings.Join(log.recorded(), "\n")
307 if !strings.Contains(events, `"id":"during-drain"`) {
308 t.Fatalf("prompt arriving after snapshot was not replayed: %s", events)
309 }
310 a.remoteTabMu.Lock()
311 pending, rehydrating := len(tab.pendingEvents), tab.routing.rehydratingPath
312 a.remoteTabMu.Unlock()
313 if pending != 1 || rehydrating != "" {
314 t.Fatalf("post-drain pending/rehydrating = %d/%q, want 1/empty", pending, rehydrating)
315 }
316 }
317
318 func TestRemoteRotationResponseCannotOverwriteLaterRouteAdoption(t *testing.T) {
319 const oldPath = "/sessions/old.jsonl"
320 const responsePath = "/sessions/response.jsonl"
321 const laterPath = "/sessions/later.jsonl"
322 requestEntered := make(chan struct{})
323 releaseResponse := make(chan struct{})
324 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
325 if r.Method != http.MethodPost || r.URL.Path != "/new" {
326 http.NotFound(w, r)
327 return
328 }
329 close(requestEntered)
330 <-releaseResponse
331 w.Header().Set("X-Reasonix-Session-Path", responsePath)
332 w.WriteHeader(http.StatusNoContent)
333 }))
334 defer server.Close()
335 tab := &remoteTab{
336 id: "remote-1", state: "ready", client: server.Client(), base: server.URL, gen: 7,
337 session: remoteTabSessionState{name: "old", path: oldPath},
338 routing: remoteTabSessionRouting{currentPath: oldPath, running: map[string]bool{}},
339 }
340 a := &App{remoteTabs: map[string]*remoteTab{tab.id: tab}}
341 done := make(chan error, 1)
342 go func() { done <- a.rotateRemoteTabSession(tab.id, "/new") }()
343 select {
344 case <-requestEntered:
345 case <-time.After(2 * time.Second):
346 t.Fatal("rotation request did not reach Serve")
347 }
348 a.adoptRemoteTabFrameCurrent(tab.id, tab.gen, laterPath, true)
349 close(releaseResponse)
350 select {
351 case err := <-done:
352 if err != nil {
353 t.Fatal(err)
354 }
355 case <-time.After(2 * time.Second):
356 t.Fatal("rotation did not finish")
357 }
358 a.remoteTabMu.Lock()
359 path, sessionPath := tab.routing.currentPath, tab.session.path
360 a.remoteTabMu.Unlock()
361 if path != laterPath || sessionPath == responsePath {
362 t.Fatalf("stale rotation response replaced later route: routing/session = %q/%q, want later route %q", path, sessionPath, laterPath)
363 }
364 }
365
366 func TestRemoteStatusAdoptionWaitsForFramePublication(t *testing.T) {
367 const currentPath = "/sessions/current.jsonl"
368 const laterPath = "/sessions/later.jsonl"
369 client := &http.Client{}
370 tab := &remoteTab{
371 id: "remote-1", state: "ready", client: client, gen: 7,
372 session: remoteTabSessionState{path: currentPath},
373 routing: remoteTabSessionRouting{currentPath: currentPath, running: map[string]bool{}},
374 runtime: remoteTabRuntimeState{revision: 11},
375 }
376 frameEntered := make(chan struct{})
377 releaseFrame := make(chan struct{})
378 log := &eventLog{}
379 a := &App{remoteTabs: map[string]*remoteTab{tab.id: tab}}
380 a.remoteEventHook = func(name string, payload any) {
381 log.add(name, payload)
382 if name == "remote-tab:"+tab.id+":event" {
383 close(frameEntered)
384 <-releaseFrame
385 }
386 }
387 frameDone := make(chan bool, 1)
388 go func() {
389 frame := json.RawMessage(`{"kind":"text","text":"current-frame","sessionPath":"/sessions/current.jsonl"}`)
390 frameDone <- a.publishRemoteTabFrame(tab.id, tab.gen, currentPath, "text", frame)
391 }()
392 select {
393 case <-frameEntered:
394 case <-time.After(2 * time.Second):
395 t.Fatal("current frame did not reach publication")
396 }
397 statusDone := make(chan bool, 1)
398 go func() {
399 statusDone <- a.recordRemoteTabSessionStatus(tab.id, client, tab.gen, 11, json.RawMessage(`{"sessionPath":"/sessions/later.jsonl"}`))
400 }()
401 select {
402 case <-statusDone:
403 t.Fatal("status route adoption overtook an in-flight frame publication")
404 case <-time.After(100 * time.Millisecond):
405 }
406 close(releaseFrame)
407 if !<-frameDone || !<-statusDone {
408 t.Fatal("ordered frame publication or status adoption was rejected")
409 }
410 events := strings.Join(log.recorded(), "\n")
411 frameIndex := strings.Index(events, "current-frame")
412 readyIndex := strings.LastIndex(events, "remote-tab:"+tab.id+":state")
413 if frameIndex < 0 || readyIndex < frameIndex {
414 t.Fatalf("status ready barrier overtook the current frame: %s", events)
415 }
416 a.remoteTabMu.Lock()
417 adoptedPath := tab.routing.currentPath
418 a.remoteTabMu.Unlock()
419 if adoptedPath != laterPath {
420 t.Fatalf("status route = %q, want %q", adoptedPath, laterPath)
421 }
422 }
423
424 func TestRemoteRejectedResumeReconciliationWaitsForFramePublication(t *testing.T) {
425 const previousPath = "/sessions/previous.jsonl"
426 const targetPath = "/sessions/target.jsonl"
427 const authoritativePath = "/sessions/authoritative.jsonl"
428 client := &http.Client{}
429 tab := &remoteTab{
430 id: "remote-1", state: "ready", client: client, gen: 7,
431 session: remoteTabSessionState{path: targetPath},
432 routing: remoteTabSessionRouting{
433 currentPath: targetPath, rehydratingPath: targetPath, running: map[string]bool{},
434 },
435 }
436 frameEntered := make(chan struct{})
437 releaseFrame := make(chan struct{})
438 log := &eventLog{}
439 a := &App{remoteTabs: map[string]*remoteTab{tab.id: tab}}
440 a.remoteEventHook = func(name string, payload any) {
441 log.add(name, payload)
442 if name == "remote-tab:"+tab.id+":event" {
443 close(frameEntered)
444 <-releaseFrame
445 }
446 }
447 frameDone := make(chan bool, 1)
448 go func() {
449 frame := json.RawMessage(`{"kind":"text","text":"target-frame","sessionPath":"/sessions/target.jsonl"}`)
450 frameDone <- a.publishRemoteTabFrameForRoute(tab.id, tab, client, tab.gen, targetPath, true, "text", frame)
451 }()
452 select {
453 case <-frameEntered:
454 case <-time.After(2 * time.Second):
455 t.Fatal("target frame did not reach publication")
456 }
457 reconcileDone := make(chan struct{})
458 go func() {
459 route := remoteTabProvisionalResume{targetPath: targetPath, previousPath: previousPath, active: true}
460 a.reconcileRemoteTabRejectedResume(tab.id, tab, client, tab.gen, route, serveSessionEntry{Path: authoritativePath}, errors.New("resume response lost"))
461 close(reconcileDone)
462 }()
463 select {
464 case <-reconcileDone:
465 t.Fatal("ambiguous-resume reconciliation overtook an in-flight frame")
466 case <-time.After(100 * time.Millisecond):
467 }
468 close(releaseFrame)
469 if !<-frameDone {
470 t.Fatal("target frame was rejected before authoritative reconciliation")
471 }
472 select {
473 case <-reconcileDone:
474 case <-time.After(2 * time.Second):
475 t.Fatal("ambiguous-resume reconciliation did not complete")
476 }
477 events := strings.Join(log.recorded(), "\n")
478 frameIndex := strings.Index(events, "target-frame")
479 readyIndex := strings.LastIndex(events, "remote-tab:"+tab.id+":state")
480 if frameIndex < 0 || readyIndex < frameIndex {
481 t.Fatalf("authoritative ready barrier overtook the target frame: %s", events)
482 }
483 a.remoteTabMu.Lock()
484 currentPath := tab.routing.currentPath
485 a.remoteTabMu.Unlock()
486 if currentPath != authoritativePath {
487 t.Fatalf("reconciled route = %q, want %q", currentPath, authoritativePath)
488 }
489 }
490
491 func TestRemoteRejectedResumeReconciliationCannotOverwriteNewerAdoption(t *testing.T) {
492 const previousPath = "/sessions/previous.jsonl"
493 const targetPath = "/sessions/target.jsonl"
494 const staleAuthoritativePath = "/sessions/stale-authoritative.jsonl"
495 const newerPath = "/sessions/newer.jsonl"
496 client := &http.Client{}
497 tab := &remoteTab{
498 id: "remote-1", state: "ready", client: client, gen: 7,
499 session: remoteTabSessionState{path: targetPath},
500 routing: remoteTabSessionRouting{
501 currentPath: targetPath, rehydratingPath: targetPath, running: map[string]bool{},
502 },
503 }
504 log := &eventLog{}
505 a := &App{remoteTabs: map[string]*remoteTab{tab.id: tab}, remoteEventHook: log.add}
506 // This route marker arrives after the reconciliation query returned C but
507 // before its caller acquired the route/publication mutex.
508 a.adoptRemoteTabFrameCurrent(tab.id, tab.gen, newerPath, true)
509 eventsBefore := len(log.recorded())
510 route := remoteTabProvisionalResume{targetPath: targetPath, previousPath: previousPath, active: true}
511 a.reconcileRemoteTabRejectedResume(tab.id, tab, client, tab.gen, route, serveSessionEntry{Path: staleAuthoritativePath}, errors.New("resume response lost"))
512 a.remoteTabMu.Lock()
513 currentPath := tab.routing.currentPath
514 a.remoteTabMu.Unlock()
515 if currentPath != newerPath {
516 t.Fatalf("stale reconciliation replaced newer route with %q, want %q", currentPath, newerPath)
517 }
518 if eventsAfter := len(log.recorded()); eventsAfter != eventsBefore {
519 t.Fatalf("stale reconciliation emitted %d events after newer adoption, want 0", eventsAfter-eventsBefore)
520 }
521 }
522
523 func TestRemoteRejectedResumeReconcilesReselectedCurrentSession(t *testing.T) {
524 const currentPath = "/sessions/current.jsonl"
525 const authoritativePath = "/sessions/authoritative.jsonl"
526 client := &http.Client{}
527 tab := &remoteTab{
528 id: "remote-1", state: "ready", client: client, gen: 7,
529 session: remoteTabSessionState{path: currentPath},
530 routing: remoteTabSessionRouting{currentPath: currentPath, pathRevision: 9, running: map[string]bool{}},
531 }
532 log := &eventLog{}
533 a := &App{remoteTabs: map[string]*remoteTab{tab.id: tab}, remoteEventHook: log.add}
534 route := a.beginRemoteTabProvisionalResume(tab.id, tab, client, tab.gen, currentPath)
535 if route.active || route.pathRevision != 9 {
536 t.Fatalf("reselection route = %+v, want inactive revision 9", route)
537 }
538 a.reconcileRemoteTabRejectedResume(tab.id, tab, client, tab.gen, route, serveSessionEntry{Path: authoritativePath}, errors.New("resume response lost"))
539 a.remoteTabMu.Lock()
540 got := tab.routing.currentPath
541 a.remoteTabMu.Unlock()
542 if got != authoritativePath {
543 t.Fatalf("reselected current route = %q, want authoritative %q", got, authoritativePath)
544 }
545 if log.count("remote-tab:"+tab.id+":state") != 1 {
546 t.Fatalf("authoritative reconciliation did not publish one ready barrier: %v", log.recorded())
547 }
548 }
549
550 func TestRemoteRejectedResumeRollbackCannotMarkNewerRouteErrored(t *testing.T) {
551 const previousPath = "/sessions/previous.jsonl"
552 const targetPath = "/sessions/target.jsonl"
553 const newerPath = "/sessions/newer.jsonl"
554 client := &http.Client{}
555 tab := &remoteTab{
556 id: "remote-1", state: "ready", client: client, gen: 7,
557 session: remoteTabSessionState{path: previousPath},
558 routing: remoteTabSessionRouting{currentPath: previousPath, running: map[string]bool{}},
559 }
560 log := &eventLog{}
561 a := &App{remoteTabs: map[string]*remoteTab{tab.id: tab}, remoteEventHook: log.add}
562 route := a.beginRemoteTabProvisionalResume(tab.id, tab, client, tab.gen, targetPath)
563 a.adoptRemoteTabFrameCurrent(tab.id, tab.gen, newerPath, true)
564 eventsBefore := len(log.recorded())
565 a.reconcileRemoteTabRejectedResume(tab.id, tab, client, tab.gen, route, serveSessionEntry{Path: previousPath}, errors.New("resume response lost"))
566 a.remoteTabMu.Lock()
567 got := tab.routing.currentPath
568 a.remoteTabMu.Unlock()
569 if got != newerPath {
570 t.Fatalf("stale rollback replaced newer route with %q, want %q", got, newerPath)
571 }
572 if eventsAfter := len(log.recorded()); eventsAfter != eventsBefore {
573 t.Fatalf("stale rollback emitted %d events after newer adoption, want 0", eventsAfter-eventsBefore)
574 }
575 }
576
577 func TestRemoteReselectionSuccessCannotOverwriteNewerAdoption(t *testing.T) {
578 const previousPath = "/sessions/previous.jsonl"
579 const newerPath = "/sessions/newer.jsonl"
580 client := &http.Client{}
581 tab := &remoteTab{
582 id: "remote-1", state: "ready", client: client, gen: 7,
583 session: remoteTabSessionState{path: previousPath},
584 routing: remoteTabSessionRouting{currentPath: previousPath, pathRevision: 3, running: map[string]bool{}},
585 }
586 a := &App{remoteTabs: map[string]*remoteTab{tab.id: tab}}
587 route := a.beginRemoteTabProvisionalResume(tab.id, tab, client, tab.gen, previousPath)
588 a.adoptRemoteTabFrameCurrent(tab.id, tab.gen, newerPath, true)
589 if _, committed := a.commitRemoteTabResume(tab.id, tab, client, tab.gen, route, serveSessionEntry{Path: previousPath}, "Previous"); committed {
590 t.Fatal("late reselection success overwrote a newer route")
591 }
592 a.remoteTabMu.Lock()
593 got := tab.routing.currentPath
594 a.remoteTabMu.Unlock()
595 if got != newerPath {
596 t.Fatalf("late reselection changed route to %q, want %q", got, newerPath)
597 }
598 }
599
600 func TestRemoteResumeCommitPublicationBlocksNewerAdoption(t *testing.T) {
601 isolateDesktopUserDirs(t)
602 const targetPath = "/sessions/target.jsonl"
603 const newerPath = "/sessions/newer.jsonl"
604 client := &http.Client{}
605 tab := &remoteTab{
606 id: "remote-1", state: "ready", client: client, gen: 7,
607 session: remoteTabSessionState{path: targetPath},
608 routing: remoteTabSessionRouting{
609 currentPath: targetPath, rehydratingPath: targetPath, pathRevision: 4, running: map[string]bool{},
610 },
611 }
612 metadataEntered := make(chan struct{})
613 releaseMetadata := make(chan struct{})
614 var once sync.Once
615 a := &App{remoteTabs: map[string]*remoteTab{tab.id: tab}}
616 a.remoteEventHook = func(name string, _ any) {
617 if name == "remote-tab:updated" {
618 once.Do(func() {
619 close(metadataEntered)
620 <-releaseMetadata
621 })
622 }
623 }
624 route := remoteTabProvisionalResume{targetPath: targetPath, active: true}
625 resumeDone := make(chan bool, 1)
626 go func() {
627 resumeDone <- a.commitAndPublishRemoteTabResume(tab.id, tab, client, tab.gen, route, serveSessionEntry{Path: targetPath}, "Target")
628 }()
629 select {
630 case <-metadataEntered:
631 case <-time.After(time.Second):
632 t.Fatal("resume metadata publication did not start")
633 }
634 adoptDone := make(chan struct{})
635 go func() {
636 a.adoptRemoteTabFrameCurrent(tab.id, tab.gen, newerPath, true)
637 close(adoptDone)
638 }()
639 select {
640 case <-adoptDone:
641 t.Fatal("newer adoption overtook the in-flight resume publication")
642 case <-time.After(100 * time.Millisecond):
643 }
644 close(releaseMetadata)
645 select {
646 case committed := <-resumeDone:
647 if !committed {
648 t.Fatal("resume commit was unexpectedly rejected")
649 }
650 case <-time.After(time.Second):
651 t.Fatal("resume publication did not finish")
652 }
653 select {
654 case <-adoptDone:
655 case <-time.After(time.Second):
656 t.Fatal("newer adoption remained blocked after resume publication")
657 }
658 a.remoteTabMu.Lock()
659 path := tab.routing.currentPath
660 a.remoteTabMu.Unlock()
661 if path != newerPath {
662 t.Fatalf("foreground route = %q, want newer adoption %q", path, newerPath)
663 }
664 }
665
666 func TestRemoteAttachResponseCannotOverwriteNewerAdoption(t *testing.T) {
667 const responsePath = "/sessions/response.jsonl"
668 const newerPath = "/sessions/newer.jsonl"
669 tab := &remoteTab{
670 id: "remote-1", gen: 7, topicTitle: "Newer",
671 session: remoteTabSessionState{name: "newer", path: newerPath},
672 routing: remoteTabSessionRouting{currentPath: newerPath, pathRevision: 5, running: map[string]bool{}},
673 }
674 a := &App{remoteTabs: map[string]*remoteTab{tab.id: tab}}
675 committed := a.commitRemoteTabAttachResponse(tab.id, tab, tab.gen, 4, serveSessionEntry{
676 Name: "response", Path: responsePath, Title: "Stale response",
677 }, false)
678 if committed {
679 t.Fatal("stale attach response overwrote a newer route adoption")
680 }
681 a.remoteTabMu.Lock()
682 path, name, title := tab.routing.currentPath, tab.session.name, tab.topicTitle
683 a.remoteTabMu.Unlock()
684 if path != newerPath || name != "newer" || title != "Newer" {
685 t.Fatalf("stale attach response changed newer identity: path=%q name=%q title=%q", path, name, title)
686 }
687 }
688
689 func TestExternalSessionAdoptionResetsAndSeedsForegroundRuntime(t *testing.T) {
690 const oldPath = "/sessions/old.jsonl"
691 const targetPath = "/sessions/target.jsonl"
692 tab := &remoteTab{
693 routing: remoteTabSessionRouting{currentPath: oldPath, running: map[string]bool{targetPath: true}},
694 session: remoteTabSessionState{name: "old", path: oldPath},
695 pendingEvents: map[string]json.RawMessage{
696 "approval_request:old": json.RawMessage(`{"kind":"approval_request"}`),
697 },
698 runtime: remoteTabRuntimeState{
699 running: true, turnStartedAt: 99, backgroundJobs: 3,
700 pendingPrompt: true, cancelRequested: true, cancellable: true,
701 },
702 }
703 if !adoptRemoteTabSessionPathLocked(tab, targetPath) {
704 t.Fatal("target session was not adopted")
705 }
706 if len(tab.pendingEvents) != 0 || !tab.runtime.running || tab.runtime.turnStartedAt != 0 ||
707 tab.runtime.backgroundJobs != 0 || tab.runtime.pendingPrompt || tab.runtime.cancelRequested || !tab.runtime.cancellable {
708 t.Fatalf("adopted runtime retained old controller state: %+v pending=%d", tab.runtime, len(tab.pendingEvents))
709 }
710 }
711
712 func TestRevivedSessionSelectionWaitsForVisibilityCommit(t *testing.T) {
713 seedBridgeTestHost(t, "box")
714 if err := editUserConfig(func(c *config.Config) error { return c.SetDesktopLayoutStyle("workbench") }); err != nil {
715 t.Fatal(err)
716 }
717 const oldPath = "/sessions/old.jsonl"
718 const targetPath = "/sessions/target.jsonl"
719 remote := &remoteTab{
720 id: "remote-1", ref: RemoteTabRef{HostID: "box", Workspace: "~/app"}, state: "disconnected",
721 topicTitle: "Old title",
722 session: remoteTabSessionState{name: "old", path: oldPath},
723 routing: remoteTabSessionRouting{currentPath: oldPath, running: map[string]bool{}},
724 }
725 a := &App{
726 tabs: map[string]*WorkspaceTab{
727 "local-1": {ID: "local-1", Ctrl: &snapshotErrorSessionController{err: errors.New("snapshot failed")}},
728 },
729 remoteTabs: map[string]*remoteTab{remote.id: remote},
730 }
731 a.remoteTabLayout.activeID = remote.id
732 a.remoteTabLayout.order = []string{remote.id}
733 _, err := a.OpenRemoteProjectTab("box", "~/app", RemoteTabOpenOptions{
734 SessionName: "target", SessionPath: targetPath, SessionTitle: "Target title",
735 })
736 if err == nil || !strings.Contains(err.Error(), "snapshot failed") {
737 t.Fatalf("revived open error = %v, want visibility snapshot failure", err)
738 }
739 a.remoteTabMu.Lock()
740 state, name, sessionPath := remote.state, remote.session.name, remote.session.path
741 route, title := remote.routing.currentPath, remote.topicTitle
742 a.remoteTabMu.Unlock()
743 if state != "disconnected" || name != "old" || sessionPath != oldPath || route != oldPath || title != "Old title" {
744 t.Fatalf("failed visibility commit changed revived shell: state=%q name=%q session=%q route=%q title=%q", state, name, sessionPath, route, title)
745 }
746 }
747
748 // TestSpectatorRouteResistsForegroundCurrentMarker pins the regression where
749 // the serve foreground's sessionCurrent marker re-routed a spectator tab that
750 // had explicitly selected a mirrored session: the banner stayed on the watched
751 // session while routing (and every reclaim/submit) silently moved to the
752 // foreground, so reclaim looked successful and messages landed in the wrong
753 // transcript.
754 func TestSpectatorRouteResistsForegroundCurrentMarker(t *testing.T) {
755 const watched = "/sessions/watched.jsonl"
756 const foreground = "/sessions/foreground.jsonl"
757 client := &http.Client{}
758 tab := &remoteTab{
759 id: "remote-1", state: "ready", client: client, gen: 3,
760 session: remoteTabSessionState{path: watched, takenOver: true},
761 routing: remoteTabSessionRouting{currentPath: watched, running: map[string]bool{}},
762 }
763 log := &eventLog{}
764 a := &App{remoteTabs: map[string]*remoteTab{tab.id: tab}, remoteEventHook: log.add}
765 eventsBefore := len(log.recorded())
766
767 a.adoptRemoteTabFrameCurrent(tab.id, tab.gen, foreground, false)
768 a.remoteTabMu.Lock()
769 path, taken := tab.routing.currentPath, tab.session.takenOver
770 a.remoteTabMu.Unlock()
771 if path != watched || !taken {
772 t.Fatalf("foreground marker stole the spectator route: path=%q takenOver=%v", path, taken)
773 }
774 if eventsAfter := len(log.recorded()); eventsAfter != eventsBefore {
775 t.Fatalf("blocked adoption emitted %d events, want 0", eventsAfter-eventsBefore)
776 }
777
778 // Once the spectator pin lifts (reclaim landed or the probe cleared it),
779 // foreground rotation frames adopt again.
780 a.remoteTabMu.Lock()
781 tab.session.takenOver = false
782 a.remoteTabMu.Unlock()
783 a.adoptRemoteTabFrameCurrent(tab.id, tab.gen, foreground, false)
784 a.remoteTabMu.Lock()
785 path = tab.routing.currentPath
786 a.remoteTabMu.Unlock()
787 if path != foreground {
788 t.Fatalf("foreground adoption after the spectator pin lifted was blocked: %q", path)
789 }
790 }
791
791 lines GO