The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 17:00 UTC
fix(web): queued-message edits survive navigation and settle once (#24972)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 25, 2026 at 15:26 UTC
7561c2e6317aab30c3f0cf9e3d63784fec20586c
6 files changed
+679
-61
apps/web/src/components/chat/queuedMessageEdit.ts
+11
-7
@@ -1,3 +1,4 @@
1
+import { resolveQueuedEditExit } from "@t3tools/client-runtime/queued-run-edit";
2
import type { ChatAttachment } from "@t3tools/contracts";
3
import {
4
composerDraftHasUserContent,
@@ -14,15 +15,18 @@ export function recoverQueuedMessageEdit(input: {
15
}): "kept" | "discarded" | "clean" {
16
const store = useComposerDraftStore.getState();
17
const draft = store.getComposerDraft(input.editTarget);
17
- const dirty =
18
- draft !== null &&
19
- (draft.prompt !== input.originalText || draft.images.length > 0 || draft.files.length > 0);
20
- if (dirty && !composerDraftHasUserContent(store.getComposerDraft(input.threadTarget))) {
18
+ const recovery = resolveQueuedEditExit({
19
+ editChanged:
20
+ draft !== null &&
21
+ (draft.prompt !== input.originalText || draft.images.length > 0 || draft.files.length > 0),
22
+ threadDraftEmpty: !composerDraftHasUserContent(store.getComposerDraft(input.threadTarget)),
23
+ });
24
+ if (recovery === "kept") {
25
store.moveComposerPromptAndImages(input.editTarget, input.threadTarget);
22
- return "kept";
26
+ } else {
27
+ store.clearComposerContent(input.editTarget);
28
}
24
- store.clearComposerContent(input.editTarget);
25
- return dirty ? "discarded" : "clean";
29
+ return recovery;
30
}
31
32
export async function prepareQueuedEditAttachments(input: {
apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx
new
+195
@@ -0,0 +1,195 @@
1
+import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
2
+import {
3
+ EnvironmentId,
4
+ MessageId,
5
+ RunId,
6
+ ThreadId,
7
+ type ScopedThreadRef,
8
+} from "@t3tools/contracts";
9
+import { useImperativeHandle, type RefObject } from "react";
10
+import { describe, expect, it, vi } from "vite-plus/test";
11
+
12
+import { act, render } from "../../../test/render";
13
+import { useComposerDraftStore } from "../../composerDraftStore";
14
+import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry";
15
+import { useQueuedRunEdit } from "./useQueuedRunEdit";
16
+
17
+interface RunStatus {
18
+ readonly id: RunId;
19
+ readonly status: string;
20
+}
21
+
22
+const mocks = await vi.hoisted(async () => {
23
+ const { Atom } = await import("effect/reactivity");
24
+ return {
25
+ editQueuedRun: vi.fn<(value: unknown) => Promise<{ readonly _tag: "Success" | "Failure" }>>(),
26
+ // The projection's runs per thread, written by each test to stand in for the server.
27
+ threadRuns: Atom.family((_key: string) =>
28
+ Atom.make<ReadonlyArray<RunStatus> | null>(null).pipe(Atom.keepAlive),
29
+ ),
30
+ };
31
+});
32
+
33
+vi.mock("../../state/use-atom-command", () => ({
34
+ useAtomCommand: () => mocks.editQueuedRun,
35
+}));
36
+
37
+const runsKey = (ref: ScopedThreadRef) => `${ref.environmentId}:${ref.threadId}`;
38
+
39
+vi.mock("../../state/threads", async () => {
40
+ const { Atom } = await import("effect/reactivity");
41
+ const key = (ref: ScopedThreadRef) => `${ref.environmentId}:${ref.threadId}`;
42
+ return {
43
+ threadEnvironment: {
44
+ snapshotAtom: () => Atom.make(null),
45
+ editQueuedRun: {},
46
+ },
47
+ environmentThreadDetails: {
48
+ statusAtom: () => Atom.make("ready"),
49
+ quietThreadAtom: (ref: ScopedThreadRef) =>
50
+ Atom.make((get) => {
51
+ const runs = get(mocks.threadRuns(key(ref)));
52
+ return runs === null ? null : { projection: { runs } };
53
+ }),
54
+ },
55
+ environmentThreadShells: {
56
+ threadShellAtom: () => Atom.make(null),
57
+ },
58
+ };
59
+});
60
+
61
+const ENV = EnvironmentId.make("env-1");
62
+const THREAD_A: ScopedThreadRef = { environmentId: ENV, threadId: ThreadId.make("thread-a") };
63
+const THREAD_B: ScopedThreadRef = { environmentId: ENV, threadId: ThreadId.make("thread-b") };
64
+const RUN = RunId.make("run-1");
65
+
66
+type HookResult = ReturnType<typeof useQueuedRunEdit>;
67
+
68
+function projection(runs: ReadonlyArray<RunStatus>) {
69
+ return { runs, messages: [] } as unknown as ThreadStructure;
70
+}
71
+
72
+function setRuns(ref: ScopedThreadRef, status: string) {
73
+ appAtomRegistry.set(mocks.threadRuns(runsKey(ref)), [{ id: RUN, status }]);
74
+}
75
+
76
+function Harness(props: {
77
+ readonly threadRef: ScopedThreadRef;
78
+ readonly runStatus: string;
79
+ readonly hookRef: RefObject<HookResult | null>;
80
+}) {
81
+ const result = useQueuedRunEdit({
82
+ environmentId: ENV,
83
+ routeThreadRef: props.threadRef,
84
+ threadDraftTarget: props.threadRef,
85
+ activeThreadId: props.threadRef.threadId,
86
+ serverProjection: projection([{ id: RUN, status: props.runStatus }]),
87
+ promptRef: { current: "" },
88
+ composerRef: { current: null },
89
+ });
90
+ useImperativeHandle(props.hookRef, () => result);
91
+ return null;
92
+}
93
+
94
+function view(threadRef: ScopedThreadRef, runStatus: string, hook: { current: HookResult | null }) {
95
+ return (
96
+ <AppAtomRegistryProvider>
97
+ <Harness threadRef={threadRef} runStatus={runStatus} hookRef={hook} />
98
+ </AppAtomRegistryProvider>
99
+ );
100
+}
101
+
102
+function setup() {
103
+ mocks.editQueuedRun.mockReset();
104
+ useComposerDraftStore.setState({ draftsByThreadKey: {}, draftThreadsByThreadKey: {} });
105
+ setRuns(THREAD_A, "queued");
106
+ setRuns(THREAD_B, "queued");
107
+ return { hook: { current: null as HookResult | null } };
108
+}
109
+
110
+function requireHook(hook: { current: HookResult | null }): HookResult {
111
+ if (hook.current === null) throw new Error("hook did not render");
112
+ return hook.current;
113
+}
114
+
115
+async function beginChangedEdit(hook: { current: HookResult | null }) {
116
+ await act(() =>
117
+ requireHook(hook).beginEdit({
118
+ runId: RUN,
119
+ messageId: MessageId.make("message-1"),
120
+ text: "original",
121
+ attachments: [],
122
+ }),
123
+ );
124
+ await act(() =>
125
+ useComposerDraftStore.getState().setPrompt(requireHook(hook).draftTarget, "changed"),
126
+ );
127
+}
128
+
129
+const promptOf = (ref: ScopedThreadRef) =>
130
+ useComposerDraftStore.getState().getComposerDraft(ref)?.prompt ?? "";
131
+
132
+describe("useQueuedRunEdit", () => {
133
+ it("keeps an open edit when the user leaves the thread and comes back", async () => {
134
+ const { hook } = setup();
135
+ await using screen = await render(view(THREAD_A, "queued", hook));
136
+ await beginChangedEdit(hook);
137
+
138
+ await screen.rerender(view(THREAD_B, "queued", hook));
139
+ expect(requireHook(hook).isEditing).toBe(false);
140
+ await screen.rerender(view(THREAD_A, "queued", hook));
141
+
142
+ expect(requireHook(hook).editingRunId).toBe(RUN);
143
+ expect(
144
+ useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt,
145
+ ).toBe("changed");
146
+ });
147
+
148
+ it("moves a changed edit into the thread draft when its run starts while the user is away", async () => {
149
+ const { hook } = setup();
150
+ await using screen = await render(view(THREAD_A, "queued", hook));
151
+ await beginChangedEdit(hook);
152
+
153
+ await screen.rerender(view(THREAD_B, "queued", hook));
154
+ expect(promptOf(THREAD_A)).toBe("");
155
+ await act(() => setRuns(THREAD_A, "running"));
156
+
157
+ expect(promptOf(THREAD_A)).toBe("changed");
158
+ });
159
+
160
+ it("does not copy a saved edit into the thread draft when the run starts mid-save", async () => {
161
+ const { hook } = setup();
162
+ let finishSave: (result: { readonly _tag: "Success" }) => void = () => {};
163
+ mocks.editQueuedRun.mockReturnValue(
164
+ new Promise((resolve) => {
165
+ finishSave = resolve;
166
+ }),
167
+ );
168
+ await using screen = await render(view(THREAD_A, "queued", hook));
169
+ await beginChangedEdit(hook);
170
+
171
+ // Not inside act(): act would hold the projection update until the save settles.
172
+ const saved = requireHook(hook).saveEdit(
173
+ {
174
+ prompt: "changed",
175
+ images: [],
176
+ files: [],
177
+ terminalContexts: [],
178
+ reviewComments: [],
179
+ previewAnnotations: [],
180
+ threadContexts: [],
181
+ },
182
+ () => {},
183
+ );
184
+ await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
185
+ // The server applied the edit and then started the run; the projection
186
+ // reports the start before the edit's acknowledgement arrives.
187
+ await act(() => setRuns(THREAD_A, "running"));
188
+ await screen.rerender(view(THREAD_A, "running", hook));
189
+ finishSave({ _tag: "Success" });
190
+ await act(() => saved);
191
+
192
+ expect(requireHook(hook).isEditing).toBe(false);
193
+ expect(promptOf(THREAD_A)).toBe("");
194
+ });
195
+});
apps/web/src/components/chat/useQueuedRunEdit.ts
+85
-54
@@ -1,3 +1,8 @@
1
+import { useAtomValue } from "@effect/atom-react";
2
+import {
3
+ makeQueuedRunEditStore,
4
+ makeQueuedRunsAtom,
5
+} from "@t3tools/client-runtime/queued-run-edit";
6
import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
7
import {
8
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
@@ -13,7 +18,8 @@ import {
18
} from "@t3tools/contracts";
19
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
20
import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
16
-import { useEffect, useRef, useState, type RefObject } from "react";
21
+import { Atom } from "effect/reactivity";
22
+import { useRef, useState, type RefObject } from "react";
23
import { useAssetUrls } from "../../assets/assetUrls";
24
import {
25
DraftId,
@@ -35,7 +41,11 @@ import type { TerminalContextDraft } from "../../lib/terminalContext";
41
import type { ReviewCommentContext } from "../../reviewCommentContext";
42
import { appAtomRegistry } from "../../rpc/atomRegistry";
43
import { environmentServerConfigsAtom } from "../../state/server";
38
-import { threadEnvironment } from "../../state/threads";
44
+import {
45
+ environmentThreadDetails,
46
+ environmentThreadShells,
47
+ threadEnvironment,
48
+} from "../../state/threads";
49
import { useAtomCommand } from "../../state/use-atom-command";
50
import { stackedThreadToast, toastManager } from "../ui/toast";
51
import type { ChatComposerHandle } from "./ChatComposer";
@@ -52,6 +62,12 @@ interface EditingQueuedRun {
62
readonly context?: OrchestrationMessageContext | undefined;
63
}
64
65
+// Keyed by the route thread, so an edit survives navigating away and back.
66
+const queuedRunEdits = makeQueuedRunEditStore<EditingQueuedRun>({
67
+ registry: appAtomRegistry,
68
+ label: "web-queued-run-edits",
69
+});
70
+
71
export interface QueuedRunEditContent {
72
readonly prompt: string;
73
readonly images: ReadonlyArray<ComposerImageAttachment>;
@@ -174,12 +190,11 @@ export function useQueuedRunEdit(input: {
190
composerRef,
191
} = input;
192
const editQueuedRunCommand = useEditQueuedRunCommand();
177
- const [editing, setEditing] = useState<EditingQueuedRun | null>(null);
193
+ const editKey = scopedThreadKey(routeThreadRef);
194
+ const storedEdit = useAtomValue(queuedRunEdits.atom)[editKey] ?? null;
195
+ const editing = activeThreadId === null ? null : storedEdit;
196
const saveInFlightRef = useRef(false);
197
const [isSaving, setIsSaving] = useState(false);
180
- if (editing !== null && activeThreadId !== editing.threadId) {
181
- setEditing(null);
182
- }
198
const draftTarget =
199
editing === null ? threadDraftTarget : queuedEditDraftTarget(routeThreadRef, editing.runId);
200
@@ -213,62 +228,73 @@ export function useQueuedRunEdit(input: {
228
const store = useComposerDraftStore.getState();
229
store.clearComposerContent(target);
230
store.setPrompt(target, request.text);
216
- setEditing({
217
- threadId: activeThreadId,
218
- runId: request.runId,
219
- messageId: request.messageId,
220
- originalText: request.text,
221
- existingAttachments: request.attachments,
222
- context: serverProjection?.messages.find((message) => message.id === request.messageId)
223
- ?.context,
224
- });
231
+ const threadRef = { environmentId, threadId: activeThreadId };
232
+ queuedRunEdits.begin(
233
+ editKey,
234
+ {
235
+ threadId: activeThreadId,
236
+ runId: request.runId,
237
+ messageId: request.messageId,
238
+ originalText: request.text,
239
+ existingAttachments: request.attachments,
240
+ context: serverProjection?.messages.find((message) => message.id === request.messageId)
241
+ ?.context,
242
+ },
243
+ {
244
+ runs: makeQueuedRunsAtom({
245
+ threadId: activeThreadId,
246
+ snapshot: threadEnvironment.snapshotAtom(environmentId),
247
+ detailStatus: environmentThreadDetails.statusAtom(threadRef),
248
+ runs: Atom.make(
249
+ (get) =>
250
+ get(environmentThreadDetails.quietThreadAtom(threadRef))?.projection.runs ?? null,
251
+ ),
252
+ }),
253
+ // The run started or was cancelled from another client. A changed
254
+ // edit moves into the thread's own draft when that draft is empty;
255
+ // otherwise it is dropped. Edits outlive navigation, so the toast is
256
+ // unscoped and names the thread: the user may be anywhere by now.
257
+ onRunLeftQueue: (_, edit) => {
258
+ const recovery = recoverQueuedMessageEdit({
259
+ editTarget: queuedEditDraftTarget(routeThreadRef, edit.runId),
260
+ threadTarget: threadDraftTarget,
261
+ originalText: edit.originalText,
262
+ });
263
+ if (recovery === "clean") return;
264
+ const title = appAtomRegistry.get(
265
+ environmentThreadShells.threadShellAtom(threadRef),
266
+ )?.title;
267
+ const where = title === undefined ? "" : ` in “${title}”`;
268
+ toastManager.add(
269
+ stackedThreadToast({
270
+ type: recovery === "kept" ? "info" : "warning",
271
+ title: "Queued message is no longer queued",
272
+ description:
273
+ recovery === "kept"
274
+ ? `Your unsaved edit${where} was kept in the composer.`
275
+ : `Your unsaved edit${where} was discarded.`,
276
+ }),
277
+ );
278
+ },
279
+ },
280
+ );
281
focusComposerSoon();
282
});
283
const cancelEdit = useStableCallback(() => {
284
if (editing === null) return;
285
clearEditDraft(editing.runId);
230
- setEditing(null);
286
+ queuedRunEdits.end(editKey);
287
focusComposerSoon();
288
});
289
const removeEditingAttachment = useStableCallback((attachmentId: string) => {
234
- setEditing((current) =>
235
- current === null
236
- ? current
237
- : {
238
- ...current,
239
- existingAttachments: current.existingAttachments.filter(
240
- (attachment) => attachment.id !== attachmentId,
241
- ),
242
- },
243
- );
290
+ queuedRunEdits.update(editKey, (current) => ({
291
+ ...current,
292
+ existingAttachments: current.existingAttachments.filter(
293
+ (attachment) => attachment.id !== attachmentId,
294
+ ),
295
+ }));
296
});
297
246
- useEffect(() => {
247
- if (editing === null || activeThreadId !== editing.threadId) return;
248
- if (serverProjection === null) return;
249
- const run = serverProjection.runs.find((candidate) => candidate.id === editing.runId);
250
- if (run !== undefined && run.status === "queued") return;
251
- const recovery = recoverQueuedMessageEdit({
252
- editTarget: queuedEditDraftTarget(routeThreadRef, editing.runId),
253
- threadTarget: threadDraftTarget,
254
- originalText: editing.originalText,
255
- });
256
- if (recovery !== "clean") {
257
- toastManager.add(
258
- stackedThreadToast({
259
- type: recovery === "kept" ? "info" : "warning",
260
- title: "Queued message is no longer queued",
261
- description:
262
- recovery === "kept"
263
- ? "Your unsaved edit was kept in the composer."
264
- : "Your unsaved edit was discarded.",
265
- }),
266
- );
267
- }
268
- // oxlint-disable-next-line react/set-state-in-effect -- Leaving edit mode follows the draft recovery and toast above, which must run once after commit.
269
- setEditing(null);
270
- }, [activeThreadId, editing, routeThreadRef, serverProjection, threadDraftTarget]);
271
-
298
const saveEdit = async (
299
content: QueuedRunEditContent,
300
setThreadError: (threadId: ThreadId, error: string | null) => void,
@@ -294,6 +320,8 @@ export function useQueuedRunEdit(input: {
320
}
321
saveInFlightRef.current = true;
322
setIsSaving(true);
323
+ // The save's result decides the edit's fate, even if the run starts meanwhile.
324
+ queuedRunEdits.suspendExitWatch(editKey);
325
const error = await submitQueuedRunEdit({
326
environmentId,
327
draftTarget,
@@ -304,12 +332,15 @@ export function useQueuedRunEdit(input: {
332
saveInFlightRef.current = false;
333
setIsSaving(false);
334
setThreadError(editing.threadId, error);
307
- if (error !== null) return;
335
+ if (error !== null) {
336
+ queuedRunEdits.resumeExitWatch(editKey);
337
+ return;
338
+ }
339
releaseDraftAttachments(newAttachments);
340
promptRef.current = "";
341
clearEditDraft(editing.runId);
342
composerRef.current?.resetCursorState();
312
- setEditing(null);
343
+ queuedRunEdits.end(editKey);
344
focusComposerSoon();
345
};
346
packages/client-runtime/package.json
+4
@@ -147,6 +147,10 @@
147
"types": "./src/webhookAddress.ts",
148
"default": "./src/webhookAddress.ts"
149
},
150
+ "./queued-run-edit": {
151
+ "types": "./src/queuedRunEdit.ts",
152
+ "default": "./src/queuedRunEdit.ts"
153
+ },
154
"./delayed-status": {
155
"types": "./src/delayedStatus.ts",
156
"default": "./src/delayedStatus.ts"
packages/client-runtime/src/queuedRunEdit.test.ts
new
+217
@@ -0,0 +1,217 @@
1
+import { RunId } from "@t3tools/contracts";
2
+import { Atom, AtomRegistry } from "effect/reactivity";
3
+import { describe, expect, it } from "vite-plus/test";
4
+
5
+import {
6
+ makeQueuedRunEditStore,
7
+ makeQueuedRunsAtom,
8
+ resolveQueuedEditExit,
9
+ type QueuedRunStatus,
10
+} from "./queuedRunEdit.ts";
11
+
12
+const RUN = RunId.make("run-1");
13
+const queued = (status = "queued"): ReadonlyArray<QueuedRunStatus> => [{ id: RUN, status }];
14
+
15
+function setup(initialRuns: ReadonlyArray<QueuedRunStatus> | null = queued()) {
16
+ const registry = AtomRegistry.make();
17
+ const runs = Atom.make<ReadonlyArray<QueuedRunStatus> | null>(initialRuns);
18
+ const store = makeQueuedRunEditStore<{ readonly runId: RunId; readonly text: string }>({
19
+ registry,
20
+ label: "test-queued-run-edits",
21
+ });
22
+ const exits: Array<{ threadKey: string; text: string }> = [];
23
+ const begin = () =>
24
+ store.begin(
25
+ "env:thread",
26
+ { runId: RUN, text: "draft" },
27
+ { runs, onRunLeftQueue: (threadKey, edit) => exits.push({ threadKey, text: edit.text }) },
28
+ );
29
+ return { registry, runs, store, exits, begin };
30
+}
31
+
32
+describe("resolveQueuedEditExit", () => {
33
+ it("closes an unchanged edit without touching drafts", () => {
34
+ expect(resolveQueuedEditExit({ editChanged: false, threadDraftEmpty: true })).toBe("clean");
35
+ });
36
+
37
+ it("keeps a changed edit only when the thread draft is empty", () => {
38
+ expect(resolveQueuedEditExit({ editChanged: true, threadDraftEmpty: true })).toBe("kept");
39
+ expect(resolveQueuedEditExit({ editChanged: true, threadDraftEmpty: false })).toBe("discarded");
40
+ });
41
+});
42
+
43
+describe("makeQueuedRunEditStore", () => {
44
+ it("fires once when the edited run leaves the queue, with the latest edit", () => {
45
+ const { registry, runs, store, exits, begin } = setup();
46
+ begin();
47
+ store.update("env:thread", (edit) => ({ ...edit, text: "changed" }));
48
+ registry.set(runs, queued());
49
+ expect(exits).toEqual([]);
50
+ registry.set(runs, queued("running"));
51
+ registry.set(runs, []);
52
+ expect(exits).toEqual([{ threadKey: "env:thread", text: "changed" }]);
53
+ });
54
+
55
+ it("waits while the runs are unknown and treats a vanished run as left", () => {
56
+ const { registry, runs, exits, begin } = setup(null);
57
+ begin();
58
+ expect(exits).toEqual([]);
59
+ registry.set(runs, []);
60
+ expect(exits).toHaveLength(1);
61
+ });
62
+
63
+ it("fires immediately when the run already left the queue", () => {
64
+ const { exits, begin } = setup(queued("running"));
65
+ begin();
66
+ expect(exits).toHaveLength(1);
67
+ });
68
+
69
+ it("stops watching when the edit ends", () => {
70
+ const { registry, runs, store, exits, begin } = setup();
71
+ begin();
72
+ store.end("env:thread");
73
+ registry.set(runs, []);
74
+ expect(exits).toEqual([]);
75
+ expect(store.get("env:thread")).toBeNull();
76
+ });
77
+
78
+ it("holds the exit during a save and replays it when the save fails", () => {
79
+ const { registry, runs, store, exits, begin } = setup();
80
+ begin();
81
+ store.suspendExitWatch("env:thread");
82
+ registry.set(runs, []);
83
+ expect(exits).toEqual([]);
84
+ store.resumeExitWatch("env:thread");
85
+ expect(exits).toHaveLength(1);
86
+ });
87
+
88
+ // The runs read the thread's detail, a live server subscription; a thread
89
+ // with no edit open must not keep it.
90
+ it("holds the thread's runs only while an edit is open and watching", () => {
91
+ // The registry removes idle nodes in a scheduled task; the test runs those tasks itself.
92
+ const tasks: Array<() => void> = [];
93
+ const registry = AtomRegistry.make({
94
+ scheduleTask: (task) => {
95
+ tasks.push(task);
96
+ return () => {};
97
+ },
98
+ });
99
+ const settle = () => {
100
+ for (const task of tasks.splice(0)) task();
101
+ };
102
+ const source = Atom.make<ReadonlyArray<QueuedRunStatus> | null>(queued());
103
+ let mounted = 0;
104
+ const runs = Atom.make((get) => {
105
+ mounted += 1;
106
+ get.addFinalizer(() => {
107
+ mounted -= 1;
108
+ });
109
+ return get(source);
110
+ });
111
+ const store = makeQueuedRunEditStore<{ readonly runId: RunId }>({
112
+ registry,
113
+ label: "test-queued-run-edits",
114
+ });
115
+ const begin = () =>
116
+ store.begin("env:thread", { runId: RUN }, { runs, onRunLeftQueue: () => {} });
117
+
118
+ begin();
119
+ expect(mounted).toBe(1);
120
+ store.end("env:thread");
121
+ settle();
122
+ expect(mounted).toBe(0);
123
+
124
+ begin();
125
+ store.suspendExitWatch("env:thread");
126
+ settle();
127
+ expect(mounted).toBe(0);
128
+ store.resumeExitWatch("env:thread");
129
+ expect(mounted).toBe(1);
130
+
131
+ registry.set(source, []);
132
+ expect(store.get("env:thread")).toBeNull();
133
+ settle();
134
+ expect(mounted).toBe(0);
135
+ });
136
+});
137
+
138
+describe("makeQueuedRunsAtom", () => {
139
+ const thread = (overrides: { archivedAt?: string | null; deletedAt?: string | null } = {}) => ({
140
+ id: "thread-1",
141
+ archivedAt: null,
142
+ deletedAt: null,
143
+ ...overrides,
144
+ });
145
+
146
+ function setupWatched() {
147
+ const registry = AtomRegistry.make();
148
+ const snapshot = Atom.make<{ threads: ReadonlyArray<ReturnType<typeof thread>> } | null>({
149
+ threads: [thread()],
150
+ });
151
+ let detailReads = 0;
152
+ const detailStatus = Atom.make("live");
153
+ const detail = Atom.make<ReadonlyArray<QueuedRunStatus> | null>(queued());
154
+ const runs = makeQueuedRunsAtom({
155
+ threadId: "thread-1",
156
+ snapshot,
157
+ detailStatus,
158
+ runs: Atom.make((get) => {
159
+ detailReads += 1;
160
+ return get(detail);
161
+ }),
162
+ });
163
+ const store = makeQueuedRunEditStore<{ readonly runId: RunId }>({
164
+ registry,
165
+ label: "test-queued-run-edits",
166
+ });
167
+ const exits: Array<string> = [];
168
+ store.begin("env:thread", { runId: RUN }, { runs, onRunLeftQueue: (key) => exits.push(key) });
169
+ return {
170
+ registry,
171
+ snapshot,
172
+ detailStatus,
173
+ detail,
174
+ store,
175
+ exits,
176
+ detailReads: () => detailReads,
177
+ };
178
+ }
179
+
180
+ it("ends the edit when the shell marks the thread deleted, without reading its detail again", () => {
181
+ const { registry, snapshot, detail, exits, detailReads } = setupWatched();
182
+ expect(exits).toEqual([]);
183
+ registry.set(snapshot, { threads: [thread({ deletedAt: "2026-10-24T00:00:00Z" })] });
184
+ expect(exits).toEqual(["env:thread"]);
185
+ const reads = detailReads();
186
+ registry.set(detail, []);
187
+ expect(detailReads()).toBe(reads);
188
+ });
189
+
190
+ it("ends the edit when the detail reports the thread gone", () => {
191
+ const { registry, snapshot, detailStatus, exits } = setupWatched();
192
+ registry.set(snapshot, { threads: [] });
193
+ expect(exits).toEqual([]);
194
+ registry.set(detailStatus, "deleted");
195
+ expect(exits).toEqual(["env:thread"]);
196
+ });
197
+
198
+ it("keeps an archived thread's edit open, ending it only when the run leaves the queue", () => {
199
+ const { registry, snapshot, detail, store, exits } = setupWatched();
200
+ // The shell drops archived threads, but their queue stays editable.
201
+ registry.set(snapshot, { threads: [] });
202
+ registry.set(snapshot, { threads: [thread({ archivedAt: "2026-10-24T00:00:00Z" })] });
203
+ expect(exits).toEqual([]);
204
+ expect(store.get("env:thread")).not.toBeNull();
205
+ registry.set(detail, queued("running"));
206
+ expect(exits).toEqual(["env:thread"]);
207
+ });
208
+
209
+ it("waits while the thread detail is unknown", () => {
210
+ const { registry, snapshot, detail, exits } = setupWatched();
211
+ registry.set(snapshot, null);
212
+ registry.set(detail, null);
213
+ expect(exits).toEqual([]);
214
+ registry.set(detail, []);
215
+ expect(exits).toEqual(["env:thread"]);
216
+ });
217
+});
packages/client-runtime/src/queuedRunEdit.ts
new
+167
@@ -0,0 +1,167 @@
1
+/**
2
+ * A queued-message edit ends on save, cancel, or when its run leaves the queue.
3
+ * The store owns one watcher per edit, so "run left the queue" is handled exactly
4
+ * once, when the projection reports it, wherever the user is in the app.
5
+ */
6
+import type { RunId } from "@t3tools/contracts";
7
+import { Atom, type AtomRegistry } from "effect/reactivity";
8
+
9
+export interface QueuedRunStatus {
10
+ readonly id: RunId;
11
+ readonly status: string;
12
+}
13
+
14
+/** The thread's runs, or null while they are unknown (detail not loaded yet). */
15
+export type QueuedRunsAtom = Atom.Atom<ReadonlyArray<QueuedRunStatus> | null>;
16
+
17
+interface ShellThreadPresence {
18
+ readonly id: string;
19
+ readonly deletedAt: unknown;
20
+}
21
+
22
+/**
23
+ * The edited thread's runs. A deleted thread (shell `deletedAt` or detail status
24
+ * `deleted`) reads as no runs, so its edit ends. Absence from the shell is not
25
+ * deletion: archived threads are dropped there but keep an editable queue, so
26
+ * everything else reads the detail's runs, unknown until it loads.
27
+ */
28
+export function makeQueuedRunsAtom(input: {
29
+ readonly threadId: string;
30
+ readonly snapshot: Atom.Atom<{ readonly threads: ReadonlyArray<ShellThreadPresence> } | null>;
31
+ readonly detailStatus: Atom.Atom<string>;
32
+ readonly runs: Atom.Atom<ReadonlyArray<QueuedRunStatus> | null>;
33
+}): QueuedRunsAtom {
34
+ return Atom.make((get) => {
35
+ const shellThread = get(input.snapshot)?.threads.find(
36
+ (candidate) => candidate.id === input.threadId,
37
+ );
38
+ if (shellThread !== undefined && shellThread.deletedAt !== null) return [];
39
+ if (get(input.detailStatus) === "deleted") return [];
40
+ return get(input.runs);
41
+ });
42
+}
43
+
44
+function runLeftQueue(runs: ReadonlyArray<QueuedRunStatus> | null, runId: RunId): boolean {
45
+ if (runs === null) return false;
46
+ return !runs.some((run) => run.id === runId && run.status === "queued");
47
+}
48
+
49
+/**
50
+ * What happens to an open edit when its run leaves the queue: an unchanged
51
+ * edit just closes; a changed one moves into the thread's own draft when that
52
+ * draft is empty, and is dropped otherwise so it never overwrites the user's
53
+ * other work.
54
+ */
55
+export function resolveQueuedEditExit(input: {
56
+ readonly editChanged: boolean;
57
+ readonly threadDraftEmpty: boolean;
58
+}): "kept" | "discarded" | "clean" {
59
+ if (!input.editChanged) return "clean";
60
+ return input.threadDraftEmpty ? "kept" : "discarded";
61
+}
62
+
63
+interface ExitWatch<E> {
64
+ readonly runs: QueuedRunsAtom;
65
+ readonly runId: RunId;
66
+ readonly onRunLeftQueue: (threadKey: string, edit: E) => void;
67
+ cancel: (() => void) | null;
68
+}
69
+
70
+export function makeQueuedRunEditStore<E extends { readonly runId: RunId }>(options: {
71
+ readonly registry: AtomRegistry.AtomRegistry;
72
+ readonly label: string;
73
+}) {
74
+ const { registry } = options;
75
+ const atom = Atom.make<Readonly<Record<string, E>>>({}).pipe(
76
+ Atom.keepAlive,
77
+ Atom.withLabel(options.label),
78
+ );
79
+ const watches = new Map<string, ExitWatch<E>>();
80
+
81
+ const get = (threadKey: string | null): E | null =>
82
+ threadKey === null ? null : (registry.get(atom)[threadKey] ?? null);
83
+
84
+ const write = (threadKey: string, edit: E | null) => {
85
+ const current = registry.get(atom);
86
+ if (edit === null) {
87
+ if (!(threadKey in current)) return;
88
+ const next = { ...current };
89
+ delete next[threadKey];
90
+ registry.set(atom, next);
91
+ return;
92
+ }
93
+ registry.set(atom, { ...current, [threadKey]: edit });
94
+ };
95
+
96
+ const unsubscribe = (watch: ExitWatch<E>) => {
97
+ watch.cancel?.();
98
+ watch.cancel = null;
99
+ };
100
+
101
+ const subscribe = (threadKey: string, watch: ExitWatch<E>) => {
102
+ const check = (runs: ReadonlyArray<QueuedRunStatus> | null) => {
103
+ if (watches.get(threadKey) !== watch || watch.cancel === null) return;
104
+ if (!runLeftQueue(runs, watch.runId)) return;
105
+ unsubscribe(watch);
106
+ watches.delete(threadKey);
107
+ const edit = get(threadKey);
108
+ if (edit === null || edit.runId !== watch.runId) return;
109
+ write(threadKey, null);
110
+ watch.onRunLeftQueue(threadKey, edit);
111
+ };
112
+ watch.cancel = registry.subscribe(watch.runs, check);
113
+ check(registry.get(watch.runs));
114
+ };
115
+
116
+ const stopWatch = (threadKey: string) => {
117
+ const watch = watches.get(threadKey);
118
+ if (watch === undefined) return;
119
+ unsubscribe(watch);
120
+ watches.delete(threadKey);
121
+ };
122
+
123
+ return {
124
+ atom,
125
+ get,
126
+ /**
127
+ * Starts an edit, replacing any edit already open on the thread. When the
128
+ * run leaves the queue the edit is removed and `onRunLeftQueue` receives
129
+ * it; if the run already left, that happens immediately.
130
+ */
131
+ begin(
132
+ threadKey: string,
133
+ edit: E,
134
+ watch: {
135
+ readonly runs: QueuedRunsAtom;
136
+ readonly onRunLeftQueue: (threadKey: string, edit: E) => void;
137
+ },
138
+ ) {
139
+ stopWatch(threadKey);
140
+ write(threadKey, edit);
141
+ const next: ExitWatch<E> = { ...watch, runId: edit.runId, cancel: null };
142
+ watches.set(threadKey, next);
143
+ subscribe(threadKey, next);
144
+ },
145
+ update(threadKey: string, f: (edit: E) => E) {
146
+ const edit = get(threadKey);
147
+ if (edit !== null) write(threadKey, f(edit));
148
+ },
149
+ end(threadKey: string) {
150
+ stopWatch(threadKey);
151
+ write(threadKey, null);
152
+ },
153
+ /**
154
+ * Holds the exit transition while a save is in flight; the save's own
155
+ * result decides the edit's fate.
156
+ */
157
+ suspendExitWatch(threadKey: string) {
158
+ const watch = watches.get(threadKey);
159
+ if (watch !== undefined) unsubscribe(watch);
160
+ },
161
+ /** Resumes after a failed save, handling an exit that happened meanwhile. */
162
+ resumeExitWatch(threadKey: string) {
163
+ const watch = watches.get(threadKey);
164
+ if (watch !== undefined && watch.cancel === null) subscribe(threadKey, watch);
165
+ },
166
+ };
167
+}