Skip to content
TypeScript

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

Julius Marminge0f28f6f6a001
diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
index 6908688f9f2..fd0ea7e1e48 100644
--- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
+++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
@@ -983,6 +983,7 @@ export function NewTaskDraftScreen(props: {
onStopThread={() => {}}
onResumeQueue={null}
onSendMessage={handleStart}
+ offersSideChat={false}
onReconnectEnvironment={() => onReconnectEnvironment(selectedProject.environmentId)}
canSwitchThreadProvider
onUpdateThreadInteractionMode={flow.planModeEnabled ? flow.setInteractionMode : undefined}
diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx
index 0de134de7c2..f588dcfa388 100644
--- a/apps/mobile/src/features/threads/ThreadComposer.tsx
+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx
@@ -217,6 +217,7 @@ export interface ThreadComposerProps {
readonly hasCompactableConversation: boolean;
/** Arms a fresh session for the next message; absent where `/clear` is unavailable. */
readonly onFreshSession?: () => void;
+ readonly offersSideChat?: boolean;
readonly serverConfig: T3ServerConfig | null;
readonly queueCount: number;
readonly activeThreadBusy: boolean;
@@ -564,6 +565,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
onUsageLimits:
usageLimitsOffered && draftAttachments.length === 0 ? openUsageLimits : undefined,
...(props.onFreshSession === undefined ? {} : { onFreshSession: props.onFreshSession }),
+ offersSideChat: props.offersSideChat === true,
});
const voiceInput = useVoiceInputController({
ownerKey: composerDraftKey,
diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
index 9a470e7c4bf..255724094aa 100644
--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
@@ -287,6 +287,7 @@ export interface ThreadDetailScreenProps {
readonly onStopThread: () => void;
/** Present while the thread's queue is held. */
readonly onResumeQueue: (() => Promise<void>) | null;
+ readonly offersSideChat: boolean;
readonly onSendMessage: (
followUp?: ActiveTurnComposerAction,
beforeDispatch?: (
@@ -1836,6 +1837,14 @@ function ThreadDetailBody(
onFreshSession: () => setFreshSessionPending(selectedThreadKey, true),
}
: {})}
+ offersSideChat={
+ props.offersSideChat &&
+ !props.draftMode &&
+ props.canOperateThread &&
+ props.queuedRunEdit === null &&
+ props.activePendingApproval === null &&
+ props.activePendingUserInput === null
+ }
serverConfig={props.serverConfig}
queueCount={props.selectedThreadQueueCount}
activeThreadBusy={props.activeThreadBusy}
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
index a15037a5bc6..d5def4f2939 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -275,7 +275,7 @@ import {
resolveWorkspaceFilePath,
resolveWorkspaceRelativeFilePath,
} from "../files/filePath";
-import { waitForThreadShellReady } from "./threadForkNavigation";
+import { waitForThreadShell } from "./threadForkNavigation";
import { resolveUserMessageIntentBadge } from "./userMessageIntentBadge";
import { fileChipClipboardPath, fileChipMenu, resolveFileChipTarget } from "./fileChipMenu";
import { useFileChipShare } from "./useFileChipShare";
@@ -381,16 +381,6 @@ export interface ThreadFeedProps {
readonly onUseArtifactTemplate?: (template: CodexArtifactTemplate) => void;
}
-async function waitForThreadShell(
- environmentId: EnvironmentId,
- threadId: ThreadId,
-): Promise<boolean> {
- const atom = environmentThreadShells.threadShellAtom(scopeThreadRef(environmentId, threadId));
- return waitForThreadShellReady({
- read: () => appAtomRegistry.get(atom) !== null,
- });
-}
-
const USER_MESSAGE_COPY_MENU_ACTIONS = [
{ id: "copy-prompt-link", title: "Copy prompt link", image: "link" },
];
@@ -470,7 +460,9 @@ function AssistantForkButton(props: {
})
.then(async (result) => {
if (result._tag !== "Success") return;
- const targetThreadReady = await waitForThreadShell(props.environmentId, targetThreadId);
+ const targetThreadReady = await waitForThreadShell(
+ scopeThreadRef(props.environmentId, targetThreadId),
+ );
if (!targetThreadReady) {
Dialog.alert(
"Fork created",
diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
index 94ddab608bd..4432da72cfb 100644
--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
@@ -111,6 +111,7 @@ import {
ThreadInspectorPreview,
type ThreadInspectorPresentation,
} from "./thread-inspector-preview";
+import { useStartSideChat } from "./useStartSideChat";
import type { ThreadInspectorMode, ThreadInspectorTarget } from "./thread-inspector-navigation";
import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
@@ -368,7 +369,8 @@ function ThreadRouteContent(
const selectedThreadDetailState = props.selectedThreadDetailState;
const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
const { selectedThreadCwd } = useSelectedThreadWorktree();
- const composer = useThreadComposerState();
+ const startSideChat = useStartSideChat();
+ const composer = useThreadComposerState({ startSideChat });
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
const requests = useSelectedThreadRequests();
@@ -1070,6 +1072,7 @@ function ThreadRouteContent(
composer.queueHeld || composer.resumableRunId !== null ? handleResumeQueue : null
}
onSendMessage={composer.onSendMessage}
+ offersSideChat={composer.sideChatUnavailableReason === null}
onReconnectEnvironment={handleReconnectEnvironment}
canSwitchThreadProvider={composer.canSwitchThreadProvider}
onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
diff --git a/apps/mobile/src/features/threads/threadForkNavigation.ts b/apps/mobile/src/features/threads/threadForkNavigation.ts
index 97ebf9c97bc..b64b4011947 100644
--- a/apps/mobile/src/features/threads/threadForkNavigation.ts
+++ b/apps/mobile/src/features/threads/threadForkNavigation.ts
@@ -1,26 +1,20 @@
-const DEFAULT_TIMEOUT_MS = 2_000;
-const DEFAULT_POLL_INTERVAL_MS = 40;
+import type { ScopedThreadRef } from "@t3tools/contracts";
-export async function waitForThreadShellReady(input: {
- readonly read: () => boolean;
- readonly timeoutMs?: number;
- readonly pollIntervalMs?: number;
- readonly now?: () => number;
- readonly delay?: (durationMs: number) => Promise<void>;
-}): Promise<boolean> {
- const now = input.now ?? Date.now;
- const delay =
- input.delay ??
- ((durationMs: number) =>
- new Promise<void>((resolve) => {
- setTimeout(resolve, durationMs);
- }));
- const deadline = now() + (input.timeoutMs ?? DEFAULT_TIMEOUT_MS);
- const pollIntervalMs = input.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
+import { appAtomRegistry } from "../../state/atom-registry";
+import { environmentThreadShells } from "../../state/threads";
- while (!input.read() && now() < deadline) {
- await delay(Math.min(pollIntervalMs, deadline - now()));
- }
+const TIMEOUT_MS = 2_000;
+const POLL_INTERVAL_MS = 40;
- return input.read();
+/** Resolves true once a thread this client just created, such as a fork, reaches its state. */
+export async function waitForThreadShell(ref: ScopedThreadRef): Promise<boolean> {
+ const atom = environmentThreadShells.threadShellAtom(ref);
+ const read = () => appAtomRegistry.get(atom) !== null;
+ const deadline = Date.now() + TIMEOUT_MS;
+ while (!read() && Date.now() < deadline) {
+ await new Promise<void>((resolve) => {
+ setTimeout(resolve, Math.min(POLL_INTERVAL_MS, deadline - Date.now()));
+ });
+ }
+ return read();
}
diff --git a/apps/mobile/src/features/threads/use-composer-command-menu.ts b/apps/mobile/src/features/threads/use-composer-command-menu.ts
index 4363f26ad3b..1d2fe31a2d4 100644
--- a/apps/mobile/src/features/threads/use-composer-command-menu.ts
+++ b/apps/mobile/src/features/threads/use-composer-command-menu.ts
@@ -106,6 +106,7 @@ export function buildComposerSlashCommandItems(input: {
readonly offersUsageLimits?: boolean;
/** T3's `/clear` replaces the provider's, which would clear a session T3 still treats as live. */
readonly offersFreshSession?: boolean;
+ readonly offersSideChat?: boolean;
readonly allowInteractionMode: boolean;
readonly selectedProviderStatus: Pick<
ServerProvider,
@@ -145,6 +146,21 @@ export function buildComposerSlashCommandItems(input: {
// Providers expand commands only at the start of a message. T3 commands
// change local state and do not have this restriction, except `/clear`.
if (!input.atMessageStart) return items;
+ if (input.offersSideChat) {
+ for (const [command, description] of [
+ ["side", "Ask a side question in a new side chat"],
+ ["btw", "Same as /side"],
+ ] as const) {
+ if (!command.includes(query)) continue;
+ items.push({
+ id: `cmd:${command}`,
+ type: "slash-command",
+ command,
+ label: `/${command}`,
+ description,
+ });
+ }
+ }
if (input.offersFreshSession && "clear".includes(query)) {
items.push({
id: "cmd:clear",
@@ -238,6 +254,7 @@ export function useComposerCommandMenu({
onUpdateInteractionMode,
onUsageLimits,
onFreshSession,
+ offersSideChat = false,
}: {
readonly draftMessage: string;
readonly ownerKey: string | null;
@@ -261,6 +278,7 @@ export function useComposerCommandMenu({
readonly onUsageLimits?: () => void;
/** Arms a fresh session for the next message; absent where `/clear` is unavailable. */
readonly onFreshSession?: () => void;
+ readonly offersSideChat?: boolean;
}) {
const [localSelection, setLocalSelection] = useState(() => ({
ownerKey,
@@ -365,6 +383,7 @@ export function useComposerCommandMenu({
hasCompactableConversation,
offersUsageLimits,
offersFreshSession: onFreshSession !== undefined,
+ offersSideChat,
allowInteractionMode: onUpdateInteractionMode !== undefined,
selectedProviderStatus: selectedProviderStatus
? {
diff --git a/apps/mobile/src/features/threads/useStartSideChat.ts b/apps/mobile/src/features/threads/useStartSideChat.ts
new file mode 100644
index 00000000000..b9c6287a257
--- /dev/null
+++ b/apps/mobile/src/features/threads/useStartSideChat.ts
@@ -0,0 +1,97 @@
+import { scopeThreadRef } from "@t3tools/client-runtime/environment";
+import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
+import {
+ isAtomCommandInterrupted,
+ squashAtomCommandFailure,
+ type AtomCommandResult,
+} from "@t3tools/client-runtime/state/runtime";
+import { MessageId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
+
+import * as Dialog from "../../components/ui/Dialog";
+import { uuidv4 } from "../../lib/uuid";
+import { appAtomRegistry } from "../../state/atom-registry";
+import { environmentThreadShells, threadEnvironment } from "../../state/threads";
+import { useAtomCommand } from "../../state/use-atom-command";
+import { waitForThreadShell } from "./threadForkNavigation";
+import { useOpenLinkedThread } from "./useOpenLinkedThread";
+
+/**
+ * Forks `source` at its latest stable point into a side chat, sends `prompt` there, and opens
+ * it like any linked thread. Resolves false when the side chat did not start.
+ */
+export function useStartSideChat() {
+ const forkSideChat = useAtomCommand(threadEnvironment.forkSideChat, { reportFailure: false });
+ const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
+ const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
+ const openLinkedThread = useOpenLinkedThread();
+
+ const alertFailure = (
+ failure: Extract<AtomCommandResult<unknown, unknown>, { readonly _tag: "Failure" }>,
+ fallback: string,
+ ) => {
+ if (isAtomCommandInterrupted(failure)) return;
+ const error = squashAtomCommandFailure(failure);
+ Dialog.alert("Side chat not started", error instanceof Error ? error.message : fallback);
+ };
+
+ return async (source: ScopedThreadRef, prompt: string): Promise<boolean> => {
+ const targetThreadId = ThreadId.make(uuidv4());
+ const fork = await forkSideChat({
+ environmentId: source.environmentId,
+ input: {
+ sourceThreadId: source.threadId,
+ targetThreadId,
+ title: "Side chat",
+ creationSource: "mobile",
+ },
+ });
+ if (fork._tag === "Failure") {
+ alertFailure(fork, "Could not start a side chat.");
+ return false;
+ }
+ // Drops the empty side chat a failed start leaves behind; one that got its message stays.
+ const discard = () =>
+ void deleteThread({
+ environmentId: source.environmentId,
+ input: { threadId: targetThreadId, onlyIfUnused: true },
+ });
+ const targetRef = scopeThreadRef(source.environmentId, targetThreadId);
+ if (!(await waitForThreadShell(targetRef))) {
+ Dialog.alert(
+ "Side chat not started",
+ "The side chat was created, but it did not reach this device.",
+ );
+ discard();
+ return false;
+ }
+ const sideChat = appAtomRegistry.get(environmentThreadShells.threadShellAtom(targetRef));
+ if (sideChat === null) {
+ Dialog.alert("Side chat not started", "The side chat is no longer available.");
+ discard();
+ return false;
+ }
+ const turn = await startTurn({
+ environmentId: source.environmentId,
+ input: {
+ threadId: targetThreadId,
+ message: {
+ messageId: MessageId.make(uuidv4()),
+ role: "user",
+ text: prompt,
+ attachments: [],
+ },
+ titleSeed: deriveThreadTitleSeed({ text: prompt, attachments: [] }),
+ runtimeMode: sideChat.runtimeMode,
+ interactionMode: "default",
+ createdAt: new Date().toISOString(),
+ },
+ });
+ if (turn._tag === "Failure") {
+ alertFailure(turn, "Could not send the side chat message.");
+ discard();
+ return false;
+ }
+ openLinkedThread({ environmentId: source.environmentId, threadId: targetThreadId });
+ return true;
+ };
+}
diff --git a/apps/mobile/src/state/thread-task-permissions.test.ts b/apps/mobile/src/state/thread-task-permissions.test.ts
index c1f83f5a620..76c485531c8 100644
--- a/apps/mobile/src/state/thread-task-permissions.test.ts
+++ b/apps/mobile/src/state/thread-task-permissions.test.ts
@@ -53,6 +53,7 @@ const state = vi.hoisted(() => ({
thread: {
id: "thread",
environmentId: "secondary",
+ lineage: { rootThreadId: "thread", parentThreadId: null, relationshipToParent: null },
projectId: "project",
modelSelection: { instanceId: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
@@ -187,6 +188,8 @@ vi.mock("./use-remote-environment-registry", () => ({ setPendingConnectionError:
import { useThreadComposerState } from "./use-thread-composer-state";
import { useSelectedThreadRequests } from "./use-selected-thread-requests";
+const NO_SIDE_CHATS = { startSideChat: async () => false };
+
beforeEach(() => {
state.grantedEnvironments = new Set(["primary"]);
state.connectionState = "connected";
@@ -219,7 +222,7 @@ beforeEach(() => {
describe("mobile task permissions", () => {
it("consumes an approval reply without queueing a parent message", async () => {
state.grantedEnvironments.add("secondary");
- const composer = useThreadComposerState();
+ const composer = useThreadComposerState(NO_SIDE_CHATS);
const requests = useSelectedThreadRequests();
const approval = { ...state.pendingRequests.approvals[0]!, supportsFeedback: true };
const messageId = await composer.onSendMessage(undefined, async (text) =>
@@ -243,7 +246,7 @@ describe("mobile task permissions", () => {
it("preserves a draft changed during an approval reply and never sends it to the parent", async () => {
state.grantedEnvironments.add("secondary");
- const composer = useThreadComposerState();
+ const composer = useThreadComposerState(NO_SIDE_CHATS);
const beforeDispatch = async () => {
state.draft = { ...state.draft, text: "New feedback" };
return "responded" as const;
@@ -255,7 +258,7 @@ describe("mobile task permissions", () => {
});
it("keeps a connected read-only task's draft instead of queueing it with another environment's grant", async () => {
- const composer = useThreadComposerState();
+ const composer = useThreadComposerState(NO_SIDE_CHATS);
expect(await composer.onSendMessage()).toBeNull();
expect(state.enqueue).not.toHaveBeenCalled();
expect(state.clearDraft).not.toHaveBeenCalled();
@@ -270,7 +273,7 @@ describe("mobile task permissions", () => {
it("keeps an armed fresh session for the message after an approval redirect", async () => {
state.grantedEnvironments.add("secondary");
state.freshPending = true;
- const composer = useThreadComposerState();
+ const composer = useThreadComposerState(NO_SIDE_CHATS);
expect(await composer.onSendMessage(undefined, async () => true)).toBe("message");
expect(state.enqueue).toHaveBeenLastCalledWith(
expect.not.objectContaining({ freshContext: true }),
@@ -308,7 +311,7 @@ describe("mobile task permissions", () => {
updatedAt: DateTime.makeUnsafe(0),
} as unknown as OrchestrationV2ThreadProjection;
state.compactDue = true;
- const composer = useThreadComposerState();
+ const composer = useThreadComposerState(NO_SIDE_CHATS);
await composer.onSendMessage();
expect(state.enqueue).toHaveBeenLastCalledWith(
expect.objectContaining({ compactBeforeSend: true }),
@@ -329,16 +332,49 @@ describe("mobile task permissions", () => {
} as ServerConfig;
state.thread.latestRun = { runId: "run" };
state.draft = { ...state.draft, text: "/clear" };
- const composer = useThreadComposerState();
+ const composer = useThreadComposerState(NO_SIDE_CHATS);
const beforeDispatch = vi.fn(async () => "responded" as const);
expect(await composer.onSendMessage(undefined, beforeDispatch)).toBeNull();
expect(beforeDispatch).toHaveBeenCalledWith("/clear", false);
expect(state.setFreshPending).not.toHaveBeenCalled();
});
+ it("starts a side chat for /side instead of sending to the thread", async () => {
+ state.grantedEnvironments.add("secondary");
+ state.serverConfig = {
+ ...state.serverConfig,
+ environment: { capabilities: { sideChats: true } },
+ } as ServerConfig;
+ state.draft = { ...state.draft, text: "/side why does this fail?" };
+ const startSideChat = vi.fn(async () => true);
+ const composer = useThreadComposerState({ startSideChat });
+ expect(composer.sideChatUnavailableReason).toBeNull();
+ expect(await composer.onSendMessage()).toBeNull();
+ expect(startSideChat).toHaveBeenCalledExactlyOnceWith(
+ { environmentId: "secondary", threadId: "thread" },
+ "why does this fail?",
+ );
+ expect(state.enqueue).not.toHaveBeenCalled();
+ expect(state.clearDraft).toHaveBeenCalled();
+
+ // An attachment added while the side chat starts stays in the draft.
+ vi.clearAllMocks();
+ startSideChat.mockImplementationOnce(async () => {
+ state.draft = {
+ ...state.draft,
+ attachments: [{ id: "added" } as DraftComposerImageAttachment],
+ };
+ return true;
+ });
+ state.draft = { ...state.draft, text: "/side again?", attachments: [] };
+ expect(await useThreadComposerState({ startSideChat }).onSendMessage()).toBeNull();
+ expect(startSideChat).toHaveBeenCalledOnce();
+ expect(state.clearDraft).not.toHaveBeenCalled();
+ });
+
it("rechecks a retained send callback before clearing or queueing the draft", async () => {
state.grantedEnvironments.add("secondary");
- const composer = useThreadComposerState();
+ const composer = useThreadComposerState(NO_SIDE_CHATS);
state.grantedEnvironments.delete("secondary");
expect(await composer.onSendMessage()).toBeNull();
expect(state.clearDraft).not.toHaveBeenCalled();
@@ -482,24 +518,27 @@ describe("mobile handoff preview and submission", () => {
],
};
- const disabled = useThreadComposerState();
+ const disabled = useThreadComposerState(NO_SIDE_CHATS);
expect(disabled.pendingHandoff).toBeNull();
expect(await disabled.onSendMessage()).toBeNull();
expect(state.enqueue).not.toHaveBeenCalled();
expect(state.clearDraft).not.toHaveBeenCalled();
projectOverride.enabled = true;
- expect(useThreadComposerState().pendingHandoff).toEqual({ from: [source], to: selection });
+ expect(useThreadComposerState(NO_SIDE_CHATS).pendingHandoff).toEqual({
+ from: [source],
+ to: selection,
+ });
provider.availability = "unavailable";
- const unavailable = useThreadComposerState();
+ const unavailable = useThreadComposerState(NO_SIDE_CHATS);
expect(unavailable.pendingHandoff).toBeNull();
expect(await unavailable.onSendMessage()).toBeNull();
expect(state.enqueue).not.toHaveBeenCalled();
expect(state.clearDraft).not.toHaveBeenCalled();
provider.availability = "available";
- const available = useThreadComposerState();
+ const available = useThreadComposerState(NO_SIDE_CHATS);
expect(available.pendingHandoff).toEqual({ from: [source], to: selection });
expect(await available.onSendMessage()).toBe("message");
expect(state.enqueue).toHaveBeenCalledExactlyOnceWith(
diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts
index d10f3fb48c9..139e5f79448 100644
--- a/apps/mobile/src/state/use-thread-composer-state.ts
+++ b/apps/mobile/src/state/use-thread-composer-state.ts
@@ -22,9 +22,11 @@ import {
DEFAULT_PROVIDER_INTERACTION_MODE,
MessageId,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
+ orchestrationV2WorktreePending,
type EnvironmentId,
type ModelSelection,
type ProviderInteractionMode,
+ type ScopedThreadRef,
type ServerProvider,
type ThreadId,
} from "@t3tools/contracts";
@@ -82,7 +84,7 @@ import {
useComposerDraft,
useComposerDraftSettings,
} from "./use-composer-drafts";
-import { isClearComposerCommand } from "@t3tools/shared/composerTrigger";
+import { isClearComposerCommand, parseSideChatCommand } from "@t3tools/shared/composerTrigger";
import {
resolveComposerDispatchMode,
type ActiveTurnComposerAction,
@@ -192,7 +194,10 @@ export function updateThreadDraftModelSelection(
});
}
-export function useThreadComposerState() {
+export function useThreadComposerState(input: {
+ /** Forks the thread into a side chat that gets `prompt`; resolves false when it did not start. */
+ readonly startSideChat: (source: ScopedThreadRef, prompt: string) => Promise<boolean>;
+}) {
const {
selectedThread: selectedThreadShell,
selectedThreadCreation,
@@ -216,6 +221,7 @@ export function useThreadComposerState() {
});
const [isSavingQueuedEdit, setIsSavingQueuedEdit] = useState(false);
const savingQueuedEditRef = useRef(false);
+ const startingSideChatRef = useRef(false);
const selectedThreadKey = selectedThreadShell
? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id)
@@ -557,6 +563,41 @@ export function useThreadComposerState() {
if (text.length === 0 && attachments.length === 0) {
return null;
}
+ // A redirect's text answers its approval, so `/side` there is that text, not the command.
+ const sideChatCommand = beforeDispatch === undefined ? parseSideChatCommand(text) : null;
+ if (sideChatCommand) {
+ if (sideChatUnavailableReason !== null) {
+ Dialog.alert("Side chat not started", sideChatUnavailableReason);
+ } else if (attachments.length > 0 || (draft.context?.records.length ?? 0) > 0) {
+ Dialog.alert(
+ "Side chats take text only",
+ "Remove the attachments and context, then send it again.",
+ );
+ } else if (sideChatCommand.prompt.length === 0) {
+ Dialog.alert("Ask a side question", "Type the question after /side, then send it.");
+ } else if (!startingSideChatRef.current) {
+ startingSideChatRef.current = true;
+ const started = await input
+ .startSideChat(
+ { environmentId: thread.environmentId, threadId: thread.id },
+ sideChatCommand.prompt,
+ )
+ .finally(() => {
+ startingSideChatRef.current = false;
+ });
+ // Clear only what was sent; the draft may have changed while the side chat started.
+ const current = getComposerDraftSnapshot(threadKey);
+ if (
+ started &&
+ current.text === draft.text &&
+ current.attachments.length === 0 &&
+ (current.context?.records.length ?? 0) === 0
+ ) {
+ clearComposerDraftContent(threadKey);
+ }
+ }
+ return null;
+ }
// A redirect's text answers its approval, so /clear there is that text, not the command.
if (
beforeDispatch === undefined &&
@@ -759,6 +800,32 @@ export function useThreadComposerState() {
return messageId;
};
+ // Side chats do not nest or start from subagents, and need a server that forks them.
+ const sideChatUnavailableReason = (() => {
+ const serverConfig = selectedEnvironmentRuntime?.serverConfig;
+ if (selectedThreadShell?.lineage.sideChat === true)
+ return "Side chats cannot start side chats.";
+ if (selectedThreadShell?.lineage.relationshipToParent === "subagent") {
+ return "Subagent threads cannot start side chats.";
+ }
+ if (!selectedThreadShell || !serverConfig) {
+ return "Side chats are not ready yet. Try again in a moment.";
+ }
+ if (serverConfig.environment.capabilities.sideChats !== true) {
+ return "Update this environment's T3 Code server to use side chats.";
+ }
+ if (selectedThreadCreation !== null) return "Side chats start after the first message.";
+ if (
+ orchestrationV2WorktreePending(
+ selectedThreadShell.worktreePath ?? null,
+ selectedThreadProjection?.projection.runs ?? [],
+ )
+ ) {
+ return "Available once the thread's worktree is set up.";
+ }
+ return null;
+ })();
+
const onChangeDraftMessage = (value: string) => {
if (!selectedThreadShell) {
return;
@@ -833,5 +900,6 @@ export function useThreadComposerState() {
onRemoveDraftImage,
onSendMessage,
onUpdateInteractionMode,
+ sideChatUnavailableReason,
};
}
diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts
index db2fa10feb8..7e0b410134c 100644
--- a/apps/web/src/components/chat/useComposerSend.ts
+++ b/apps/web/src/components/chat/useComposerSend.ts
@@ -1,4 +1,4 @@
-import { isClearComposerCommand } from "@t3tools/shared/composerTrigger";
+import { isClearComposerCommand, parseSideChatCommand } from "@t3tools/shared/composerTrigger";
import { armFreshSession, disarmFreshSession, readFreshSessionArm } from "./freshSessionArms";
import {
mergeDirectPreviewAnnotation,
@@ -56,7 +56,6 @@ import {
import {
type ComposerSubmissionIntent,
collapseExpandedComposerCursor,
- parseSideChatCommand,
parseStandaloneComposerSlashCommand,
} from "../../composer-logic";
import { resolvePlanFollowUpSubmission } from "../../proposedPlan";
diff --git a/apps/web/src/composer-logic.test.ts b/apps/web/src/composer-logic.test.ts
index cb65ab6bde0..bc28bf73809 100644
--- a/apps/web/src/composer-logic.test.ts
+++ b/apps/web/src/composer-logic.test.ts
@@ -22,7 +22,6 @@ import {
extendReplacementRangeForTrailingSpace,
formatAssistantCitationForComposer,
isPathSuggestionCurrent,
- parseSideChatCommand,
replaceTextRange,
} from "./composer-logic";
import { slashCommandItemsForPromptPosition } from "./components/chat/composerSlashCommandSearch";
@@ -551,19 +550,8 @@ describe("extendReplacementRangeForTrailingSpace", () => {
});
});
-describe("parseSideChatCommand", () => {
- it("reads an optional prompt after /side or /btw", () => {
- expect(parseSideChatCommand("/side")).toEqual({ prompt: "" });
- expect(parseSideChatCommand(" /SIDE why does this fail?\nline two ")).toEqual({
- prompt: "why does this fail?\nline two",
- });
- expect(parseSideChatCommand("/btw check @src/a.ts")).toEqual({ prompt: "check @src/a.ts" });
- });
-
- it("ignores other commands and inline mentions, which the menu does not offer", () => {
- expect(parseSideChatCommand("/sidebar")).toBeNull();
- expect(parseSideChatCommand("/btwx")).toBeNull();
- expect(parseSideChatCommand("ask /side later")).toBeNull();
+describe("side chat slash commands", () => {
+ it("are not offered after the start of a message", () => {
const items = (["side", "btw", "clear", "plan"] as const).map((command) => ({
id: `slash:${command}`,
type: "slash-command" as const,
diff --git a/apps/web/src/composer-logic.ts b/apps/web/src/composer-logic.ts
index 1cfbaceb4b2..00196d63497 100644
--- a/apps/web/src/composer-logic.ts
+++ b/apps/web/src/composer-logic.ts
@@ -318,12 +318,6 @@ export function composerStateAtPromptEnd(
};
}
-/** `/side [prompt]`, or its alias `/btw [prompt]`, as the whole message. */
-export function parseSideChatCommand(text: string): { prompt: string } | null {
- const match = /^\/(?:side|btw)(?:\s+([\s\S]*))?$/i.exec(text.trim());
- return match ? { prompt: match[1]?.trim() ?? "" } : null;
-}
-
export function parseStandaloneComposerSlashCommand(
text: string,
): Exclude<ComposerSlashCommand, "model" | "side" | "btw" | "clear"> | null {
diff --git a/packages/shared/src/composerTrigger.test.ts b/packages/shared/src/composerTrigger.test.ts
index 7a33fc82e19..72ff3db848c 100644
--- a/packages/shared/src/composerTrigger.test.ts
+++ b/packages/shared/src/composerTrigger.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from "vite-plus/test";
-import { detectComposerTrigger, serializeComposerFileLink } from "./composerTrigger.ts";
+import {
+ detectComposerTrigger,
+ parseSideChatCommand,
+ serializeComposerFileLink,
+} from "./composerTrigger.ts";
describe("detectComposerTrigger", () => {
it.each([
@@ -91,3 +95,19 @@ describe("serializeComposerFileLink", () => {
);
});
});
+
+describe("parseSideChatCommand", () => {
+ it("reads an optional prompt after /side or /btw", () => {
+ expect(parseSideChatCommand("/side")).toEqual({ prompt: "" });
+ expect(parseSideChatCommand(" /SIDE why does this fail?\nline two ")).toEqual({
+ prompt: "why does this fail?\nline two",
+ });
+ expect(parseSideChatCommand("/btw check @src/a.ts")).toEqual({ prompt: "check @src/a.ts" });
+ });
+
+ it("ignores other commands and inline mentions", () => {
+ expect(parseSideChatCommand("/sidebar")).toBeNull();
+ expect(parseSideChatCommand("/btwx")).toBeNull();
+ expect(parseSideChatCommand("ask /side later")).toBeNull();
+ });
+});
diff --git a/packages/shared/src/composerTrigger.ts b/packages/shared/src/composerTrigger.ts
index 68e3c51087b..80292492154 100644
--- a/packages/shared/src/composerTrigger.ts
+++ b/packages/shared/src/composerTrigger.ts
@@ -174,3 +174,9 @@ export function replaceTextRange(
export function isClearComposerCommand(text: string): boolean {
return /^\/clear\s*$/i.test(text.trim());
}
+
+/** `/side [prompt]`, or its alias `/btw [prompt]`, as the whole message. */
+export function parseSideChatCommand(text: string): { prompt: string } | null {
+ const match = /^\/(?:side|btw)(?:\s+([\s\S]*))?$/i.exec(text.trim());
+ return match ? { prompt: match[1]?.trim() ?? "" } : null;
+}