The best way to control Claude Code, Codex and more from any computer or phone
fix(web,mobile): side chats keep your attachments and context (#38350)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net>
Bilal Bakr committed
Nov 19, 2026 at 02:36 UTC
052ca497cf1103b001327bcd964188a71dfec213
29 files changed
+572
-219
apps/mobile/src/features/threads/useStartSideChat.ts
+11
-10
@@ -1,6 +1,6 @@
1
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2
import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3
-import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
3
+import type { StartThreadTurnInput } from "@t3tools/client-runtime/operations";
4
import {
5
isAtomCommandInterrupted,
6
squashAtomCommandFailure,
@@ -24,8 +24,13 @@ import { useAtomCommand } from "../../state/use-atom-command";
24
import { waitForThreadShell } from "./threadForkNavigation";
25
import { useOpenLinkedThread } from "./useOpenLinkedThread";
26
27
+export type SideChatMessage = Pick<
28
+ StartThreadTurnInput["message"],
29
+ "text" | "attachments" | "context"
30
+> & { readonly titleSeed: string };
31
+
32
/**
28
- * Forks `source` at its latest stable point into a side chat, sends `prompt` there, and opens
33
+ * Forks `source` at its latest stable point into a side chat, sends `message` there, and opens
34
* it like any linked thread. Resolves false when the side chat did not start. `settings` are
35
* what the parent's composer would send, which its thread gets only on its next send.
36
*/
@@ -48,7 +53,7 @@ export function useStartSideChat() {
53
54
return async (
55
source: ScopedThreadRef,
51
- prompt: string,
56
+ message: SideChatMessage,
57
settings: { readonly runtimeMode: RuntimeMode; readonly modelSelection: ModelSelection },
58
): Promise<boolean> => {
59
const targetThreadId = ThreadId.make(uuidv4());
@@ -101,18 +106,14 @@ export function useStartSideChat() {
106
return false;
107
}
108
}
109
+ const { titleSeed, ...content } = message;
110
const turn = await startTurn({
111
environmentId: source.environmentId,
112
input: {
113
threadId: targetThreadId,
108
- message: {
109
- messageId: MessageId.make(uuidv4()),
110
- role: "user",
111
- text: prompt,
112
- attachments: [],
113
- },
114
+ message: { messageId: MessageId.make(uuidv4()), role: "user", ...content },
115
modelSelection: settings.modelSelection,
115
- titleSeed: deriveThreadTitleSeed({ text: prompt, attachments: [] }, m),
116
+ titleSeed,
117
runtimeMode: settings.runtimeMode,
118
interactionMode: "default",
119
createdAt: new Date().toISOString(),
apps/mobile/src/i18n/translations/de.json
-2
@@ -1580,8 +1580,6 @@
1580
"b02695b75d8b050d": "Deine Bearbeitung ist noch im Eingabefeld.",
1581
"6ad508d2af838010": "Sie wurde möglicherweise bereits gestartet. Deine Bearbeitung ist noch im Eingabefeld.",
1582
"74e7e5c0536cda02": "Nebenchat nicht gestartet",
1583
- "be6231ac5b08f35e": "Nebenchats nehmen nur Text an",
1584
- "faf9ee0a28119e10": "Entferne die Anhänge und den Kontext und sende dann erneut.",
1583
"a0269861cbd8c727": "Eine Nebenfrage stellen",
1584
"d49fc7ca60395d59": "Gib die Frage nach {command} ein und sende sie dann.",
1585
"2498db230c4b87b6": "Zu viel Kontext",
apps/mobile/src/i18n/translations/en.json
-2
@@ -1580,8 +1580,6 @@
1580
"b02695b75d8b050d": "Your edit is still in the composer.",
1581
"6ad508d2af838010": "It may have already started. Your edit is still in the composer.",
1582
"74e7e5c0536cda02": "Side chat not started",
1583
- "be6231ac5b08f35e": "Side chats take text only",
1584
- "faf9ee0a28119e10": "Remove the attachments and context, then send it again.",
1583
"a0269861cbd8c727": "Ask a side question",
1584
"d49fc7ca60395d59": "Type the question after {command}, then send it.",
1585
"2498db230c4b87b6": "Too much context",
apps/mobile/src/i18n/translations/es.json
-2
@@ -1580,8 +1580,6 @@
1580
"b02695b75d8b050d": "Tu edición sigue en el cuadro de mensaje.",
1581
"6ad508d2af838010": "Puede que ya haya empezado. Tu edición sigue en el cuadro de mensaje.",
1582
"74e7e5c0536cda02": "Chat lateral no iniciado",
1583
- "be6231ac5b08f35e": "Los chats laterales solo admiten texto",
1584
- "faf9ee0a28119e10": "Quita los adjuntos y el contexto, y vuelve a enviarlo.",
1583
"a0269861cbd8c727": "Haz una pregunta aparte",
1584
"d49fc7ca60395d59": "Escribe la pregunta después de {command} y envíala.",
1585
"2498db230c4b87b6": "Demasiado contexto",
apps/mobile/src/i18n/translations/fr.json
-2
@@ -1580,8 +1580,6 @@
1580
"b02695b75d8b050d": "Votre modification est toujours dans la zone de saisie.",
1581
"6ad508d2af838010": "Il a peut-être déjà démarré. Votre modification est toujours dans la zone de saisie.",
1582
"74e7e5c0536cda02": "Discussion annexe non démarrée",
1583
- "be6231ac5b08f35e": "Les discussions annexes n’acceptent que du texte",
1584
- "faf9ee0a28119e10": "Retirez les pièces jointes et le contexte, puis renvoyez.",
1583
"a0269861cbd8c727": "Poser une question annexe",
1584
"d49fc7ca60395d59": "Tapez la question après {command}, puis envoyez-la.",
1585
"2498db230c4b87b6": "Trop de contexte",
apps/mobile/src/i18n/translations/ja.json
-2
@@ -1580,8 +1580,6 @@
1580
"b02695b75d8b050d": "編集内容は入力欄に残っています。",
1581
"6ad508d2af838010": "すでに開始されている可能性があります。編集内容は入力欄に残っています。",
1582
"74e7e5c0536cda02": "サイドチャットが開始されていません",
1583
- "be6231ac5b08f35e": "サイドチャットではテキストのみ使用できます",
1584
- "faf9ee0a28119e10": "添付ファイルとコンテキストを削除してから、もう一度送信してください。",
1583
"a0269861cbd8c727": "横から質問する",
1584
"d49fc7ca60395d59": "{command} の後に質問を入力して送信してください。",
1585
"2498db230c4b87b6": "コンテキストが多すぎます",
apps/mobile/src/i18n/translations/ko.json
-2
@@ -1580,8 +1580,6 @@
1580
"b02695b75d8b050d": "편집 내용은 입력창에 그대로 있습니다.",
1581
"6ad508d2af838010": "이미 시작되었을 수 있습니다. 편집 내용은 입력창에 그대로 있습니다.",
1582
"74e7e5c0536cda02": "사이드 채팅이 시작되지 않음",
1583
- "be6231ac5b08f35e": "사이드 채팅은 텍스트만 받습니다",
1584
- "faf9ee0a28119e10": "첨부 파일과 컨텍스트를 제거한 다음 다시 보내세요.",
1583
"a0269861cbd8c727": "곁가지 질문하기",
1584
"d49fc7ca60395d59": "{command} 뒤에 질문을 입력한 뒤 보내세요.",
1585
"2498db230c4b87b6": "컨텍스트가 너무 많습니다",
apps/mobile/src/i18n/translations/pt-BR.json
-2
@@ -1580,8 +1580,6 @@
1580
"b02695b75d8b050d": "Sua edição continua no editor de mensagens.",
1581
"6ad508d2af838010": "Ela pode já ter começado. Sua edição continua no editor de mensagens.",
1582
"74e7e5c0536cda02": "Chat paralelo não iniciado",
1583
- "be6231ac5b08f35e": "Chats paralelos aceitam só texto",
1584
- "faf9ee0a28119e10": "Remova os anexos e o contexto e envie novamente.",
1583
"a0269861cbd8c727": "Fazer uma pergunta paralela",
1584
"d49fc7ca60395d59": "Digite a pergunta depois de {command} e envie.",
1585
"2498db230c4b87b6": "Contexto demais",
apps/mobile/src/i18n/translations/ru.json
-2
@@ -1580,8 +1580,6 @@
1580
"b02695b75d8b050d": "Ваша правка всё ещё в поле ввода.",
1581
"6ad508d2af838010": "Возможно, оно уже начало выполняться. Ваша правка всё ещё в поле ввода.",
1582
"74e7e5c0536cda02": "Боковой чат не начат",
1583
- "be6231ac5b08f35e": "Боковые чаты принимают только текст",
1584
- "faf9ee0a28119e10": "Удалите вложения и контекст, затем отправьте снова.",
1583
"a0269861cbd8c727": "Задать вопрос в сторону",
1584
"d49fc7ca60395d59": "Введите вопрос после {command} и отправьте.",
1585
"2498db230c4b87b6": "Слишком много контекста",
apps/mobile/src/i18n/translations/sv.json
-2
@@ -1580,8 +1580,6 @@
1580
"b02695b75d8b050d": "Din redigering finns kvar i inmatningsfältet.",
1581
"6ad508d2af838010": "Det kan redan ha startat. Din redigering finns kvar i inmatningsfältet.",
1582
"74e7e5c0536cda02": "Sidochatten startades inte",
1583
- "be6231ac5b08f35e": "Sidochattar tar bara emot text",
1584
- "faf9ee0a28119e10": "Ta bort bilagorna och kontexten och skicka sedan igen.",
1583
"a0269861cbd8c727": "Ställ en sidofråga",
1584
"d49fc7ca60395d59": "Skriv frågan efter {command} och skicka den sedan.",
1585
"2498db230c4b87b6": "För mycket kontext",
apps/mobile/src/i18n/translations/zh.json
-2
@@ -1581,8 +1581,6 @@
1581
"b02695b75d8b050d": "你的编辑仍在输入框中。",
1582
"6ad508d2af838010": "它可能已经开始处理。你的编辑仍在输入框中。",
1583
"74e7e5c0536cda02": "侧聊未开始",
1584
- "be6231ac5b08f35e": "侧聊只支持文字",
1585
- "faf9ee0a28119e10": "请移除附件和上下文后再发送。",
1584
"a0269861cbd8c727": "问一个旁支问题",
1585
"d49fc7ca60395d59": "在 {command} 后输入问题,然后发送。",
1586
"2498db230c4b87b6": "上下文过多",
apps/mobile/src/state/thread-task-permissions.test.ts
+93
-13
@@ -11,6 +11,7 @@ import {
11
ThreadId,
12
TurnItemId,
13
type ModelSelection,
14
+ type OrchestrationMessageContext,
15
type OrchestrationV2ThreadProjection,
16
type RuntimeMode,
17
type ServerConfig,
@@ -35,6 +36,7 @@ const state = vi.hoisted(() => ({
36
draft: {
37
text: "Keep my draft",
38
attachments: [] as DraftComposerImageAttachment[],
39
+ context: undefined as OrchestrationMessageContext | undefined,
40
modelSelection: undefined as ModelSelection | undefined,
41
runtimeMode: undefined as RuntimeMode | undefined,
42
},
@@ -48,6 +50,8 @@ const state = vi.hoisted(() => ({
50
setFreshPending: vi.fn(),
51
clearDraft: vi.fn(),
52
appendAttachments: vi.fn(),
53
+ mergeDraft: vi.fn(),
54
+ fileHolds: [] as string[],
55
questionDrafts: {} as Record<
56
string,
57
{ text: string; attachments: DraftComposerImageAttachment[] }
@@ -105,8 +109,33 @@ vi.mock("@t3tools/client-runtime/state/context-window", async (importOriginal) =
109
: null,
110
}));
111
vi.mock("../lib/clock", () => ({ useNowMinuteMs: () => 0 }));
108
-vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: vi.fn() }));
112
+vi.mock("../lib/attachmentUpload", async () => {
113
+ const { Effect } = await import("effect");
114
+ return {
115
+ prepareTurnAttachments: vi.fn(
116
+ (input: { readonly attachments: ReadonlyArray<{ readonly id: string }> }) =>
117
+ Effect.succeed({
118
+ status: "ready",
119
+ attachments: input.attachments.map((attachment) => ({
120
+ type: "image",
121
+ id: `uploaded-${attachment.id}`,
122
+ name: "shot.png",
123
+ mimeType: "image/png",
124
+ sizeBytes: 1,
125
+ })),
126
+ }),
127
+ ),
128
+ };
129
+});
130
vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid" }));
131
+vi.mock("../lib/composerAttachmentPreviewRetention", () => ({
132
+ retainComposerAttachmentFileForPreview: (attachment: { readonly fileUri: string }) => {
133
+ state.fileHolds.push(attachment.fileUri);
134
+ return () => {
135
+ state.fileHolds.splice(state.fileHolds.indexOf(attachment.fileUri), 1);
136
+ };
137
+ },
138
+}));
139
vi.mock("./queued-run-edit", () => ({
140
useQueuedRunEdit: () => null,
141
getQueuedRunEdit: () => null,
@@ -169,6 +198,7 @@ vi.mock("./composer-attachment-uploads", async () => {
198
composerAttachmentUploadsAtom: Atom.make({}),
199
composerAttachmentUploadBlockReason: () => null,
200
composerAttachmentsStillUploading: () => false,
201
+ uploadComposerAttachmentShared: vi.fn(),
202
};
203
});
204
vi.mock("./use-composer-drafts", async () => {
@@ -189,7 +219,7 @@ vi.mock("./use-composer-drafts", async () => {
219
scheduleUnusedComposerAttachmentCleanup: () => {},
220
appendComposerDraftAttachments: state.appendAttachments,
221
appendComposerDraftText: vi.fn(),
192
- mergeComposerDraftContent: vi.fn(),
222
+ mergeComposerDraftContent: state.mergeDraft,
223
removeComposerDraftAttachment: vi.fn(),
224
useComposerDraft: () => state.draft,
225
useComposerDraftSettings: () => state.draft,
@@ -197,6 +227,8 @@ vi.mock("./use-composer-drafts", async () => {
227
};
228
});
229
vi.mock("../lib/composerImages", () => ({
230
+ isFileBackedComposerAttachment: (attachment: { readonly fileUri?: string }) =>
231
+ attachment.fileUri !== undefined,
232
convertPastedImagesToAttachments: vi.fn(),
233
pickComposerFiles: vi.fn(),
234
pickComposerMedia: vi.fn(),
@@ -224,6 +256,7 @@ beforeEach(() => {
256
state.draft = {
257
text: "Keep my draft",
258
attachments: [],
259
+ context: undefined,
260
modelSelection: undefined,
261
runtimeMode: undefined,
262
};
@@ -431,25 +464,72 @@ describe("mobile task permissions", () => {
464
expect(await composer.onSendMessage()).toBeNull();
465
expect(startSideChat).toHaveBeenCalledExactlyOnceWith(
466
{ environmentId: "secondary", threadId: "thread" },
434
- "why does this fail?",
467
+ { text: "why does this fail?", attachments: [], titleSeed: "why does this fail?" },
468
{ runtimeMode: "approval-required", modelSelection: selection },
469
);
470
expect(state.enqueue).not.toHaveBeenCalled();
471
expect(state.clearDraft).toHaveBeenCalled();
472
440
- // An attachment added while the side chat starts stays in the draft.
473
+ // Attachments and context go to the side chat, bound to their uploaded ids.
474
+ vi.clearAllMocks();
475
+ const imageRecord = {
476
+ version: 1,
477
+ kind: "image",
478
+ contextId: "image-shot",
479
+ label: "shot.png",
480
+ attachmentId: "shot",
481
+ name: "shot.png",
482
+ mimeType: "image/png",
483
+ sizeBytes: 1,
484
+ } as OrchestrationMessageContext["records"][number];
485
+ state.draft = {
486
+ ...state.draft,
487
+ text: "/side what is this?",
488
+ attachments: [
489
+ { id: "shot", type: "image", name: "shot.png" } as DraftComposerImageAttachment,
490
+ ],
491
+ context: { version: 1, records: [imageRecord] },
492
+ };
493
+ expect(await useThreadComposerState({ startSideChat }).onSendMessage()).toBeNull();
494
+ expect(startSideChat).toHaveBeenCalledExactlyOnceWith(
495
+ { environmentId: "secondary", threadId: "thread" },
496
+ expect.objectContaining({
497
+ text: "what is this?",
498
+ attachments: [expect.objectContaining({ id: "uploaded-shot" })],
499
+ context: { version: 1, records: [{ ...imageRecord, attachmentId: "uploaded-shot" }] },
500
+ }),
501
+ expect.anything(),
502
+ );
503
+ expect(state.clearDraft).toHaveBeenCalled();
504
+ state.draft = { ...state.draft, context: undefined };
505
+
506
+ // A failed start restores the draft: text first, since the merge caps attachments, then
507
+ // the uncapped attachments. The local file stays on disk meanwhile, and no send runs from
508
+ // the half-restored draft.
509
vi.clearAllMocks();
510
+ let heldDuringStart: string[] = [];
511
startSideChat.mockImplementationOnce(async () => {
443
- state.draft = {
444
- ...state.draft,
445
- attachments: [{ id: "added" } as DraftComposerImageAttachment],
446
- };
447
- return true;
512
+ heldDuringStart = [...state.fileHolds];
513
+ return false;
514
});
449
- state.draft = { ...state.draft, text: "/side again?", attachments: [] };
450
- expect(await useThreadComposerState({ startSideChat }).onSendMessage()).toBeNull();
451
- expect(startSideChat).toHaveBeenCalledOnce();
452
- expect(state.clearDraft).not.toHaveBeenCalled();
515
+ const shot = { id: "shot", fileUri: "file:///shot.png" } as DraftComposerImageAttachment;
516
+ const sent = { ...state.draft, attachments: [shot] };
517
+ state.draft = sent;
518
+ const restoring = useThreadComposerState({ startSideChat });
519
+ const restoreOrder: string[] = [];
520
+ state.mergeDraft.mockImplementationOnce(async (_key, content) => {
521
+ state.draft = { ...sent, text: "new text" };
522
+ await restoring.onSendMessage();
523
+ restoreOrder.push(`merge ${content.text}`);
524
+ });
525
+ state.appendAttachments.mockImplementationOnce((_key, attachments, options) =>
526
+ restoreOrder.push(`append ${attachments.length} restore=${options.restore}`),
527
+ );
528
+ expect(await restoring.onSendMessage()).toBeNull();
529
+ expect(restoreOrder).toEqual(["merge /side what is this?", "append 1 restore=true"]);
530
+ expect(state.enqueue).not.toHaveBeenCalled();
531
+ expect(heldDuringStart).toEqual(["file:///shot.png"]);
532
+ expect(state.fileHolds).toEqual([]);
533
// A model the send would refuse does not start a side chat either.
534
vi.clearAllMocks();
535
state.serverConfig = {
apps/mobile/src/state/use-thread-composer-state.ts
+93
-45
@@ -45,9 +45,15 @@ import {
45
type CodexFeedbackSubmission,
46
} from "@t3tools/client-runtime/state/threads";
47
import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
48
+import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
49
import { upgradeLegacyContextMessage } from "@t3tools/shared/composerContextLegacy";
50
import { restoreAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences";
50
-import { composerContextSendBlockReason, reidentifyComposerContext } from "../lib/composerContext";
51
+import {
52
+ composerContextSendBlockReason,
53
+ reidentifyComposerContext,
54
+ serializeComposerMessageForServer,
55
+ uploadedComposerContext,
56
+} from "../lib/composerContext";
57
import { uuidv4 } from "../lib/uuid";
58
import { useNowMinuteMs } from "../lib/clock";
59
@@ -57,7 +63,11 @@ import {
63
isModelSelectionUnavailable,
64
} from "../lib/modelOptions";
65
60
-import type { DraftComposerImageAttachment } from "../lib/composerImages";
66
+import {
67
+ type DraftComposerImageAttachment,
68
+ isFileBackedComposerAttachment,
69
+} from "../lib/composerImages";
70
+import { retainComposerAttachmentFileForPreview } from "../lib/composerAttachmentPreviewRetention";
71
import { scopedThreadKey } from "../lib/scopedEntities";
72
import { buildThreadFeed, createThreadFeedCache } from "../lib/threadActivity";
73
import {
@@ -71,6 +81,7 @@ import {
81
import { threadAllowsProviderSwitch } from "./thread-provider-switching";
82
import { appAtomRegistry } from "./atom-registry";
83
import { pendingThreadCreationMessage } from "./pending-thread-creation";
84
+import type { SideChatMessage } from "../features/threads/useStartSideChat";
85
import {
86
composerAttachmentUploadBlockReason,
87
composerAttachmentUploadsAtom,
@@ -211,10 +222,10 @@ export function useThreadDraftForThread(input: {
222
}
223
224
export function useThreadComposerState(input: {
214
- /** Forks the thread into a side chat that gets `prompt`; resolves false when it did not start. */
225
+ /** Forks the thread into a side chat that gets `message`; resolves false when it did not start. */
226
readonly startSideChat: (
227
source: ScopedThreadRef,
217
- prompt: string,
228
+ message: SideChatMessage,
229
settings: { readonly runtimeMode: RuntimeMode; readonly modelSelection: ModelSelection },
230
) => Promise<boolean>;
231
}) {
@@ -634,6 +645,8 @@ export function useThreadComposerState(input: {
645
return null;
646
}
647
648
+ // Until a side chat start settles, its draft may be only partly back in the composer.
649
+ if (startingSideChatRef.current) return null;
650
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
651
const draft = getComposerDraftSnapshot(threadKey);
652
if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
@@ -666,47 +679,100 @@ export function useThreadComposerState(input: {
679
);
680
Dialog.alert(title, detail);
681
};
682
+ // Recovery preserves over-cap attachments; require trimming or outbox delivery would reject indefinitely.
683
+ if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
684
+ Dialog.alert(
685
+ m(msg("Too many attachments")),
686
+ m(
687
+ msg("Remove attachments until there are at most {max}.", {
688
+ max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
689
+ }),
690
+ ),
691
+ );
692
+ return null;
693
+ }
694
+
695
+ const contextBlockReason = composerContextSendBlockReason(draft.context);
696
+ if (contextBlockReason) {
697
+ Dialog.alert(m(msg("Too much context")), contextBlockReason);
698
+ return null;
699
+ }
700
+
701
// A redirect's text answers its approval, so `/side` there is that text, not the command.
702
const sideChatCommand = beforeDispatch === undefined ? parseSideChatCommand(text) : null;
703
if (sideChatCommand) {
704
if (sideChatUnavailableReason !== null) {
705
Dialog.alert(m(msg("Side chat not started")), sideChatUnavailableReason);
674
- } else if (attachments.length > 0 || (draft.context?.records.length ?? 0) > 0) {
675
- Dialog.alert(
676
- m(msg("Side chats take text only")),
677
- m(msg("Remove the attachments and context, then send it again.")),
678
- );
679
- } else if (sideChatCommand.prompt.length === 0) {
706
+ } else if (
707
+ sideChatCommand.prompt.length === 0 &&
708
+ attachments.length === 0 &&
709
+ (draft.context?.records.length ?? 0) === 0
710
+ ) {
711
Dialog.alert(
712
m(msg("Ask a side question")),
713
m(msg("Type the question after {command}, then send it.", { command: "/side" })),
714
);
715
} else if (modelUnavailable) {
716
alertModelUnavailable();
686
- } else if (!startingSideChatRef.current) {
717
+ } else {
718
startingSideChatRef.current = true;
688
- const started = await input
689
- .startSideChat(
719
+ // Cleared at send, like a queued message, so nothing in it can vanish mid-start. The
720
+ // holds keep the local files until the side chat has them or the draft has them back.
721
+ const fileHolds = attachments
722
+ .filter(isFileBackedComposerAttachment)
723
+ .map(retainComposerAttachmentFileForPreview);
724
+ clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
725
+ const started = await settlePromise(async () => {
726
+ const prepared = await Effect.runPromise(
727
+ prepareTurnAttachments({
728
+ environmentId: thread.environmentId,
729
+ attachments,
730
+ supportsImageUploads: true,
731
+ uploadAttachment: (attachment) =>
732
+ uploadComposerAttachmentShared(thread.environmentId, attachment),
733
+ }),
734
+ );
735
+ if (prepared.status !== "ready") return false;
736
+ return input.startSideChat(
737
{ environmentId: thread.environmentId, threadId: thread.id },
691
- sideChatCommand.prompt,
738
+ {
739
+ ...serializeComposerMessageForServer(
740
+ restoreAttachmentOnlyBootstrapPrompt(
741
+ sideChatCommand.prompt,
742
+ prepared.attachments.length > 0,
743
+ ),
744
+ uploadedComposerContext(draft.context, attachments, prepared.attachments),
745
+ ),
746
+ attachments: prepared.attachments,
747
+ titleSeed: deriveThreadTitleSeed({ text: sideChatCommand.prompt, attachments }, m),
748
+ },
749
{
750
runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
751
modelSelection,
752
},
696
- )
697
- .finally(() => {
698
- startingSideChatRef.current = false;
699
- });
700
- // Clear only what was sent; the draft may have changed while the side chat started.
701
- const current = getComposerDraftSnapshot(threadKey);
702
- if (
703
- started &&
704
- current.text === draft.text &&
705
- current.attachments.length === 0 &&
706
- (current.context?.records.length ?? 0) === 0
707
- ) {
708
- clearComposerDraftContent(threadKey);
753
+ );
754
+ });
755
+ if (AsyncResult.isSuccess(started) && started.value) {
756
+ scheduleUnusedComposerAttachmentCleanup(attachments);
757
+ } else {
758
+ // Restore with uncapped append; a capped merge could drop attachments added meanwhile.
759
+ // A failed disk write still leaves the merged draft in memory, and the append saves again.
760
+ await mergeComposerDraftContent(threadKey, {
761
+ text: draft.text,
762
+ context: draft.context,
763
+ attachments: [],
764
+ }).catch(() => undefined);
765
+ appendComposerDraftAttachments(threadKey, attachments, { restore: true });
766
+ if (AsyncResult.isFailure(started)) {
767
+ const error = squashAtomCommandFailure(started);
768
+ Dialog.alert(
769
+ m(msg("Side chat not started")),
770
+ error instanceof Error ? error.message : m(msg("Could not start a side chat.")),
771
+ );
772
+ }
773
}
774
+ startingSideChatRef.current = false;
775
+ for (const release of fileHolds) release();
776
}
777
return null;
778
}
@@ -723,24 +789,6 @@ export function useThreadComposerState(input: {
789
clearComposerDraftContent(threadKey);
790
return null;
791
}
726
- // Recovery preserves over-cap attachments; require trimming or outbox delivery would reject indefinitely.
727
- if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
728
- Dialog.alert(
729
- m(msg("Too many attachments")),
730
- m(
731
- msg("Remove attachments until there are at most {max}.", {
732
- max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
733
- }),
734
- ),
735
- );
736
- return null;
737
- }
738
-
739
- const contextBlockReason = composerContextSendBlockReason(draft.context);
740
- if (contextBlockReason) {
741
- Dialog.alert(m(msg("Too much context")), contextBlockReason);
742
- return null;
743
- }
792
793
if (modelUnavailable) {
794
alertModelUnavailable();
apps/web/src/components/ChatView.browser.test.tsx
+82
@@ -662,3 +662,85 @@ it("selecting a side-chat tab focuses that side chat's composer", async () => {
662
await expect.element(sideEditor).toHaveFocus();
663
await expect.element(mainEditor).toHaveTextContent("main draft");
664
});
665
+
666
+it("/side sends the draft's attachments and context, and keeps them when it does not start", async () => {
667
+ await page.viewport(1400, 900);
668
+ const thread = threadWithHistory("side-attachments", 1);
669
+ let holdFork = false;
670
+ using _environment = installFakeEnvironment([thread], {
671
+ acceptCommands: true,
672
+ holdCommand: (command) => holdFork && command.type === "thread.fork",
673
+ });
674
+ __setClientSettingsForTests({
675
+ ...DEFAULT_CLIENT_SETTINGS,
676
+ onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
677
+ });
678
+ const router = getRouter(
679
+ createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
680
+ );
681
+ await router.load();
682
+ await using _app = await render(<AppRoot router={router} />, {
683
+ // AppRoot brings its own router.
684
+ router: false,
685
+ });
686
+ using _uploads = acceptAttachmentUploads();
687
+ await expect.element(page.getByText(`Answer 0 for ${thread.id}.`)).toBeVisible();
688
+
689
+ const editor = page.getByRole("textbox", { name: `Message ${thread.title}`, exact: true });
690
+ const image = page.getByRole("img", { name: "shot.png" });
691
+ const sendImageToSideChat = async () => {
692
+ await userEvent.click(editor);
693
+ const clipboardData = new DataTransfer();
694
+ clipboardData.items.add(new File([PNG], "shot.png", { type: "image/png" }));
695
+ editor
696
+ .element()
697
+ .dispatchEvent(
698
+ new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }),
699
+ );
700
+ await expect.element(image).toBeVisible();
701
+ await userEvent.keyboard("/side what is this?{Enter}");
702
+ await expect.element(image).not.toBeInTheDocument();
703
+ };
704
+ const sentMessage = (fields: Record<string, unknown>) =>
705
+ vi.waitFor(() =>
706
+ expect(dispatchedCommands()).toContainEqual(
707
+ expect.objectContaining({ type: "message.dispatch", ...fields }),
708
+ ),
709
+ );
710
+
711
+ await sendImageToSideChat();
712
+ await sentMessage({
713
+ text: "what is this?",
714
+ attachments: [expect.objectContaining({ type: "image", id: "upload-1" })],
715
+ context: {
716
+ version: 1,
717
+ records: [expect.objectContaining({ kind: "image", attachmentId: "upload-1" })],
718
+ },
719
+ });
720
+
721
+ // A reply alone is enough to send.
722
+ await page.getByRole("button", { name: "Reply to this response" }).first().click();
723
+ await userEvent.click(editor);
724
+ await userEvent.keyboard("/side {Enter}");
725
+ await sentMessage({
726
+ context: expect.objectContaining({ records: [expect.objectContaining({ kind: "response" })] }),
727
+ });
728
+
729
+ // A failed start puts the message back after the draft typed meanwhile.
730
+ holdFork = true;
731
+ await sendImageToSideChat();
732
+ await userEvent.keyboard("next draft");
733
+ await vi.waitFor(() =>
734
+ expect(dispatchedCommands().filter((command) => command.type === "thread.fork")).toHaveLength(
735
+ 3,
736
+ ),
737
+ );
738
+ await rejectPendingCommand("Side chats are paused.");
739
+ await expect.element(image).toBeVisible();
740
+ await vi.waitFor(() =>
741
+ expect((editor.element() as HTMLElement).innerText.split("\n").filter(Boolean)).toEqual([
742
+ "next draft",
743
+ "/side what is this?",
744
+ ]),
745
+ );
746
+});
apps/web/src/components/ChatView.tsx
+1
-1
@@ -2882,7 +2882,7 @@ export default function ChatView(props: ChatViewProps) {
2882
? gt("Available once the thread's worktree is set up.")
2883
: null;
2884
const openSideChatStable = useStableCallback(() => void sideChat.open());
2885
- const sendSideChatStable = useStableCallback((prompt: string) => sideChat.open(prompt));
2885
+ const sendSideChatStable = useStableCallback(sideChat.open);
2886
const { onConfirmRevertStable, onForkFromRunStable, onRevertTimelineTurnStable } =
2887
useTimelineRewind({
2888
environmentId,
apps/web/src/components/chat/chatViewSend.ts
+42
-10
@@ -272,26 +272,58 @@ export async function rewindToMessage(input: {
272
}
273
}
274
275
+function withRestored<T>(
276
+ existing: ReadonlyArray<T> | undefined,
277
+ restored: ReadonlyArray<T>,
278
+ key: (item: T) => string,
279
+): T[] {
280
+ const kept = existing ?? [];
281
+ return [...kept, ...restored.filter((item) => !kept.some((other) => key(other) === key(item)))];
282
+}
283
+
284
/**
276
- * Writes a failed send's composer contents back into its draft. Returns the
277
- * restored images, which are fresh copies so their preview URLs outlive the
278
- * optimistic row that held the originals.
285
+ * Writes a failed send's composer contents back into its draft, after anything
286
+ * typed since. Returns the restored images, which are fresh copies so their
287
+ * preview URLs outlive the optimistic row that held the originals.
288
*/
289
export function restoreComposerDraft(
290
draftTarget: ScopedThreadRef | DraftId,
291
snapshot: ComposerSendSnapshot,
292
): ComposerImageAttachment[] {
293
const store = useComposerDraftStore.getState();
294
+ const current = store.getComposerDraft(draftTarget);
295
const images = snapshot.images.map(cloneComposerImageForRetry);
286
- store.setPrompt(draftTarget, snapshot.draftText);
287
- store.setReplyTo(draftTarget, snapshot.replyTo);
296
+ store.setPrompt(
297
+ draftTarget,
298
+ current?.prompt.trim() ? `${current.prompt}\n\n${snapshot.draftText}` : snapshot.draftText,
299
+ );
300
+ store.setReplyTo(draftTarget, current?.replyTo ?? snapshot.replyTo);
301
store.addImages(draftTarget, images);
302
store.addFiles(draftTarget, snapshot.files);
290
- store.setTerminalContexts(draftTarget, snapshot.terminalContexts);
291
- store.setPreviewAnnotations(draftTarget, snapshot.previewAnnotations);
292
- store.setReviewComments(draftTarget, snapshot.reviewComments);
293
- store.setThreadContexts(draftTarget, snapshot.threadContexts);
294
- store.setEnvironmentContexts(draftTarget, snapshot.environmentContexts);
303
+ store.setTerminalContexts(
304
+ draftTarget,
305
+ withRestored(current?.terminalContexts, snapshot.terminalContexts, (context) => context.id),
306
+ );
307
+ store.setPreviewAnnotations(
308
+ draftTarget,
309
+ withRestored(current?.previewAnnotations, snapshot.previewAnnotations, (entry) => entry.id),
310
+ );
311
+ store.setReviewComments(
312
+ draftTarget,
313
+ withRestored(current?.reviewComments, snapshot.reviewComments, (comment) => comment.id),
314
+ );
315
+ store.setThreadContexts(
316
+ draftTarget,
317
+ withRestored(current?.threadContexts, snapshot.threadContexts, (record) => record.contextId),
318
+ );
319
+ store.setEnvironmentContexts(
320
+ draftTarget,
321
+ withRestored(
322
+ current?.environmentContexts,
323
+ snapshot.environmentContexts,
324
+ (record) => record.contextId,
325
+ ),
326
+ );
327
return images;
328
}
329
apps/web/src/components/chat/useComposerSend.ts
+196
-87
@@ -25,7 +25,9 @@ import {
25
type EnvironmentId,
26
type ModelSelection,
27
type PreviewAnnotationPayload,
28
+ type ResponseContextRecord,
29
type ScopedThreadRef,
30
+ type ThreadContextRecord,
31
type ThreadId,
32
ProviderInteractionMode,
33
RuntimeMode,
@@ -80,10 +82,7 @@ import {
82
useComposerDraftStore,
83
DraftId,
84
} from "../../composerDraftStore";
83
-import {
84
- filterTerminalContextsWithText,
85
- type TerminalContextDraft,
86
-} from "../../lib/terminalContext";
85
+import type { TerminalContextDraft } from "../../lib/terminalContext";
86
import {
87
collectInlineContextIds,
88
ensureInlineContextReferences,
@@ -108,6 +107,7 @@ import {
107
referencedThreadContexts,
108
} from "./composerSend.logic";
109
import { useMultipleModelSend } from "./useMultipleModelSend";
110
+import type { SideChatMessage } from "./useSideChat";
111
import { type ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";
112
import {
113
getUploadedAttachments,
@@ -158,6 +158,32 @@ function readEnvironmentPresentation(environmentId: EnvironmentId) {
158
return appAtomRegistry.get(environmentPresentations.presentationsAtom).get(environmentId);
159
}
160
161
+function liveAttachmentCapabilities(
162
+ environmentId: EnvironmentId,
163
+ files: ReadonlyArray<ComposerFileAttachment>,
164
+) {
165
+ const config = appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId) ?? null;
166
+ const supportsAttachmentUploads = config !== null;
167
+ return {
168
+ supportsAttachmentUploads,
169
+ fileBlockReason: fileAttachmentCapabilityBlockReason({
170
+ files,
171
+ attachmentUploadsCapabilityKnown: config !== null,
172
+ supportsAttachmentUploads,
173
+ maxFileAttachmentBytes:
174
+ config?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null,
175
+ }),
176
+ };
177
+}
178
+
179
+// The reply leads the message, so its card sits above the text it is about. Text that
180
+// already points at that response, from a pasted card, keeps its one reference.
181
+function withReplyReference(prompt: string, replyTo: ResponseContextRecord | null) {
182
+ return replyTo && !collectInlineContextIds(prompt).includes(replyTo.contextId)
183
+ ? `${formatInlineContextReference(responseContextReference(replyTo))} ${prompt}`
184
+ : prompt;
185
+}
186
+
187
function draftHasNonPromptContent(target: ComposerThreadTarget) {
188
const draft = useComposerDraftStore.getState().getComposerDraft(target);
189
return draft ? composerDraftHasUserContent({ ...draft, prompt: "" }) : false;
@@ -247,8 +273,8 @@ interface ComposerSendInput {
273
readonly setKeepFullHistory: (threadKey: string, keep: boolean) => void;
274
readonly anchorNewTurn: TimelineFollow["anchorNewTurn"];
275
readonly acknowledgeActiveThreadWoke: () => void;
250
- /** Resolves true once the side chat started and got the prompt. */
251
- readonly onSideChat?: ((prompt: string) => Promise<boolean>) | undefined;
276
+ /** Resolves true once the side chat started and got the message. */
277
+ readonly onSideChat?: ((message: SideChatMessage | undefined) => Promise<boolean>) | undefined;
278
/** Refuses `/side` with this reason and keeps the draft. */
279
readonly sideChatDisabledReason: string | null;
280
readonly handleNewThreadInActiveProject: () => void;
@@ -505,35 +531,177 @@ export function useComposerSend(input: ComposerSendInput) {
531
);
532
return;
533
}
534
+ const startDraftAttachmentUploads = (
535
+ attachments: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>,
536
+ ) => {
537
+ for (const attachment of attachments) {
538
+ const upload =
539
+ readAttachmentUpload(attachment.id)?.status === "failed"
540
+ ? retryAttachmentUpload
541
+ : startAttachmentUpload;
542
+ upload({ environmentId, image: attachment, draftTarget: composerDraftTarget });
543
+ }
544
+ };
545
+ const warnStrandedThreadContext = (
546
+ text: string,
547
+ records: ReadonlyArray<ThreadContextRecord>,
548
+ ) => {
549
+ const strandedThread = threadContextsOutsideEnvironment({
550
+ text,
551
+ records,
552
+ environmentId,
553
+ linkedEnvironments,
554
+ })[0];
555
+ if (!strandedThread) return false;
556
+ const owner =
557
+ readEnvironmentPresentation(strandedThread.environmentId)?.entry.target.label ?? null;
558
+ toastManager.add(
559
+ stackedThreadToast({
560
+ type: "warning",
561
+ title: m(msg("Attached thread is on another machine")),
562
+ description:
563
+ owner === null
564
+ ? m(
565
+ msg(
566
+ "This machine's agent can't read \"{title}\". Remove it, or switch back to its machine to send.",
567
+ { title: strandedThread.title },
568
+ ),
569
+ )
570
+ : m(
571
+ msg(
572
+ "This machine's agent can't read \"{title}\". Remove it, or switch back to {owner} to send.",
573
+ { title: strandedThread.title, owner },
574
+ ),
575
+ ),
576
+ }),
577
+ );
578
+ return true;
579
+ };
580
if (onSideChat && sendCtx && sideChatCommand && sideChatDisabledReason === null) {
581
+ const replyTo =
582
+ useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.replyTo ?? null;
583
+ const prompt = withReplyReference(sideChatCommand.prompt, replyTo);
584
+ const { sendableTerminalContexts, hasSendableContent } = deriveComposerSendState({
585
+ prompt,
586
+ imageCount: sendCtx.images.length + sendCtx.files.length,
587
+ terminalContexts: sendCtx.terminalContexts,
588
+ elementContextCount:
589
+ (replyTo === null ? 0 : 1) +
590
+ sendCtx.previewAnnotations.length +
591
+ sendCtx.reviewComments.length +
592
+ sendCtx.threadContexts.length +
593
+ sendCtx.environmentContexts.length,
594
+ });
595
+ // An answer's text and attachments live in the question's draft, apart from this one.
596
if (
510
- sendCtx.images.length > 0 ||
511
- sendCtx.files.length > 0 ||
512
- filterTerminalContextsWithText(sendCtx.terminalContexts).length > 0 ||
513
- sendCtx.previewAnnotations.length > 0 ||
514
- sendCtx.reviewComments.length > 0 ||
515
- sendCtx.threadContexts.length > 0 ||
516
- sendCtx.environmentContexts.length > 0 ||
517
- useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.replyTo
597
+ sendCtx.answeringPendingUserInput &&
598
+ (replyTo !== null ||
599
+ sendCtx.images.length > 0 ||
600
+ sendCtx.files.length > 0 ||
601
+ sendableTerminalContexts.length > 0 ||
602
+ sendCtx.previewAnnotations.length > 0 ||
603
+ sendCtx.reviewComments.length > 0 ||
604
+ sendCtx.threadContexts.length > 0 ||
605
+ sendCtx.environmentContexts.length > 0)
606
) {
607
toastManager.add(
608
stackedThreadToast({
609
type: "warning",
522
- title: m(msg("Side chats take text only")),
610
+ title: m(msg("Side chat not started")),
611
description: m(msg("Remove the attachments and context, then send it again.")),
612
}),
613
);
614
return;
615
}
528
- const started = await onSideChat(sideChatCommand.prompt);
529
- // Clear only what was sent; the user may have edited the draft or left meanwhile.
530
- if (
531
- started &&
532
- currentRouteThreadKeyRef.current === routeThreadKey &&
533
- promptRef.current === promptAtSend
534
- ) {
616
+ if (warnStrandedThreadContext(prompt, sendCtx.threadContexts)) return;
617
+ const snapshot = snapshotComposerSend({
618
+ ...sendCtx,
619
+ prompt,
620
+ sendableTerminalContexts,
621
+ replyTo,
622
+ });
623
+ const capabilities = liveAttachmentCapabilities(environmentId, snapshot.files);
624
+ if (capabilities.fileBlockReason !== null) {
625
+ setThreadError(activeThread.id, capabilities.fileBlockReason);
626
+ return;
627
+ }
628
+ const sendsDraft = hasSendableContent && !sendCtx.answeringPendingUserInput;
629
+ sendInFlightRef.current = true;
630
+ if (capabilities.supportsAttachmentUploads) startDraftAttachmentUploads(snapshot.attachments);
631
+ // Cleared at send, like a regular message, so nothing in it can change or vanish mid-start.
632
+ if (sendsDraft) {
633
+ clearComposerDraftContent(composerDraftTarget);
634
promptRef.current = "";
536
- setComposerDraftPrompt(composerDraftTarget, "");
635
+ composerRef.current?.resetCursorState();
636
+ }
637
+ const started = await settlePromise(async () => {
638
+ if (!hasSendableContent) return onSideChat(undefined);
639
+ const attachments = await prepareTurnAttachments({
640
+ environmentId,
641
+ attachments: snapshot.attachments,
642
+ usesAttachmentUploads: capabilities.supportsAttachmentUploads,
643
+ draftTarget: composerDraftTarget,
644
+ });
645
+ // `onSideChat` forks the thread on screen, which may have changed during the upload.
646
+ if (currentRouteThreadKeyRef.current !== routeThreadKey) return false;
647
+ const attachmentIds = boundAttachmentIds(attachments, snapshot.attachments);
648
+ return onSideChat({
649
+ attachments,
650
+ ...withMessageContext({
651
+ text: snapshot.messageText || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
652
+ context: buildMessageContext({
653
+ ...snapshot,
654
+ attachments: snapshot.attachments.map((attachment, index) => ({
655
+ attachment,
656
+ attachmentId: attachmentIds[index]!,
657
+ })),
658
+ }),
659
+ }),
660
+ titleSeed: deriveThreadTitleSeed(
661
+ {
662
+ text: snapshot.messageText,
663
+ attachments: snapshot.attachments,
664
+ fallbackLabels: sendTitleFallbackLabels(snapshot),
665
+ },
666
+ m,
667
+ ),
668
+ });
669
+ }).finally(() => {
670
+ sendInFlightRef.current = false;
671
+ });
672
+ const startedOk = started._tag === "Success" && started.value;
673
+ if (started._tag === "Failure") {
674
+ const error = squashAtomCommandFailure(started);
675
+ setThreadError(
676
+ activeThread.id,
677
+ error instanceof Error ? error.message : m(msg("Could not start a side chat.")),
678
+ );
679
+ }
680
+ if (sendsDraft) {
681
+ if (startedOk && capabilities.supportsAttachmentUploads) {
682
+ releaseDraftAttachments(snapshot.attachments);
683
+ }
684
+ // A restore clones the images first, so the sent previews can go either way.
685
+ if (!startedOk)
686
+ restoreComposerDraft(composerDraftTarget, { ...snapshot, draftText: promptAtSend });
687
+ for (const image of snapshot.images) {
688
+ if (image.previewUrl.startsWith("blob:")) URL.revokeObjectURL(image.previewUrl);
689
+ }
690
+ if (!startedOk && currentRouteThreadKeyRef.current === routeThreadKey) {
691
+ const prompt =
692
+ useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.prompt ??
693
+ promptAtSend;
694
+ promptRef.current = prompt;
695
+ composerRef.current?.resetCursorState({ prompt });
696
+ }
697
+ return;
698
+ }
699
+ // Answering a question, the composer shows the answer, which lives apart from this draft.
700
+ if (startedOk && currentRouteThreadKeyRef.current === routeThreadKey) {
701
+ if (!sendCtx.answeringPendingUserInput && promptRef.current === promptAtSend) {
702
+ setComposerDraftPrompt(composerDraftTarget, "");
703
+ promptRef.current = "";
704
+ }
705
composerRef.current?.resetCursorState();
706
}
707
return;
@@ -616,43 +784,8 @@ export function useComposerSend(input: ComposerSendInput) {
784
: promptRef.current;
785
const replyTo =
786
useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.replyTo ?? null;
619
- // The reply leads the message, so its card sits above the text it is about. Text that
620
- // already points at that response, from a pasted card, keeps its one reference.
621
- const promptForSend =
622
- replyTo && !collectInlineContextIds(draftPrompt).includes(replyTo.contextId)
623
- ? `${formatInlineContextReference(responseContextReference(replyTo))} ${draftPrompt}`
624
- : draftPrompt;
625
- const strandedThread = threadContextsOutsideEnvironment({
626
- text: promptForSend,
627
- records: composerThreadContexts,
628
- environmentId,
629
- linkedEnvironments,
630
- })[0];
631
- if (strandedThread) {
632
- const owner =
633
- readEnvironmentPresentation(strandedThread.environmentId)?.entry.target.label ?? null;
634
- toastManager.add(
635
- stackedThreadToast({
636
- type: "warning",
637
- title: m(msg("Attached thread is on another machine")),
638
- description:
639
- owner === null
640
- ? m(
641
- msg(
642
- "This machine's agent can't read \"{title}\". Remove it, or switch back to its machine to send.",
643
- { title: strandedThread.title },
644
- ),
645
- )
646
- : m(
647
- msg(
648
- "This machine's agent can't read \"{title}\". Remove it, or switch back to {owner} to send.",
649
- { title: strandedThread.title, owner },
650
- ),
651
- ),
652
- }),
653
- );
654
- return;
655
- }
787
+ const promptForSend = withReplyReference(draftPrompt, replyTo);
788
+ if (warnStrandedThreadContext(promptForSend, composerThreadContexts)) return;
789
if (queuedRunEdit.isEditing) {
790
// A queued message stays in its thread, so saving `/side` would send it to main.
791
if (!directAnnotation && parseSideChatCommand(promptAtSend)) {
@@ -888,20 +1021,8 @@ export function useComposerSend(input: ComposerSendInput) {
1021
return;
1022
}
1023
891
- const readLiveAttachmentCapabilities = () => {
892
- const config = appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId) ?? null;
893
- const liveSupportsAttachmentUploads = config !== null;
894
- return {
895
- supportsAttachmentUploads: liveSupportsAttachmentUploads,
896
- fileBlockReason: fileAttachmentCapabilityBlockReason({
897
- files: composerFilesSnapshot,
898
- attachmentUploadsCapabilityKnown: config !== null,
899
- supportsAttachmentUploads: liveSupportsAttachmentUploads,
900
- maxFileAttachmentBytes:
901
- config?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null,
902
- }),
903
- };
904
- };
1024
+ const readLiveAttachmentCapabilities = () =>
1025
+ liveAttachmentCapabilities(environmentId, composerFilesSnapshot);
1026
1027
const multipleTargets: MultipleModelTarget[] = [];
1028
for (const resolved of resolveMultipleModelTargets({
@@ -938,19 +1059,7 @@ export function useComposerSend(input: ComposerSendInput) {
1059
? attachmentCapabilitiesBeforeUpload.supportsAttachmentUploads
1060
: (readEnvironmentPresentation(environmentId)?.serverConfig ?? null) !== null;
1061
// Uploads finish after the message shows as sending; the turn starts once they land.
941
- if (turnUsesAttachmentUploads) {
942
- for (const attachment of composerAttachmentsSnapshot) {
943
- const upload =
944
- readAttachmentUpload(attachment.id)?.status === "failed"
945
- ? retryAttachmentUpload
946
- : startAttachmentUpload;
947
- upload({
948
- environmentId,
949
- image: attachment,
950
- draftTarget: composerDraftTarget,
951
- });
952
- }
953
- }
1062
+ if (turnUsesAttachmentUploads) startDraftAttachmentUploads(composerAttachmentsSnapshot);
1063
1064
if (
1065
multipleModelSelections === null &&
apps/web/src/components/chat/useSideChat.ts
+14
-9
@@ -3,7 +3,7 @@ import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
3
import { m } from "~/i18n/messages";
4
import type { ModelSelection, RuntimeMode, ScopedThreadRef } from "@t3tools/contracts";
5
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
6
-import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
6
+import type { StartThreadTurnInput } from "@t3tools/client-runtime/operations";
7
import {
8
type AtomCommandResult,
9
isAtomCommandInterrupted,
@@ -20,9 +20,14 @@ import { threadEnvironment } from "../../state/threads";
20
import { useAtomCommand } from "../../state/use-atom-command";
21
import { useOrchestrationCommand } from "../../state/use-orchestration-command";
22
23
+export type SideChatMessage = Pick<
24
+ StartThreadTurnInput["message"],
25
+ "text" | "attachments" | "context"
26
+> & { readonly titleSeed: string };
27
+
28
/**
29
* Starts side chats from `threadRef`, or offers none when it is null. `open` forks the
25
- * thread's latest stable point, sends `prompt` there with `readSettings()`, the parent
30
+ * thread's latest stable point, sends `message` there with `readSettings()`, the parent
31
* composer's settings, and shows the tab. It resolves false when the side chat did not
32
* start, or another one is still starting.
33
*/
@@ -51,7 +56,7 @@ export function useSideChat(input: {
56
const error = squashAtomCommandFailure(failure);
57
input.onError(thrownErrorMessage(error, m) ?? fallback);
58
};
54
- const start = async (threadRef: ScopedThreadRef, prompt: string | undefined) => {
59
+ const start = async (threadRef: ScopedThreadRef, message: SideChatMessage | undefined) => {
60
const { runtimeMode, modelSelection } = input.readSettings();
61
const targetThreadId = newThreadId();
62
const fork = await forkSideChat({
@@ -92,16 +97,16 @@ export function useSideChat(input: {
97
return false;
98
}
99
}
95
- const text = prompt?.trim();
100
// Send before showing the tab: closing a tab whose side chat has no run deletes it.
97
- if (text) {
101
+ if (message) {
102
+ const { titleSeed, ...content } = message;
103
const turn = await startThreadTurn({
104
environmentId: threadRef.environmentId,
105
input: {
106
threadId: targetThreadId,
102
- message: { messageId: newMessageId(), role: "user", text, attachments: [] },
107
+ message: { messageId: newMessageId(), role: "user", ...content },
108
...(modelSelection === undefined ? {} : { modelSelection }),
104
- titleSeed: deriveThreadTitleSeed({ text, attachments: [] }, m),
109
+ titleSeed,
110
runtimeMode,
111
interactionMode: "default",
112
createdAt: new Date().toISOString(),
@@ -118,11 +123,11 @@ export function useSideChat(input: {
123
useRightPanelStore.getState().openSideChat(threadRef, targetThreadId);
124
return true;
125
};
121
- const open = async (prompt?: string) => {
126
+ const open = async (message?: SideChatMessage) => {
127
const { threadRef } = input;
128
if (!threadRef || pendingRef.current) return false;
129
pendingRef.current = true;
125
- return start(threadRef, prompt).finally(() => {
130
+ return start(threadRef, message).finally(() => {
131
pendingRef.current = false;
132
});
133
};
apps/web/src/i18n/translations/de.json
-1
@@ -4599,7 +4599,6 @@
4599
"6d00220bfee72afd": "Nicht verbunden: Nachricht nicht gesendet",
4600
"f62c43120e8c60e7": "Verbindung zur Umgebung wird wiederhergestellt. Versuche es erneut, sobald sie verbunden ist.",
4601
"74e7e5c0536cda02": "Nebenchat nicht gestartet",
4602
- "be6231ac5b08f35e": "Nebenchats nehmen nur Text an",
4602
"faf9ee0a28119e10": "Entferne die Anhänge und den Kontext und sende dann erneut.",
4603
"1778ba2f32077b39": "Aktualisiere diesen Server, bevor du mehrere Modelle startest.",
4604
"736caccf2954a7f5": "Modelle und einen Basis-Branch wählen",
apps/web/src/i18n/translations/en.json
-1
@@ -4598,7 +4598,6 @@
4598
"6d00220bfee72afd": "Not connected: message not sent",
4599
"f62c43120e8c60e7": "Reconnecting to the environment. Try again once it is connected.",
4600
"74e7e5c0536cda02": "Side chat not started",
4601
- "be6231ac5b08f35e": "Side chats take text only",
4601
"faf9ee0a28119e10": "Remove the attachments and context, then send it again.",
4602
"1778ba2f32077b39": "Update this server before starting multiple models.",
4603
"736caccf2954a7f5": "Choose models and a base branch",
apps/web/src/i18n/translations/es.json
-1
@@ -4596,7 +4596,6 @@
4596
"6d00220bfee72afd": "Sin conexión: mensaje no enviado",
4597
"f62c43120e8c60e7": "Reconectando con el entorno. Vuelve a intentarlo cuando esté conectado.",
4598
"74e7e5c0536cda02": "Chat lateral no iniciado",
4599
- "be6231ac5b08f35e": "Los chats laterales solo admiten texto",
4599
"faf9ee0a28119e10": "Quita los adjuntos y el contexto, y vuelve a enviarlo.",
4600
"1778ba2f32077b39": "Actualiza este servidor antes de iniciar varios modelos.",
4601
"736caccf2954a7f5": "Elige los modelos y una rama base",
apps/web/src/i18n/translations/fr.json
-1
@@ -4597,7 +4597,6 @@
4597
"6d00220bfee72afd": "Non connecté : message non envoyé",
4598
"f62c43120e8c60e7": "Reconnexion à l’environnement. Réessayez une fois la connexion établie.",
4599
"74e7e5c0536cda02": "Discussion annexe non démarrée",
4600
- "be6231ac5b08f35e": "Les discussions annexes n’acceptent que du texte",
4600
"faf9ee0a28119e10": "Retirez les pièces jointes et le contexte, puis renvoyez.",
4601
"1778ba2f32077b39": "Mettez à jour ce serveur avant de lancer plusieurs modèles.",
4602
"736caccf2954a7f5": "Choisissez des modèles et une branche de base",
apps/web/src/i18n/translations/ja.json
-1
@@ -4586,7 +4586,6 @@
4586
"6d00220bfee72afd": "未接続: メッセージは送信されませんでした",
4587
"f62c43120e8c60e7": "環境に再接続しています。接続されたらもう一度お試しください。",
4588
"74e7e5c0536cda02": "サイドチャットが開始されていません",
4589
- "be6231ac5b08f35e": "サイドチャットではテキストのみ使用できます",
4589
"faf9ee0a28119e10": "添付ファイルとコンテキストを削除してから、もう一度送信してください。",
4590
"1778ba2f32077b39": "複数のモデルを開始する前に、このサーバーを更新してください。",
4591
"736caccf2954a7f5": "モデルとベースブランチを選択",
apps/web/src/i18n/translations/ko.json
-1
@@ -4583,7 +4583,6 @@
4583
"6d00220bfee72afd": "연결되지 않음: 메시지를 보내지 않았습니다",
4584
"f62c43120e8c60e7": "환경에 다시 연결하는 중입니다. 연결되면 다시 시도하세요.",
4585
"74e7e5c0536cda02": "사이드 채팅이 시작되지 않음",
4586
- "be6231ac5b08f35e": "사이드 채팅은 텍스트만 받습니다",
4586
"faf9ee0a28119e10": "첨부 파일과 컨텍스트를 제거한 다음 다시 보내세요.",
4587
"1778ba2f32077b39": "여러 모델을 시작하기 전에 이 서버를 업데이트하세요.",
4588
"736caccf2954a7f5": "모델과 기본 브랜치를 선택하세요",
apps/web/src/i18n/translations/pt-BR.json
-1
@@ -4596,7 +4596,6 @@
4596
"6d00220bfee72afd": "Não conectado: mensagem não enviada",
4597
"f62c43120e8c60e7": "Reconectando ao ambiente. Tente novamente quando estiver conectado.",
4598
"74e7e5c0536cda02": "Chat paralelo não iniciado",
4599
- "be6231ac5b08f35e": "Chats paralelos aceitam só texto",
4599
"faf9ee0a28119e10": "Remova os anexos e o contexto e envie novamente.",
4600
"1778ba2f32077b39": "Atualize este servidor antes de iniciar vários modelos.",
4601
"736caccf2954a7f5": "Escolha os modelos e um branch base",
apps/web/src/i18n/translations/ru.json
-1
@@ -4596,7 +4596,6 @@
4596
"6d00220bfee72afd": "Нет подключения: сообщение не отправлено",
4597
"f62c43120e8c60e7": "Переподключение к окружению. Повторите, когда подключение восстановится.",
4598
"74e7e5c0536cda02": "Боковой чат не начат",
4599
- "be6231ac5b08f35e": "Боковые чаты принимают только текст",
4599
"faf9ee0a28119e10": "Удалите вложения и контекст, затем отправьте снова.",
4600
"1778ba2f32077b39": "Обновите этот сервер, прежде чем запускать несколько моделей.",
4601
"736caccf2954a7f5": "Выберите модели и базовую ветку",
apps/web/src/i18n/translations/sv.json
-1
@@ -4597,7 +4597,6 @@
4597
"6d00220bfee72afd": "Inte ansluten: meddelandet skickades inte",
4598
"f62c43120e8c60e7": "Återansluter till miljön. Försök igen när den är ansluten.",
4599
"74e7e5c0536cda02": "Sidochatten startades inte",
4600
- "be6231ac5b08f35e": "Sidochattar tar bara emot text",
4600
"faf9ee0a28119e10": "Ta bort bilagorna och kontexten och skicka sedan igen.",
4601
"1778ba2f32077b39": "Uppdatera den här servern innan du startar flera modeller.",
4602
"736caccf2954a7f5": "Välj modeller och en basgren",
apps/web/src/i18n/translations/zh.json
-1
@@ -4603,7 +4603,6 @@
4603
"6d00220bfee72afd": "未连接:消息没有发送",
4604
"f62c43120e8c60e7": "正在重新连接环境,连接后请重试。",
4605
"74e7e5c0536cda02": "侧聊未开始",
4606
- "be6231ac5b08f35e": "侧聊只支持文字",
4606
"faf9ee0a28119e10": "请移除附件和上下文后再发送。",
4607
"1778ba2f32077b39": "请先更新此服务器,再同时启动多个模型。",
4608
"736caccf2954a7f5": "请选择模型和基准分支",
apps/web/test/fakeEnvironment.ts
+40
-14
@@ -67,7 +67,7 @@ const descriptor = {
67
// A matching version, since a mismatch adds an update banner a typical user never sees.
68
serverVersion: APP_VERSION,
69
orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
70
- capabilities: { repositoryIdentity: true },
70
+ capabilities: { repositoryIdentity: true, sideChats: true },
71
};
72
const auth = {
73
policy: "loopback-browser",
@@ -406,6 +406,7 @@ const json = (body: unknown, status = 200) =>
406
// Keyed by thread id: a live thread subscription's queue, for pushing events to it.
407
const threadSubscribers = new Map<string, Queue.Queue<OrchestrationV2ThreadStreamItem>>();
408
let terminalMetadataSubscriber: Queue.Queue<TerminalMetadataStreamEvent> | null = null;
409
+let shellSubscriber: Queue.Queue<OrchestrationV2ShellStreamItem> | null = null;
410
let threads: ReadonlyArray<FakeThread> = [];
411
let dispatched: OrchestrationV2Command[] = [];
412
let acceptCommands = false;
@@ -438,8 +439,25 @@ const handlers: Record<string, (input: never) => unknown> = {
439
[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
440
Effect.suspend(() => {
441
dispatched.push(command);
441
- if (acceptCommands && !holdCommand(command))
442
- return Effect.succeed({ sequence: sequence + 1 });
442
+ if (acceptCommands && !holdCommand(command)) {
443
+ if (command.type !== "thread.fork" || !command.sideChat || shellSubscriber === null)
444
+ return Effect.succeed({ sequence: sequence + 1 });
445
+ const fork: FakeThread = {
446
+ id: command.targetThreadId,
447
+ title: command.title ?? "Side chat",
448
+ sideChatOf: command.sourceThreadId,
449
+ runs: [],
450
+ items: [],
451
+ };
452
+ threads = [...threads, fork];
453
+ sequence += 1;
454
+ return Queue.offer(shellSubscriber, {
455
+ kind: "thread.updated",
456
+ sequence,
457
+ location: "active",
458
+ thread: shellOf(fork),
459
+ }).pipe(Effect.as({ sequence }));
460
+ }
461
const reply = Deferred.makeUnsafe<never, OrchestrationV2DispatchCommandError>();
462
pendingDispatches.push({ command, reply });
463
return Deferred.await(reply);
@@ -459,19 +477,27 @@ const handlers: Record<string, (input: never) => unknown> = {
477
};
478
}),
479
[ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () =>
462
- subscribe<OrchestrationV2ShellStreamItem>([
463
- {
464
- kind: "snapshot",
465
- snapshot: {
466
- schemaVersion: 1,
467
- snapshotSequence: sequence,
468
- projects,
469
- threads: threads.filter((thread) => !thread.olderSettled).map(shellOf),
470
- archivedThreads: [],
480
+ subscribe<OrchestrationV2ShellStreamItem>(
481
+ [
482
+ {
483
+ kind: "snapshot",
484
+ snapshot: {
485
+ schemaVersion: 1,
486
+ snapshotSequence: sequence,
487
+ projects,
488
+ threads: threads.filter((thread) => !thread.olderSettled).map(shellOf),
489
+ archivedThreads: [],
490
+ },
491
},
492
+ { kind: "synchronized" },
493
+ ],
494
+ (queue) => {
495
+ shellSubscriber = queue;
496
+ return () => {
497
+ if (shellSubscriber === queue) shellSubscriber = null;
498
+ };
499
},
473
- { kind: "synchronized" },
474
- ]),
500
+ ),
501
[ORCHESTRATION_V2_WS_METHODS.subscribeThread]: (input: { readonly threadId: ThreadId }) => {
502
const thread = threads.find((candidate) => candidate.id === input.threadId);
503
if (!thread) return Stream.never;