@devries-cameron20 / t3code Mirror · read-only / commits / 0f28f6f6a0
Fork 0

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, 03:15 UTC

feat(mobile): start side chats with /side (#31709)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 5, 2026 at 14:52 UTC 0f28f6f6a00130e71e127e849d8e01cd46668588
15 files changed +302 -71
apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
+1
@@ -983,6 +983,7 @@ export function NewTaskDraftScreen(props: {
983 onStopThread={() => {}}
984 onResumeQueue={null}
985 onSendMessage={handleStart}
986 + offersSideChat={false}
987 onReconnectEnvironment={() => onReconnectEnvironment(selectedProject.environmentId)}
988 canSwitchThreadProvider
989 onUpdateThreadInteractionMode={flow.planModeEnabled ? flow.setInteractionMode : undefined}
apps/mobile/src/features/threads/ThreadComposer.tsx
+2
@@ -217,6 +217,7 @@ export interface ThreadComposerProps {
217 readonly hasCompactableConversation: boolean;
218 /** Arms a fresh session for the next message; absent where `/clear` is unavailable. */
219 readonly onFreshSession?: () => void;
220 + readonly offersSideChat?: boolean;
221 readonly serverConfig: T3ServerConfig | null;
222 readonly queueCount: number;
223 readonly activeThreadBusy: boolean;
@@ -564,6 +565,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
565 onUsageLimits:
566 usageLimitsOffered && draftAttachments.length === 0 ? openUsageLimits : undefined,
567 ...(props.onFreshSession === undefined ? {} : { onFreshSession: props.onFreshSession }),
568 + offersSideChat: props.offersSideChat === true,
569 });
570 const voiceInput = useVoiceInputController({
571 ownerKey: composerDraftKey,
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+9
@@ -287,6 +287,7 @@ export interface ThreadDetailScreenProps {
287 readonly onStopThread: () => void;
288 /** Present while the thread's queue is held. */
289 readonly onResumeQueue: (() => Promise<void>) | null;
290 + readonly offersSideChat: boolean;
291 readonly onSendMessage: (
292 followUp?: ActiveTurnComposerAction,
293 beforeDispatch?: (
@@ -1836,6 +1837,14 @@ function ThreadDetailBody(
1837 onFreshSession: () => setFreshSessionPending(selectedThreadKey, true),
1838 }
1839 : {})}
1840 + offersSideChat={
1841 + props.offersSideChat &&
1842 + !props.draftMode &&
1843 + props.canOperateThread &&
1844 + props.queuedRunEdit === null &&
1845 + props.activePendingApproval === null &&
1846 + props.activePendingUserInput === null
1847 + }
1848 serverConfig={props.serverConfig}
1849 queueCount={props.selectedThreadQueueCount}
1850 activeThreadBusy={props.activeThreadBusy}
apps/mobile/src/features/threads/ThreadFeed.tsx
+4 -12
@@ -275,7 +275,7 @@ import {
275 resolveWorkspaceFilePath,
276 resolveWorkspaceRelativeFilePath,
277 } from "../files/filePath";
278 -import { waitForThreadShellReady } from "./threadForkNavigation";
278 +import { waitForThreadShell } from "./threadForkNavigation";
279 import { resolveUserMessageIntentBadge } from "./userMessageIntentBadge";
280 import { fileChipClipboardPath, fileChipMenu, resolveFileChipTarget } from "./fileChipMenu";
281 import { useFileChipShare } from "./useFileChipShare";
@@ -381,16 +381,6 @@ export interface ThreadFeedProps {
381 readonly onUseArtifactTemplate?: (template: CodexArtifactTemplate) => void;
382 }
383
384 -async function waitForThreadShell(
385 - environmentId: EnvironmentId,
386 - threadId: ThreadId,
387 -): Promise<boolean> {
388 - const atom = environmentThreadShells.threadShellAtom(scopeThreadRef(environmentId, threadId));
389 - return waitForThreadShellReady({
390 - read: () => appAtomRegistry.get(atom) !== null,
391 - });
392 -}
393 -
384 const USER_MESSAGE_COPY_MENU_ACTIONS = [
385 { id: "copy-prompt-link", title: "Copy prompt link", image: "link" },
386 ];
@@ -470,7 +460,9 @@ function AssistantForkButton(props: {
460 })
461 .then(async (result) => {
462 if (result._tag !== "Success") return;
473 - const targetThreadReady = await waitForThreadShell(props.environmentId, targetThreadId);
463 + const targetThreadReady = await waitForThreadShell(
464 + scopeThreadRef(props.environmentId, targetThreadId),
465 + );
466 if (!targetThreadReady) {
467 Dialog.alert(
468 "Fork created",
apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+4 -1
@@ -111,6 +111,7 @@ import {
111 ThreadInspectorPreview,
112 type ThreadInspectorPresentation,
113 } from "./thread-inspector-preview";
114 +import { useStartSideChat } from "./useStartSideChat";
115 import type { ThreadInspectorMode, ThreadInspectorTarget } from "./thread-inspector-navigation";
116 import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
117
@@ -368,7 +369,8 @@ function ThreadRouteContent(
369 const selectedThreadDetailState = props.selectedThreadDetailState;
370 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
371 const { selectedThreadCwd } = useSelectedThreadWorktree();
371 - const composer = useThreadComposerState();
372 + const startSideChat = useStartSideChat();
373 + const composer = useThreadComposerState({ startSideChat });
374 const gitState = useSelectedThreadGitState();
375 const gitActions = useSelectedThreadGitActions();
376 const requests = useSelectedThreadRequests();
@@ -1070,6 +1072,7 @@ function ThreadRouteContent(
1072 composer.queueHeld || composer.resumableRunId !== null ? handleResumeQueue : null
1073 }
1074 onSendMessage={composer.onSendMessage}
1075 + offersSideChat={composer.sideChatUnavailableReason === null}
1076 onReconnectEnvironment={handleReconnectEnvironment}
1077 canSwitchThreadProvider={composer.canSwitchThreadProvider}
1078 onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
apps/mobile/src/features/threads/threadForkNavigation.ts
+16 -22
@@ -1,26 +1,20 @@
1 -const DEFAULT_TIMEOUT_MS = 2_000;
2 -const DEFAULT_POLL_INTERVAL_MS = 40;
1 +import type { ScopedThreadRef } from "@t3tools/contracts";
2
4 -export async function waitForThreadShellReady(input: {
5 - readonly read: () => boolean;
6 - readonly timeoutMs?: number;
7 - readonly pollIntervalMs?: number;
8 - readonly now?: () => number;
9 - readonly delay?: (durationMs: number) => Promise<void>;
10 -}): Promise<boolean> {
11 - const now = input.now ?? Date.now;
12 - const delay =
13 - input.delay ??
14 - ((durationMs: number) =>
15 - new Promise<void>((resolve) => {
16 - setTimeout(resolve, durationMs);
17 - }));
18 - const deadline = now() + (input.timeoutMs ?? DEFAULT_TIMEOUT_MS);
19 - const pollIntervalMs = input.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
3 +import { appAtomRegistry } from "../../state/atom-registry";
4 +import { environmentThreadShells } from "../../state/threads";
5
21 - while (!input.read() && now() < deadline) {
22 - await delay(Math.min(pollIntervalMs, deadline - now()));
23 - }
6 +const TIMEOUT_MS = 2_000;
7 +const POLL_INTERVAL_MS = 40;
8
25 - return input.read();
9 +/** Resolves true once a thread this client just created, such as a fork, reaches its state. */
10 +export async function waitForThreadShell(ref: ScopedThreadRef): Promise<boolean> {
11 + const atom = environmentThreadShells.threadShellAtom(ref);
12 + const read = () => appAtomRegistry.get(atom) !== null;
13 + const deadline = Date.now() + TIMEOUT_MS;
14 + while (!read() && Date.now() < deadline) {
15 + await new Promise<void>((resolve) => {
16 + setTimeout(resolve, Math.min(POLL_INTERVAL_MS, deadline - Date.now()));
17 + });
18 + }
19 + return read();
20 }
apps/mobile/src/features/threads/use-composer-command-menu.ts
+19
@@ -106,6 +106,7 @@ export function buildComposerSlashCommandItems(input: {
106 readonly offersUsageLimits?: boolean;
107 /** T3's `/clear` replaces the provider's, which would clear a session T3 still treats as live. */
108 readonly offersFreshSession?: boolean;
109 + readonly offersSideChat?: boolean;
110 readonly allowInteractionMode: boolean;
111 readonly selectedProviderStatus: Pick<
112 ServerProvider,
@@ -145,6 +146,21 @@ export function buildComposerSlashCommandItems(input: {
146 // Providers expand commands only at the start of a message. T3 commands
147 // change local state and do not have this restriction, except `/clear`.
148 if (!input.atMessageStart) return items;
149 + if (input.offersSideChat) {
150 + for (const [command, description] of [
151 + ["side", "Ask a side question in a new side chat"],
152 + ["btw", "Same as /side"],
153 + ] as const) {
154 + if (!command.includes(query)) continue;
155 + items.push({
156 + id: `cmd:${command}`,
157 + type: "slash-command",
158 + command,
159 + label: `/${command}`,
160 + description,
161 + });
162 + }
163 + }
164 if (input.offersFreshSession && "clear".includes(query)) {
165 items.push({
166 id: "cmd:clear",
@@ -238,6 +254,7 @@ export function useComposerCommandMenu({
254 onUpdateInteractionMode,
255 onUsageLimits,
256 onFreshSession,
257 + offersSideChat = false,
258 }: {
259 readonly draftMessage: string;
260 readonly ownerKey: string | null;
@@ -261,6 +278,7 @@ export function useComposerCommandMenu({
278 readonly onUsageLimits?: () => void;
279 /** Arms a fresh session for the next message; absent where `/clear` is unavailable. */
280 readonly onFreshSession?: () => void;
281 + readonly offersSideChat?: boolean;
282 }) {
283 const [localSelection, setLocalSelection] = useState(() => ({
284 ownerKey,
@@ -365,6 +383,7 @@ export function useComposerCommandMenu({
383 hasCompactableConversation,
384 offersUsageLimits,
385 offersFreshSession: onFreshSession !== undefined,
386 + offersSideChat,
387 allowInteractionMode: onUpdateInteractionMode !== undefined,
388 selectedProviderStatus: selectedProviderStatus
389 ? {
apps/mobile/src/features/threads/useStartSideChat.ts new
+97
@@ -0,0 +1,97 @@
1 +import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2 +import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
3 +import {
4 + isAtomCommandInterrupted,
5 + squashAtomCommandFailure,
6 + type AtomCommandResult,
7 +} from "@t3tools/client-runtime/state/runtime";
8 +import { MessageId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
9 +
10 +import * as Dialog from "../../components/ui/Dialog";
11 +import { uuidv4 } from "../../lib/uuid";
12 +import { appAtomRegistry } from "../../state/atom-registry";
13 +import { environmentThreadShells, threadEnvironment } from "../../state/threads";
14 +import { useAtomCommand } from "../../state/use-atom-command";
15 +import { waitForThreadShell } from "./threadForkNavigation";
16 +import { useOpenLinkedThread } from "./useOpenLinkedThread";
17 +
18 +/**
19 + * Forks `source` at its latest stable point into a side chat, sends `prompt` there, and opens
20 + * it like any linked thread. Resolves false when the side chat did not start.
21 + */
22 +export function useStartSideChat() {
23 + const forkSideChat = useAtomCommand(threadEnvironment.forkSideChat, { reportFailure: false });
24 + const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
25 + const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
26 + const openLinkedThread = useOpenLinkedThread();
27 +
28 + const alertFailure = (
29 + failure: Extract<AtomCommandResult<unknown, unknown>, { readonly _tag: "Failure" }>,
30 + fallback: string,
31 + ) => {
32 + if (isAtomCommandInterrupted(failure)) return;
33 + const error = squashAtomCommandFailure(failure);
34 + Dialog.alert("Side chat not started", error instanceof Error ? error.message : fallback);
35 + };
36 +
37 + return async (source: ScopedThreadRef, prompt: string): Promise<boolean> => {
38 + const targetThreadId = ThreadId.make(uuidv4());
39 + const fork = await forkSideChat({
40 + environmentId: source.environmentId,
41 + input: {
42 + sourceThreadId: source.threadId,
43 + targetThreadId,
44 + title: "Side chat",
45 + creationSource: "mobile",
46 + },
47 + });
48 + if (fork._tag === "Failure") {
49 + alertFailure(fork, "Could not start a side chat.");
50 + return false;
51 + }
52 + // Drops the empty side chat a failed start leaves behind; one that got its message stays.
53 + const discard = () =>
54 + void deleteThread({
55 + environmentId: source.environmentId,
56 + input: { threadId: targetThreadId, onlyIfUnused: true },
57 + });
58 + const targetRef = scopeThreadRef(source.environmentId, targetThreadId);
59 + if (!(await waitForThreadShell(targetRef))) {
60 + Dialog.alert(
61 + "Side chat not started",
62 + "The side chat was created, but it did not reach this device.",
63 + );
64 + discard();
65 + return false;
66 + }
67 + const sideChat = appAtomRegistry.get(environmentThreadShells.threadShellAtom(targetRef));
68 + if (sideChat === null) {
69 + Dialog.alert("Side chat not started", "The side chat is no longer available.");
70 + discard();
71 + return false;
72 + }
73 + const turn = await startTurn({
74 + environmentId: source.environmentId,
75 + input: {
76 + threadId: targetThreadId,
77 + message: {
78 + messageId: MessageId.make(uuidv4()),
79 + role: "user",
80 + text: prompt,
81 + attachments: [],
82 + },
83 + titleSeed: deriveThreadTitleSeed({ text: prompt, attachments: [] }),
84 + runtimeMode: sideChat.runtimeMode,
85 + interactionMode: "default",
86 + createdAt: new Date().toISOString(),
87 + },
88 + });
89 + if (turn._tag === "Failure") {
90 + alertFailure(turn, "Could not send the side chat message.");
91 + discard();
92 + return false;
93 + }
94 + openLinkedThread({ environmentId: source.environmentId, threadId: targetThreadId });
95 + return true;
96 + };
97 +}
apps/mobile/src/state/thread-task-permissions.test.ts
+50 -11
@@ -53,6 +53,7 @@ const state = vi.hoisted(() => ({
53 thread: {
54 id: "thread",
55 environmentId: "secondary",
56 + lineage: { rootThreadId: "thread", parentThreadId: null, relationshipToParent: null },
57 projectId: "project",
58 modelSelection: { instanceId: "codex", model: "gpt-5.4" },
59 runtimeMode: "full-access",
@@ -187,6 +188,8 @@ vi.mock("./use-remote-environment-registry", () => ({ setPendingConnectionError:
188 import { useThreadComposerState } from "./use-thread-composer-state";
189 import { useSelectedThreadRequests } from "./use-selected-thread-requests";
190
191 +const NO_SIDE_CHATS = { startSideChat: async () => false };
192 +
193 beforeEach(() => {
194 state.grantedEnvironments = new Set(["primary"]);
195 state.connectionState = "connected";
@@ -219,7 +222,7 @@ beforeEach(() => {
222 describe("mobile task permissions", () => {
223 it("consumes an approval reply without queueing a parent message", async () => {
224 state.grantedEnvironments.add("secondary");
222 - const composer = useThreadComposerState();
225 + const composer = useThreadComposerState(NO_SIDE_CHATS);
226 const requests = useSelectedThreadRequests();
227 const approval = { ...state.pendingRequests.approvals[0]!, supportsFeedback: true };
228 const messageId = await composer.onSendMessage(undefined, async (text) =>
@@ -243,7 +246,7 @@ describe("mobile task permissions", () => {
246
247 it("preserves a draft changed during an approval reply and never sends it to the parent", async () => {
248 state.grantedEnvironments.add("secondary");
246 - const composer = useThreadComposerState();
249 + const composer = useThreadComposerState(NO_SIDE_CHATS);
250 const beforeDispatch = async () => {
251 state.draft = { ...state.draft, text: "New feedback" };
252 return "responded" as const;
@@ -255,7 +258,7 @@ describe("mobile task permissions", () => {
258 });
259
260 it("keeps a connected read-only task's draft instead of queueing it with another environment's grant", async () => {
258 - const composer = useThreadComposerState();
261 + const composer = useThreadComposerState(NO_SIDE_CHATS);
262 expect(await composer.onSendMessage()).toBeNull();
263 expect(state.enqueue).not.toHaveBeenCalled();
264 expect(state.clearDraft).not.toHaveBeenCalled();
@@ -270,7 +273,7 @@ describe("mobile task permissions", () => {
273 it("keeps an armed fresh session for the message after an approval redirect", async () => {
274 state.grantedEnvironments.add("secondary");
275 state.freshPending = true;
273 - const composer = useThreadComposerState();
276 + const composer = useThreadComposerState(NO_SIDE_CHATS);
277 expect(await composer.onSendMessage(undefined, async () => true)).toBe("message");
278 expect(state.enqueue).toHaveBeenLastCalledWith(
279 expect.not.objectContaining({ freshContext: true }),
@@ -308,7 +311,7 @@ describe("mobile task permissions", () => {
311 updatedAt: DateTime.makeUnsafe(0),
312 } as unknown as OrchestrationV2ThreadProjection;
313 state.compactDue = true;
311 - const composer = useThreadComposerState();
314 + const composer = useThreadComposerState(NO_SIDE_CHATS);
315 await composer.onSendMessage();
316 expect(state.enqueue).toHaveBeenLastCalledWith(
317 expect.objectContaining({ compactBeforeSend: true }),
@@ -329,16 +332,49 @@ describe("mobile task permissions", () => {
332 } as ServerConfig;
333 state.thread.latestRun = { runId: "run" };
334 state.draft = { ...state.draft, text: "/clear" };
332 - const composer = useThreadComposerState();
335 + const composer = useThreadComposerState(NO_SIDE_CHATS);
336 const beforeDispatch = vi.fn(async () => "responded" as const);
337 expect(await composer.onSendMessage(undefined, beforeDispatch)).toBeNull();
338 expect(beforeDispatch).toHaveBeenCalledWith("/clear", false);
339 expect(state.setFreshPending).not.toHaveBeenCalled();
340 });
341
342 + it("starts a side chat for /side instead of sending to the thread", async () => {
343 + state.grantedEnvironments.add("secondary");
344 + state.serverConfig = {
345 + ...state.serverConfig,
346 + environment: { capabilities: { sideChats: true } },
347 + } as ServerConfig;
348 + state.draft = { ...state.draft, text: "/side why does this fail?" };
349 + const startSideChat = vi.fn(async () => true);
350 + const composer = useThreadComposerState({ startSideChat });
351 + expect(composer.sideChatUnavailableReason).toBeNull();
352 + expect(await composer.onSendMessage()).toBeNull();
353 + expect(startSideChat).toHaveBeenCalledExactlyOnceWith(
354 + { environmentId: "secondary", threadId: "thread" },
355 + "why does this fail?",
356 + );
357 + expect(state.enqueue).not.toHaveBeenCalled();
358 + expect(state.clearDraft).toHaveBeenCalled();
359 +
360 + // An attachment added while the side chat starts stays in the draft.
361 + vi.clearAllMocks();
362 + startSideChat.mockImplementationOnce(async () => {
363 + state.draft = {
364 + ...state.draft,
365 + attachments: [{ id: "added" } as DraftComposerImageAttachment],
366 + };
367 + return true;
368 + });
369 + state.draft = { ...state.draft, text: "/side again?", attachments: [] };
370 + expect(await useThreadComposerState({ startSideChat }).onSendMessage()).toBeNull();
371 + expect(startSideChat).toHaveBeenCalledOnce();
372 + expect(state.clearDraft).not.toHaveBeenCalled();
373 + });
374 +
375 it("rechecks a retained send callback before clearing or queueing the draft", async () => {
376 state.grantedEnvironments.add("secondary");
341 - const composer = useThreadComposerState();
377 + const composer = useThreadComposerState(NO_SIDE_CHATS);
378 state.grantedEnvironments.delete("secondary");
379 expect(await composer.onSendMessage()).toBeNull();
380 expect(state.clearDraft).not.toHaveBeenCalled();
@@ -482,24 +518,27 @@ describe("mobile handoff preview and submission", () => {
518 ],
519 };
520
485 - const disabled = useThreadComposerState();
521 + const disabled = useThreadComposerState(NO_SIDE_CHATS);
522 expect(disabled.pendingHandoff).toBeNull();
523 expect(await disabled.onSendMessage()).toBeNull();
524 expect(state.enqueue).not.toHaveBeenCalled();
525 expect(state.clearDraft).not.toHaveBeenCalled();
526
527 projectOverride.enabled = true;
492 - expect(useThreadComposerState().pendingHandoff).toEqual({ from: [source], to: selection });
528 + expect(useThreadComposerState(NO_SIDE_CHATS).pendingHandoff).toEqual({
529 + from: [source],
530 + to: selection,
531 + });
532
533 provider.availability = "unavailable";
495 - const unavailable = useThreadComposerState();
534 + const unavailable = useThreadComposerState(NO_SIDE_CHATS);
535 expect(unavailable.pendingHandoff).toBeNull();
536 expect(await unavailable.onSendMessage()).toBeNull();
537 expect(state.enqueue).not.toHaveBeenCalled();
538 expect(state.clearDraft).not.toHaveBeenCalled();
539
540 provider.availability = "available";
502 - const available = useThreadComposerState();
541 + const available = useThreadComposerState(NO_SIDE_CHATS);
542 expect(available.pendingHandoff).toEqual({ from: [source], to: selection });
543 expect(await available.onSendMessage()).toBe("message");
544 expect(state.enqueue).toHaveBeenCalledExactlyOnceWith(
apps/mobile/src/state/use-thread-composer-state.ts
+70 -2
@@ -22,9 +22,11 @@ import {
22 DEFAULT_PROVIDER_INTERACTION_MODE,
23 MessageId,
24 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
25 + orchestrationV2WorktreePending,
26 type EnvironmentId,
27 type ModelSelection,
28 type ProviderInteractionMode,
29 + type ScopedThreadRef,
30 type ServerProvider,
31 type ThreadId,
32 } from "@t3tools/contracts";
@@ -82,7 +84,7 @@ import {
84 useComposerDraft,
85 useComposerDraftSettings,
86 } from "./use-composer-drafts";
85 -import { isClearComposerCommand } from "@t3tools/shared/composerTrigger";
87 +import { isClearComposerCommand, parseSideChatCommand } from "@t3tools/shared/composerTrigger";
88 import {
89 resolveComposerDispatchMode,
90 type ActiveTurnComposerAction,
@@ -192,7 +194,10 @@ export function updateThreadDraftModelSelection(
194 });
195 }
196
195 -export function useThreadComposerState() {
197 +export function useThreadComposerState(input: {
198 + /** Forks the thread into a side chat that gets `prompt`; resolves false when it did not start. */
199 + readonly startSideChat: (source: ScopedThreadRef, prompt: string) => Promise<boolean>;
200 +}) {
201 const {
202 selectedThread: selectedThreadShell,
203 selectedThreadCreation,
@@ -216,6 +221,7 @@ export function useThreadComposerState() {
221 });
222 const [isSavingQueuedEdit, setIsSavingQueuedEdit] = useState(false);
223 const savingQueuedEditRef = useRef(false);
224 + const startingSideChatRef = useRef(false);
225
226 const selectedThreadKey = selectedThreadShell
227 ? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id)
@@ -557,6 +563,41 @@ export function useThreadComposerState() {
563 if (text.length === 0 && attachments.length === 0) {
564 return null;
565 }
566 + // A redirect's text answers its approval, so `/side` there is that text, not the command.
567 + const sideChatCommand = beforeDispatch === undefined ? parseSideChatCommand(text) : null;
568 + if (sideChatCommand) {
569 + if (sideChatUnavailableReason !== null) {
570 + Dialog.alert("Side chat not started", sideChatUnavailableReason);
571 + } else if (attachments.length > 0 || (draft.context?.records.length ?? 0) > 0) {
572 + Dialog.alert(
573 + "Side chats take text only",
574 + "Remove the attachments and context, then send it again.",
575 + );
576 + } else if (sideChatCommand.prompt.length === 0) {
577 + Dialog.alert("Ask a side question", "Type the question after /side, then send it.");
578 + } else if (!startingSideChatRef.current) {
579 + startingSideChatRef.current = true;
580 + const started = await input
581 + .startSideChat(
582 + { environmentId: thread.environmentId, threadId: thread.id },
583 + sideChatCommand.prompt,
584 + )
585 + .finally(() => {
586 + startingSideChatRef.current = false;
587 + });
588 + // Clear only what was sent; the draft may have changed while the side chat started.
589 + const current = getComposerDraftSnapshot(threadKey);
590 + if (
591 + started &&
592 + current.text === draft.text &&
593 + current.attachments.length === 0 &&
594 + (current.context?.records.length ?? 0) === 0
595 + ) {
596 + clearComposerDraftContent(threadKey);
597 + }
598 + }
599 + return null;
600 + }
601 // A redirect's text answers its approval, so /clear there is that text, not the command.
602 if (
603 beforeDispatch === undefined &&
@@ -759,6 +800,32 @@ export function useThreadComposerState() {
800 return messageId;
801 };
802
803 + // Side chats do not nest or start from subagents, and need a server that forks them.
804 + const sideChatUnavailableReason = (() => {
805 + const serverConfig = selectedEnvironmentRuntime?.serverConfig;
806 + if (selectedThreadShell?.lineage.sideChat === true)
807 + return "Side chats cannot start side chats.";
808 + if (selectedThreadShell?.lineage.relationshipToParent === "subagent") {
809 + return "Subagent threads cannot start side chats.";
810 + }
811 + if (!selectedThreadShell || !serverConfig) {
812 + return "Side chats are not ready yet. Try again in a moment.";
813 + }
814 + if (serverConfig.environment.capabilities.sideChats !== true) {
815 + return "Update this environment's T3 Code server to use side chats.";
816 + }
817 + if (selectedThreadCreation !== null) return "Side chats start after the first message.";
818 + if (
819 + orchestrationV2WorktreePending(
820 + selectedThreadShell.worktreePath ?? null,
821 + selectedThreadProjection?.projection.runs ?? [],
822 + )
823 + ) {
824 + return "Available once the thread's worktree is set up.";
825 + }
826 + return null;
827 + })();
828 +
829 const onChangeDraftMessage = (value: string) => {
830 if (!selectedThreadShell) {
831 return;
@@ -833,5 +900,6 @@ export function useThreadComposerState() {
900 onRemoveDraftImage,
901 onSendMessage,
902 onUpdateInteractionMode,
903 + sideChatUnavailableReason,
904 };
905 }
apps/web/src/components/chat/useComposerSend.ts
+1 -2
@@ -1,4 +1,4 @@
1 -import { isClearComposerCommand } from "@t3tools/shared/composerTrigger";
1 +import { isClearComposerCommand, parseSideChatCommand } from "@t3tools/shared/composerTrigger";
2 import { armFreshSession, disarmFreshSession, readFreshSessionArm } from "./freshSessionArms";
3 import {
4 mergeDirectPreviewAnnotation,
@@ -56,7 +56,6 @@ import {
56 import {
57 type ComposerSubmissionIntent,
58 collapseExpandedComposerCursor,
59 - parseSideChatCommand,
59 parseStandaloneComposerSlashCommand,
60 } from "../../composer-logic";
61 import { resolvePlanFollowUpSubmission } from "../../proposedPlan";
apps/web/src/composer-logic.test.ts
+2 -14
@@ -22,7 +22,6 @@ import {
22 extendReplacementRangeForTrailingSpace,
23 formatAssistantCitationForComposer,
24 isPathSuggestionCurrent,
25 - parseSideChatCommand,
25 replaceTextRange,
26 } from "./composer-logic";
27 import { slashCommandItemsForPromptPosition } from "./components/chat/composerSlashCommandSearch";
@@ -551,19 +550,8 @@ describe("extendReplacementRangeForTrailingSpace", () => {
550 });
551 });
552
554 -describe("parseSideChatCommand", () => {
555 - it("reads an optional prompt after /side or /btw", () => {
556 - expect(parseSideChatCommand("/side")).toEqual({ prompt: "" });
557 - expect(parseSideChatCommand(" /SIDE why does this fail?\nline two ")).toEqual({
558 - prompt: "why does this fail?\nline two",
559 - });
560 - expect(parseSideChatCommand("/btw check @src/a.ts")).toEqual({ prompt: "check @src/a.ts" });
561 - });
562 -
563 - it("ignores other commands and inline mentions, which the menu does not offer", () => {
564 - expect(parseSideChatCommand("/sidebar")).toBeNull();
565 - expect(parseSideChatCommand("/btwx")).toBeNull();
566 - expect(parseSideChatCommand("ask /side later")).toBeNull();
553 +describe("side chat slash commands", () => {
554 + it("are not offered after the start of a message", () => {
555 const items = (["side", "btw", "clear", "plan"] as const).map((command) => ({
556 id: `slash:${command}`,
557 type: "slash-command" as const,
apps/web/src/composer-logic.ts
-6
@@ -318,12 +318,6 @@ export function composerStateAtPromptEnd(
318 };
319 }
320
321 -/** `/side [prompt]`, or its alias `/btw [prompt]`, as the whole message. */
322 -export function parseSideChatCommand(text: string): { prompt: string } | null {
323 - const match = /^\/(?:side|btw)(?:\s+([\s\S]*))?$/i.exec(text.trim());
324 - return match ? { prompt: match[1]?.trim() ?? "" } : null;
325 -}
326 -
321 export function parseStandaloneComposerSlashCommand(
322 text: string,
323 ): Exclude<ComposerSlashCommand, "model" | "side" | "btw" | "clear"> | null {
packages/shared/src/composerTrigger.test.ts
+21 -1
@@ -1,6 +1,10 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 -import { detectComposerTrigger, serializeComposerFileLink } from "./composerTrigger.ts";
3 +import {
4 + detectComposerTrigger,
5 + parseSideChatCommand,
6 + serializeComposerFileLink,
7 +} from "./composerTrigger.ts";
8
9 describe("detectComposerTrigger", () => {
10 it.each([
@@ -91,3 +95,19 @@ describe("serializeComposerFileLink", () => {
95 );
96 });
97 });
98 +
99 +describe("parseSideChatCommand", () => {
100 + it("reads an optional prompt after /side or /btw", () => {
101 + expect(parseSideChatCommand("/side")).toEqual({ prompt: "" });
102 + expect(parseSideChatCommand(" /SIDE why does this fail?\nline two ")).toEqual({
103 + prompt: "why does this fail?\nline two",
104 + });
105 + expect(parseSideChatCommand("/btw check @src/a.ts")).toEqual({ prompt: "check @src/a.ts" });
106 + });
107 +
108 + it("ignores other commands and inline mentions", () => {
109 + expect(parseSideChatCommand("/sidebar")).toBeNull();
110 + expect(parseSideChatCommand("/btwx")).toBeNull();
111 + expect(parseSideChatCommand("ask /side later")).toBeNull();
112 + });
113 +});
packages/shared/src/composerTrigger.ts
+6
@@ -174,3 +174,9 @@ export function replaceTextRange(
174 export function isClearComposerCommand(text: string): boolean {
175 return /^\/clear\s*$/i.test(text.trim());
176 }
177 +
178 +/** `/side [prompt]`, or its alias `/btw [prompt]`, as the whole message. */
179 +export function parseSideChatCommand(text: string): { prompt: string } | null {
180 + const match = /^\/(?:side|btw)(?:\s+([\s\S]*))?$/i.exec(text.trim());
181 + return match ? { prompt: match[1]?.trim() ?? "" } : null;
182 +}