返回 DeepSeek-Reasonix
topic_activation_canonical_test.go
根目录 / desktop / topic_activation_canonical_test.go
1 package main
2
3 import (
4 "context"
5 "encoding/json"
6 "errors"
7 "os"
8 "sync"
9 "testing"
10 "time"
11
12 "reasonix/internal/control"
13 "reasonix/internal/session"
14 )
15
16 func canonicalTopicHistoryReady(t *testing.T, app *App, tabID string) session.HistoryWindowPage {
17 t.Helper()
18 req := session.HistoryWindowRequest{Anchor: "newest", Limit: 32}
19 page, err := app.SessionHistoryWindowForTab(tabID, req)
20 if err != nil {
21 t.Fatal(err)
22 }
23 if page.Status == "preparing" {
24 query, ref, err := app.canonicalSessionQuery(tabID)
25 if err != nil {
26 t.Fatal(err)
27 }
28 // TitleMessages joins this query's locator preparation, so completion
29 // supplies the readiness boundary without polling filesystem speed.
30 if _, err := query.TitleMessages(t.Context(), ref, 1); err != nil {
31 t.Fatal(err)
32 }
33 page, err = app.SessionHistoryWindowForTab(tabID, req)
34 if err != nil {
35 t.Fatal(err)
36 }
37 }
38 if page.Status != "ready" || len(page.Messages) == 0 {
39 t.Fatalf("history is not readable: status=%s messages=%d", page.Status, len(page.Messages))
40 }
41 return page
42 }
43
44 func TestCanonicalSidebarActivationReplacesRemoteSurface(t *testing.T) {
45 app, source, target, root, _ := canonicalWorkspaceOpenFixture(t)
46 app.readyHook = func() {}
47 installNoopRuntimeEvents(app, source.sink)
48 events := newActivationEventRecorder(app)
49 t.Cleanup(func() { app.shutdown(context.Background()) })
50
51 remoteCtx, cancelRemote := context.WithCancel(context.Background())
52 app.remoteTabMu.Lock()
53 app.remoteTabs = map[string]*remoteTab{
54 "remote": {id: "remote", ref: RemoteTabRef{HostID: "box", Workspace: "/work"}, state: "ready", cancel: cancelRemote},
55 }
56 app.remoteTabLayout = remoteTabLayoutState{activeID: "remote", order: []string{"remote"}, stripOrder: []string{"remote"}}
57 app.remoteTabMu.Unlock()
58
59 ref := target.Ref()
60 ticket, err := app.StartTopicActivation(TopicActivationRequest{
61 Selector: &SessionSelector{Ref: &ref}, Scope: "project", WorkspaceRoot: root,
62 TopicID: "existing-topic", SessionPath: sessionRoute(ref.SessionID), RequestID: "sidebar-local",
63 })
64 if err != nil {
65 t.Fatal(err)
66 }
67 if ticket.Meta.SessionID != ref.SessionID || ticket.Meta.WorkspaceRoot != root {
68 t.Fatalf("selected local session = %+v, want %s in %s", ticket.Meta, ref.SessionID, root)
69 }
70 if tabs := app.ListTabs(); len(tabs) == 0 {
71 t.Fatal("local tab disappeared after canonical sidebar activation")
72 } else {
73 for _, tab := range tabs {
74 if tab.Active != (tab.ID == ticket.TabID) {
75 t.Fatalf("tab activity after canonical sidebar activation = %+v", tabs)
76 }
77 }
78 }
79 events.waitFor(t, activationEventFor(ticket.RequestID, "ready"))
80 flushActivationCompletions(app)
81 if tabs := app.ListTabs(); len(tabs) != 1 || tabs[0].ID != ticket.TabID || !tabs[0].Active {
82 t.Fatalf("tabs after local activation = %+v", tabs)
83 }
84 select {
85 case <-remoteCtx.Done():
86 default:
87 t.Fatal("remote tab remained attached after selecting a local session")
88 }
89 }
90
91 func TestCanonicalTopicActivationPublishesReadableHistoryBeforeRuntime(t *testing.T) {
92 app, source, target, root, workspace := canonicalWorkspaceOpenFixture(t)
93 app.readyHook = func() {}
94 installNoopRuntimeEvents(app, source.sink)
95 events := newActivationEventRecorder(app)
96 gate := newTabBuildGate(app)
97 t.Cleanup(func() { app.shutdown(context.Background()) })
98 t.Cleanup(gate.releaseAll)
99 app.runtimeRebuildMu.Lock()
100 unlock := sync.OnceFunc(app.runtimeRebuildMu.Unlock)
101 defer unlock()
102
103 type result struct {
104 ticket TopicActivationTicket
105 err error
106 }
107 done := make(chan result, 1)
108 ref := target.Ref()
109 go func() {
110 ticket, err := app.StartTopicActivation(TopicActivationRequest{
111 Selector: &SessionSelector{Ref: &ref}, Scope: "project", WorkspaceRoot: source.WorkspaceRoot,
112 SessionPath: sessionRoute(ref.SessionID), RequestID: "canonical-history",
113 })
114 done <- result{ticket, err}
115 }()
116 var ticket TopicActivationTicket
117 select {
118 case got := <-done:
119 if got.err != nil {
120 t.Fatal(got.err)
121 }
122 ticket = got.ticket
123 case <-time.After(5 * time.Second):
124 unlock()
125 <-done
126 t.Fatal("canonical history activation waited for the runtime rebuild mutex before publishing its identity")
127 }
128 gate.waitEntered(t, ticket.TabID)
129 if ticket.Meta.SessionID != ref.SessionID || ticket.Meta.WorkspaceID != workspace || ticket.Meta.WorkspaceRoot != root || ticket.Meta.Ready {
130 t.Fatalf("cold canonical ticket = %+v", ticket.Meta)
131 }
132 page := canonicalTopicHistoryReady(t, app, ticket.TabID)
133 if page.Messages[len(page.Messages)-1].MessageID != "session-B-user" {
134 t.Fatal("history read returned another session's messages")
135 }
136 events.waitFor(t, activationEventFor("canonical-history", "starting"))
137 app.mu.RLock()
138 sourcePreserved := app.tabs[source.ID] == source && source.Ctrl != nil && source.SessionID == "session-A"
139 app.mu.RUnlock()
140 if !sourcePreserved {
141 t.Fatal("source runtime was replaced before target startup completed")
142 }
143 unlock()
144 gate.release(ticket.TabID)
145 events.waitFor(t, activationEventFor("canonical-history", "ready"))
146 app.mu.RLock()
147 controller := app.tabs[ticket.TabID].Ctrl
148 app.mu.RUnlock()
149 bound, ok := controller.(control.IdentityLifecycle).SessionRef()
150 if !ok || bound != ref {
151 t.Fatalf("startup bound a different session: %+v, want %+v", bound, ref)
152 }
153 }
154
155 func TestCanonicalTopicOpenInactivePublishesIdentityWithoutChangingVisibleSession(t *testing.T) {
156 app, source, target, root, workspace := canonicalWorkspaceOpenFixture(t)
157 app.readyHook = func() {}
158 installNoopRuntimeEvents(app, source.sink)
159 gate := newTabBuildGate(app)
160 t.Cleanup(func() { app.shutdown(context.Background()) })
161 t.Cleanup(gate.releaseAll)
162 if err := app.workspaceRegistry().EnsureSessionTopic(t.Context(), target.Ref().SessionID, "target-topic", "Target title"); err != nil {
163 t.Fatal(err)
164 }
165 meta, err := app.openProjectTabInactive(root, "target-topic")
166 if err != nil {
167 t.Fatal(err)
168 }
169 gate.waitEntered(t, meta.ID)
170 if meta.SessionID != target.Ref().SessionID || meta.WorkspaceID != workspace || meta.TopicTitle != "Target title" || meta.Ready {
171 t.Fatalf("inactive canonical metadata = %+v", meta)
172 }
173 app.mu.RLock()
174 active := app.activeTabID
175 app.mu.RUnlock()
176 if active != source.ID {
177 t.Fatal("inactive history open changed the visible session")
178 }
179 canonicalTopicHistoryReady(t, app, meta.ID)
180 }
181
182 func TestCanonicalTopicActivationSupersededBuildKeepsRunningSource(t *testing.T) {
183 app, source, target, root, _ := canonicalWorkspaceOpenFixture(t)
184 app.readyHook = func() {}
185 active := &activeNavigationController{
186 SessionAPI: source.Ctrl, IdentityLifecycle: source.Ctrl.(control.IdentityLifecycle),
187 status: control.RuntimeStatus{Running: true},
188 }
189 source.Ctrl = active
190 installNoopRuntimeEvents(app, source.sink)
191 events := newActivationEventRecorder(app)
192 gate := newTabBuildGate(app)
193 t.Cleanup(func() { app.shutdown(context.Background()) })
194 t.Cleanup(gate.releaseAll)
195 first, err := app.StartTopicActivation(TopicActivationRequest{
196 Scope: "project", WorkspaceRoot: root, SessionPath: sessionRoute(target.Ref().SessionID), RequestID: "first",
197 })
198 if err != nil {
199 t.Fatal(err)
200 }
201 gate.waitEntered(t, first.TabID)
202 app.mu.RLock()
203 buildDone := app.tabs[first.TabID].buildDone
204 app.mu.RUnlock()
205 second, err := app.StartTopicActivation(TopicActivationRequest{
206 Scope: "project", WorkspaceRoot: source.WorkspaceRoot, SessionPath: sessionRoute(source.SessionID), RequestID: "second",
207 })
208 if err != nil {
209 t.Fatal(err)
210 }
211 events.waitFor(t, activationEventFor("first", "cancelled"))
212 events.waitFor(t, activationEventFor("second", "ready"))
213 gate.release(first.TabID)
214 select {
215 case <-buildDone:
216 case <-time.After(5 * time.Second):
217 t.Fatal("superseded build did not stop")
218 }
219 app.mu.RLock()
220 current := app.tabs[app.activeTabID]
221 correct := current == source && current.Ctrl == active && second.TabID == source.ID
222 app.mu.RUnlock()
223 if !correct || active.closed {
224 t.Fatal("late history build displaced or closed the running source")
225 }
226 }
227
228 func TestCanonicalTopicActivationKeepsHistoryReadableWhenWriterUnavailable(t *testing.T) {
229 app, source, target, root, _ := canonicalWorkspaceOpenFixture(t)
230 app.readyHook = func() {}
231 installNoopRuntimeEvents(app, source.sink)
232 events := newActivationEventRecorder(app)
233 t.Cleanup(func() { app.shutdown(context.Background()) })
234 if err := app.desktopSessionService("").Close(t.Context(), target.Ref()); err != nil {
235 t.Fatal(err)
236 }
237 other, err := session.NewService(localDesktopHostID, session.NewFilesystemPersistence(app.desktopSessions.root))
238 if err != nil {
239 t.Fatal(err)
240 }
241 t.Cleanup(func() { _ = other.Shutdown(context.Background()) })
242 lease, err := other.Open(t.Context(), target.Ref())
243 if err != nil {
244 t.Fatal(err)
245 }
246 t.Cleanup(func() { _ = lease.Release(context.Background()) })
247 ticket, err := app.StartTopicActivation(TopicActivationRequest{
248 Scope: "project", WorkspaceRoot: root, SessionPath: sessionRoute(target.Ref().SessionID), RequestID: "writer-busy",
249 })
250 if err != nil {
251 t.Fatalf("writer ownership blocked history navigation: %v", err)
252 }
253 events.waitFor(t, activationEventFor("writer-busy", "failed"))
254 canonicalTopicHistoryReady(t, app, ticket.TabID)
255 app.mu.RLock()
256 tab := app.tabs[ticket.TabID]
257 correct := tab != nil && tab.SessionID == target.Ref().SessionID && tab.StartupErr != "" && !tab.Ready
258 app.mu.RUnlock()
259 if !correct {
260 t.Fatal("runtime failure lost the target identity or failure state")
261 }
262 }
263
264 func TestCanonicalTopicOpenRejectsConflictingWorkspaceBeforePublishing(t *testing.T) {
265 app, source, target, root, workspaceID := canonicalWorkspaceOpenFixture(t)
266 state, err := app.workspaceRegistry().Load(t.Context())
267 if err != nil {
268 t.Fatal(err)
269 }
270 workspace := state.Workspaces[workspaceID]
271 workspace.Root = source.WorkspaceRoot
272 state.Workspaces[workspaceID] = workspace
273 data, err := json.Marshal(state)
274 if err != nil {
275 t.Fatal(err)
276 }
277 if err := os.WriteFile(app.workspaceRegistry().Path(), data, 0o600); err != nil {
278 t.Fatal(err)
279 }
280 _, err = app.OpenTopicSession("project", root, "", sessionRoute(target.Ref().SessionID))
281 if !errors.Is(err, errSessionWorkspaceConflict) {
282 t.Fatalf("conflicting canonical workspace accepted: %v", err)
283 }
284 if len(app.tabs) != 1 || app.activeTabID != source.ID || source.SessionID != "session-A" || !source.Ready {
285 t.Fatal("failed identity validation changed the visible session")
286 }
287 }
288
289 func TestCanonicalTopicActivationReattachesRunningSourceWithoutRebuild(t *testing.T) {
290 app, source, target, root, _ := canonicalWorkspaceOpenFixture(t)
291 app.readyHook = func() {}
292 active := &activeNavigationController{
293 SessionAPI: source.Ctrl, IdentityLifecycle: source.Ctrl.(control.IdentityLifecycle),
294 status: control.RuntimeStatus{Running: true},
295 }
296 source.Ctrl = active
297 installNoopRuntimeEvents(app, source.sink)
298 events := newActivationEventRecorder(app)
299 t.Cleanup(func() { app.shutdown(context.Background()) })
300 sourceID, sourceRoot := source.SessionID, source.WorkspaceRoot
301 first, err := app.StartTopicActivation(TopicActivationRequest{
302 Scope: "project", WorkspaceRoot: root, SessionPath: sessionRoute(target.Ref().SessionID), RequestID: "target",
303 })
304 if err != nil {
305 t.Fatal(err)
306 }
307 events.waitFor(t, activationEventFor("target", "ready"))
308 // Complete pruning before the return click so this covers detached reuse,
309 // not merely reuse of a source that is still in the visible tabs map.
310 app.singleSurfaceMu.Lock()
311 _, err = app.keepOnlyVisibleTab(first.TabID)
312 app.singleSurfaceMu.Unlock()
313 if err != nil {
314 t.Fatal(err)
315 }
316 app.mu.RLock()
317 _, visible := app.tabs[source.ID]
318 app.mu.RUnlock()
319 if visible || active.closed {
320 t.Fatal("running source was not preserved as a detached runtime")
321 }
322 second, err := app.StartTopicActivation(TopicActivationRequest{
323 Scope: "project", WorkspaceRoot: sourceRoot, SessionPath: sessionRoute(sourceID), RequestID: "return",
324 })
325 if err != nil {
326 t.Fatal(err)
327 }
328 events.waitFor(t, activationEventFor("return", "ready"))
329 app.mu.RLock()
330 current := app.tabs[second.TabID]
331 correct := current != nil && current.Ctrl == active && current.SessionID == sourceID
332 app.mu.RUnlock()
333 if !correct || active.closed {
334 t.Fatal("returning to running history replaced its controller")
335 }
336 }
337
337 lines GO