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 21, 14:45 UTC
fix(web): a stashed prompt keeps its machine mentions (#28780)
Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>
Victor committed
Nov 14, 2026 at 06:56 UTC
5e27bae22e628ff0fcdc9b329d66a5582a66d2d7
3 files changed
+213
-3
apps/web/src/components/ChatView.browser.test.tsx
+118
-1
@@ -1,6 +1,6 @@
1
import { createMemoryHistory } from "@tanstack/react-router";
2
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
3
-import { RunId, ThreadId } from "@t3tools/contracts";
3
+import { EnvironmentId, RunId, ThreadId } from "@t3tools/contracts";
4
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
5
import type * as Context from "effect/Context";
6
import { expect, it, vi } from "vite-plus/test";
@@ -13,6 +13,8 @@ import "~/components/ChatView";
13
import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
14
import { selectThreadDiffPanelSelection, useDiffPanelStore } from "~/diffPanelStore";
15
import { __setClientSettingsForTests } from "~/hooks/useSettings";
16
+import { environmentContextRecord } from "~/lib/composerContextRecords";
17
+import { usePromptStashStore } from "~/promptStashStore";
18
import { useRightPanelStore } from "~/rightPanelStore";
19
import { getRouter } from "~/router";
20
import { appAtomRegistry } from "~/rpc/atomRegistry";
@@ -20,12 +22,15 @@ import { environmentThreadDetails } from "~/state/threads";
22
import {
23
ENVIRONMENT_ID,
24
PROJECT_ID,
25
+ answerAssetUrls,
26
assistantItem,
27
dispatchedCommands,
28
emitThreadEvent,
29
+ hasPendingAssetUrl,
30
installFakeEnvironment,
31
rejectPendingCommand,
32
threadWithHistory,
33
+ threadWithQuestion,
34
type FakeDriver,
35
} from "../../test/fakeEnvironment";
36
import { act, fakeTimers, render } from "../../test/render";
@@ -45,6 +50,118 @@ vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({
50
trackRpcRequestSent: () => {},
51
}));
52
53
+it("a machine chip stashed in one thread restores with its machine in another", async () => {
54
+ const other = threadWithHistory("thread-stash-restore", 1);
55
+ const asking = threadWithQuestion("thread-stash-question", "Which file should change?");
56
+ using _environment = installFakeEnvironment([other, asking]);
57
+ __setClientSettingsForTests({
58
+ ...DEFAULT_CLIENT_SETTINGS,
59
+ onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
60
+ });
61
+ const draftId = DraftId.make("draft-stash-machine");
62
+ const machine = environmentContextRecord(EnvironmentId.make("environment-build"), "Build box");
63
+ const drafts = useComposerDraftStore.getState();
64
+ drafts.setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, {
65
+ threadId: ThreadId.make("thread-stash-machine"),
66
+ });
67
+ drafts.setPrompt(draftId, "Deploy on ");
68
+ drafts.addEnvironmentContexts(draftId, [machine]);
69
+ const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
70
+ await router.load();
71
+ await using _app = await render(<AppRoot router={router} />, {
72
+ // AppRoot brings its own router.
73
+ router: false,
74
+ });
75
+ const editor = page.getByTestId("composer-editor");
76
+ const pressStashShortcut = async () => {
77
+ await userEvent.click(editor);
78
+ await userEvent.keyboard("{ControlOrMeta>}s{/ControlOrMeta}");
79
+ };
80
+ await vi.waitFor(() => expect(editor.element().textContent).toContain("Deploy on"));
81
+ // A draft can't stash until the shell snapshot lists its project.
82
+ await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
83
+ await pressStashShortcut();
84
+ await vi.waitFor(() => expect(usePromptStashStore.getState().entries).toHaveLength(1));
85
+
86
+ // An answer carries no machines, so an open question refuses the restore and keeps the entry.
87
+ await router.navigate({ to: `/${ENVIRONMENT_ID}/${asking.id}` });
88
+ await expect.element(page.getByText("Which file should change?")).toBeVisible();
89
+ await userEvent.click(page.getByRole("button", { name: /^Stashed prompts/ }));
90
+ await userEvent.click(page.getByRole("button", { name: /^Restore stashed prompt/ }));
91
+ await vi.waitFor(() =>
92
+ expect(document.body.textContent).toContain("Stashed machines can't go in an answer"),
93
+ );
94
+ expect(usePromptStashStore.getState().entries).toHaveLength(1);
95
+
96
+ await router.navigate({ to: `/${ENVIRONMENT_ID}/${other.id}` });
97
+ await expect.element(page.getByText("Answer 0 for thread-stash-restore.")).toBeVisible();
98
+ await pressStashShortcut();
99
+
100
+ await vi.waitFor(() => expect(editor.element().textContent).toContain("Deploy on"));
101
+ expect(
102
+ useComposerDraftStore.getState().getComposerDraft(scopeThreadRef(ENVIRONMENT_ID, other.id))
103
+ ?.environmentContexts,
104
+ ).toEqual([machine]);
105
+ expect(
106
+ useComposerDraftStore.getState().getComposerDraft(draftId)?.environmentContexts ?? [],
107
+ ).toEqual([]);
108
+});
109
+
110
+it("a question that opens while a stashed file is checked keeps a machine stash", async () => {
111
+ const thread = threadWithHistory("thread-stash-late-question", 1);
112
+ const asking = threadWithQuestion("thread-stash-late-question", "Which file should change?");
113
+ const [request] = asking.runtimeRequests ?? [];
114
+ const question = asking.items.at(-1);
115
+ if (!request || !question) throw new Error("threadWithQuestion has no question");
116
+ using _environment = installFakeEnvironment([thread]);
117
+ __setClientSettingsForTests({
118
+ ...DEFAULT_CLIENT_SETTINGS,
119
+ onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
120
+ });
121
+ usePromptStashStore.getState().stashEntry({
122
+ id: "stash-late-question",
123
+ createdAt: "2026-01-01T00:00:00.000Z",
124
+ prompt: "Deploy on ",
125
+ attachments: [],
126
+ files: [
127
+ {
128
+ id: "file-notes",
129
+ name: "notes.txt",
130
+ mimeType: "text/plain",
131
+ sizeBytes: 5,
132
+ attachmentId: "attachment-notes",
133
+ environmentId: ENVIRONMENT_ID,
134
+ },
135
+ ],
136
+ droppedImageNames: [],
137
+ records: [environmentContextRecord(EnvironmentId.make("environment-build"), "Build box")],
138
+ });
139
+ const router = getRouter(
140
+ createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
141
+ );
142
+ await router.load();
143
+ await using _app = await render(<AppRoot router={router} />, {
144
+ // AppRoot brings its own router.
145
+ router: false,
146
+ });
147
+ await expect.element(page.getByText("Answer 0 for thread-stash-late-question.")).toBeVisible();
148
+ await userEvent.click(page.getByRole("button", { name: /^Stashed prompts/ }));
149
+ await userEvent.click(page.getByRole("button", { name: /^Restore stashed prompt/ }));
150
+
151
+ // The question opens while the restore still waits on the server's file check.
152
+ await vi.waitFor(() => expect(hasPendingAssetUrl()).toBe(true));
153
+ await emitThreadEvent(thread.id, { type: "turn-item.updated", payload: question });
154
+ await emitThreadEvent(thread.id, { type: "runtime-request.updated", payload: request });
155
+ await expect.element(page.getByText("Which file should change?")).toBeVisible();
156
+ await answerAssetUrls();
157
+
158
+ await vi.waitFor(() =>
159
+ expect(document.body.textContent).toContain("Stashed machines can't go in an answer"),
160
+ );
161
+ expect(usePromptStashStore.getState().entries).toHaveLength(1);
162
+ usePromptStashStore.getState().takeEntry("stash-late-question");
163
+});
164
+
165
it("a new draft does not load its reserved thread before the server lists it", async () => {
166
using _environment = installFakeEnvironment([]);
167
using fetchSpy = vi.spyOn(globalThis, "fetch");
apps/web/src/components/chat/useComposerStash.ts
+25
-1
@@ -145,6 +145,9 @@ export function useComposerStash(input: {
145
(store) => store.clearComposerPromptAndImages,
146
);
147
const setComposerDraftThreadContexts = useComposerDraftStore((store) => store.setThreadContexts);
148
+ const setComposerDraftEnvironmentContexts = useComposerDraftStore(
149
+ (store) => store.setEnvironmentContexts,
150
+ );
151
const [isStashMenuOpen, setIsStashMenuOpen] = useState(false);
152
// Each stash bumps the key; the badge replays its one-shot pulse animation per key.
153
const [stashPulseKey, setStashPulseKey] = useState(0);
@@ -159,6 +162,23 @@ export function useComposerStash(input: {
162
setStashPulseKey((key) => key + 1);
163
};
164
165
+ // Stable, so the check after the verify await sees a question that opened during it.
166
+ const refuseMachinesInAnswer = useStableCallback((menuEntry: PromptStashEntry) => {
167
+ // An answer to an agent's question carries no machines, so restoring here would drop them.
168
+ if (
169
+ pendingUserInputs.length > 0 &&
170
+ menuEntry.records?.some((record) => record.kind === "environment")
171
+ ) {
172
+ toastManager.add({
173
+ type: "error",
174
+ title: "Stashed machines can't go in an answer",
175
+ description: "Restore this prompt after the agent's question is answered.",
176
+ });
177
+ return true;
178
+ }
179
+ return false;
180
+ });
181
+
182
const restoreStashEntry = async (menuEntry: PromptStashEntry) => {
183
const filesToVerify = menuEntry.files ?? [];
184
if (filesToVerify.some((file) => file.environmentId !== environmentId)) {
@@ -169,6 +189,7 @@ export function useComposerStash(input: {
189
});
190
return;
191
}
192
+ if (refuseMachinesInAnswer(menuEntry)) return;
193
setIsStashMenuOpen(false);
194
195
// An expired upload restores as a needs-reattach row instead of a reference
@@ -191,7 +212,8 @@ export function useComposerStash(input: {
212
// so abort and leave the entry restorable where the user now is.
213
if (
214
isRevertingCheckpoint() ||
194
- !isComposerDraftTargetOpen(composerTargetKey(composerDraftTarget))
215
+ !isComposerDraftTargetOpen(composerTargetKey(composerDraftTarget)) ||
216
+ refuseMachinesInAnswer(menuEntry)
217
) {
218
return;
219
}
@@ -483,6 +505,7 @@ export function useComposerStash(input: {
505
const stashedRecords: ComposerContextRecord[] = [
506
...(replyTo ? [replyTo] : []),
507
...composerThreadContexts,
508
+ ...(getComposerDraft(composerDraftTarget)?.environmentContexts ?? []),
509
...readTerminalContexts().map(terminalContextRecord),
510
...composerReviewComments.map(reviewCommentContextRecord),
511
...composerPreviewAnnotations.map((annotation) =>
@@ -596,6 +619,7 @@ export function useComposerStash(input: {
619
clearComposerDraftPromptAndImages(stashTarget);
620
clearComposerDraftTerminalContexts(stashTarget);
621
setComposerDraftThreadContexts(stashTarget, []);
622
+ setComposerDraftEnvironmentContexts(stashTarget, []);
623
setComposerDraftReplyTo(stashTarget, null);
624
for (const comment of composerReviewComments) {
625
removeComposerDraftReviewComment(stashTarget, comment.id);
apps/web/test/fakeEnvironment.ts
+70
-1
@@ -2,17 +2,20 @@
2
// session that answers the shell, thread and config subscriptions from fixtures. Other RPCs
3
// stay pending so nothing retries on timers. Everything above the wire is the app's own.
4
import {
5
+ type AssetCreateUrlResult,
6
AuthStandardClientScopes,
7
EnvironmentId,
8
EventId,
9
ExecutionEnvironmentDescriptor,
10
MessageId,
11
+ NodeId,
12
OrchestrationV2DispatchCommandError,
13
ORCHESTRATION_PROTOCOL_VERSION,
14
ORCHESTRATION_V2_WS_METHODS,
15
ProjectId,
16
ProviderInstanceId,
17
RunId,
18
+ RuntimeRequestId,
19
ServerConfig,
20
ThreadId,
21
TurnItemId,
@@ -227,6 +230,7 @@ export interface FakeThread {
230
readonly providerThreads?: ReadonlyArray<OrchestrationV2ProviderThread>;
231
readonly runs: ReadonlyArray<OrchestrationV2Run>;
232
readonly items: ReadonlyArray<OrchestrationV2TurnItem>;
233
+ readonly runtimeRequests?: OrchestrationV2ThreadProjection["runtimeRequests"];
234
}
235
236
/** A thread of `turns` user prompts, each answered in markdown with a list and inline code. */
@@ -256,6 +260,47 @@ export function threadWithHistory(
260
return { id, title: `Thread ${name}`, modelSelection, runs, items };
261
}
262
263
+/** A one-turn thread whose agent waits on an answer to one question. */
264
+export function threadWithQuestion(name: string, question: string): FakeThread {
265
+ const thread = threadWithHistory(name, 1);
266
+ const requestId = RuntimeRequestId.make(`${name}-request`);
267
+ return {
268
+ ...thread,
269
+ items: [
270
+ ...thread.items,
271
+ {
272
+ ...base(thread.id, RunId.make(`${name}-run-0`), `${name}-question`, 2),
273
+ type: "user_input_request",
274
+ requestId,
275
+ responseMode: "message",
276
+ questions: [
277
+ {
278
+ id: "choice",
279
+ header: "Choice",
280
+ question,
281
+ required: true,
282
+ allowCustomAnswer: false,
283
+ options: [{ label: "Continue", value: "continue", description: "Resume work" }],
284
+ },
285
+ ],
286
+ },
287
+ ],
288
+ runtimeRequests: [
289
+ {
290
+ id: requestId,
291
+ nodeId: NodeId.make(`${name}-node`),
292
+ providerTurnId: null,
293
+ nativeRequestRef: null,
294
+ kind: "user_input",
295
+ status: "pending",
296
+ responseCapability: { type: "message" },
297
+ createdAt: AT,
298
+ resolvedAt: null,
299
+ },
300
+ ],
301
+ };
302
+}
303
+
304
function shellOf(thread: FakeThread): OrchestrationV2ThreadShell {
305
const latest = thread.runs.at(-1);
306
const modelSelection = thread.modelSelection ?? MODEL;
@@ -341,7 +386,7 @@ function projectionOf(thread: FakeThread): OrchestrationV2ThreadProjection {
386
providerSessions: [],
387
providerThreads: [...(thread.providerThreads ?? [])],
388
providerTurns: [],
344
- runtimeRequests: [],
389
+ runtimeRequests: [...(thread.runtimeRequests ?? [])],
390
messages: [],
391
plans: [],
392
turnItems: [...thread.items],
@@ -368,6 +413,7 @@ let pendingDispatches: Array<{
413
readonly command: OrchestrationV2Command;
414
readonly reply: Deferred.Deferred<never, OrchestrationV2DispatchCommandError>;
415
}> = [];
416
+let pendingAssetUrls: Array<Deferred.Deferred<AssetCreateUrlResult>> = [];
417
let sequence = 1;
418
let vcsStatusSubscriber: Queue.Queue<VcsStatusStreamEvent> | null = null;
419
@@ -396,6 +442,13 @@ const handlers: Record<string, (input: never) => unknown> = {
442
pendingDispatches.push({ command, reply });
443
return Deferred.await(reply);
444
}),
445
+ // Held like any other unanswered call, until `answerAssetUrls`.
446
+ [WS_METHODS.assetsCreateUrl]: () =>
447
+ Effect.suspend(() => {
448
+ const reply = Deferred.makeUnsafe<AssetCreateUrlResult>();
449
+ pendingAssetUrls.push(reply);
450
+ return Deferred.await(reply);
451
+ }),
452
[WS_METHODS.subscribeTerminalMetadata]: () =>
453
subscribe<TerminalMetadataStreamEvent>([{ type: "snapshot", terminals: [] }], (queue) => {
454
terminalMetadataSubscriber = queue;
@@ -544,6 +597,7 @@ export function installFakeEnvironment(
597
acceptCommands = false;
598
holdCommand = () => false;
599
pendingDispatches = [];
600
+ pendingAssetUrls = [];
601
},
602
};
603
}
@@ -564,6 +618,21 @@ export async function rejectPendingCommand(message: string): Promise<void> {
618
);
619
}
620
621
+export function hasPendingAssetUrl(): boolean {
622
+ return pendingAssetUrls.length > 0;
623
+}
624
+
625
+/** Answers every held asset URL request, as a server that still has the file. */
626
+export async function answerAssetUrls(): Promise<void> {
627
+ const replies = pendingAssetUrls;
628
+ pendingAssetUrls = [];
629
+ for (const reply of replies) {
630
+ await Effect.runPromise(
631
+ Deferred.succeed(reply, { relativeUrl: "/api/assets/fake", expiresAt: 4_102_444_800_000 }),
632
+ );
633
+ }
634
+}
635
+
636
/** Commands the app dispatched to the environment, oldest first. */
637
export function dispatchedCommands(): ReadonlyArray<OrchestrationV2Command> {
638
return dispatched;