Skip to content

Commit e455200

Browse files
authored
fix: side chats start with the parent's permission mode and reasoning level (#32315)
1 parent 97d04c3 commit e455200

6 files changed

Lines changed: 127 additions & 26 deletions

File tree

‎apps/mobile/src/features/threads/useStartSideChat.ts‎

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,13 @@ import {
55
squashAtomCommandFailure,
66
type AtomCommandResult,
77
} from "@t3tools/client-runtime/state/runtime";
8-
import { MessageId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
8+
import {
9+
MessageId,
10+
ThreadId,
11+
type ModelSelection,
12+
type RuntimeMode,
13+
type ScopedThreadRef,
14+
} from "@t3tools/contracts";
915

1016
import * as Dialog from "../../components/ui/Dialog";
1117
import { uuidv4 } from "../../lib/uuid";
@@ -17,11 +23,13 @@ import { useOpenLinkedThread } from "./useOpenLinkedThread";
1723

1824
/**
1925
* 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.
26+
* it like any linked thread. Resolves false when the side chat did not start. `settings` are
27+
* what the parent's composer would send, which its thread gets only on its next send.
2128
*/
2229
export function useStartSideChat() {
2330
const forkSideChat = useAtomCommand(threadEnvironment.forkSideChat, { reportFailure: false });
2431
const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
32+
const setRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, { reportFailure: false });
2533
const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
2634
const openLinkedThread = useOpenLinkedThread();
2735

@@ -34,7 +42,11 @@ export function useStartSideChat() {
3442
Dialog.alert("Side chat not started", error instanceof Error ? error.message : fallback);
3543
};
3644

37-
return async (source: ScopedThreadRef, prompt: string): Promise<boolean> => {
45+
return async (
46+
source: ScopedThreadRef,
47+
prompt: string,
48+
settings: { readonly runtimeMode: RuntimeMode; readonly modelSelection: ModelSelection },
49+
): Promise<boolean> => {
3850
const targetThreadId = ThreadId.make(uuidv4());
3951
const fork = await forkSideChat({
4052
environmentId: source.environmentId,
@@ -70,6 +82,21 @@ export function useStartSideChat() {
7082
discard();
7183
return false;
7284
}
85+
if (settings.runtimeMode !== sideChat.runtimeMode) {
86+
const mode = await setRuntimeMode({
87+
environmentId: source.environmentId,
88+
input: {
89+
threadId: targetThreadId,
90+
runtimeMode: settings.runtimeMode,
91+
createdAt: new Date().toISOString(),
92+
},
93+
});
94+
if (mode._tag === "Failure") {
95+
alertFailure(mode, "Could not set the side chat's permission mode.");
96+
discard();
97+
return false;
98+
}
99+
}
73100
const turn = await startTurn({
74101
environmentId: source.environmentId,
75102
input: {
@@ -80,8 +107,9 @@ export function useStartSideChat() {
80107
text: prompt,
81108
attachments: [],
82109
},
110+
modelSelection: settings.modelSelection,
83111
titleSeed: deriveThreadTitleSeed({ text: prompt, attachments: [] }),
84-
runtimeMode: sideChat.runtimeMode,
112+
runtimeMode: settings.runtimeMode,
85113
interactionMode: "default",
86114
createdAt: new Date().toISOString(),
87115
},

‎apps/mobile/src/state/thread-task-permissions.test.ts‎

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
TurnItemId,
1111
type ModelSelection,
1212
type OrchestrationV2ThreadProjection,
13+
type RuntimeMode,
1314
type ServerConfig,
1415
} from "@t3tools/contracts";
1516
import {
@@ -30,6 +31,7 @@ const state = vi.hoisted(() => ({
3031
text: "Keep my draft",
3132
attachments: [] as DraftComposerImageAttachment[],
3233
modelSelection: undefined as ModelSelection | undefined,
34+
runtimeMode: undefined as RuntimeMode | undefined,
3335
},
3436
serverConfig: null as ServerConfig | null,
3537
projection: null as OrchestrationV2ThreadProjection | null,
@@ -185,6 +187,7 @@ vi.mock("../lib/commandMetadata", () => ({
185187
vi.mock("../lib/copyTextWithHaptic", () => ({ copyTextWithHaptic: vi.fn() }));
186188
vi.mock("./use-remote-environment-registry", () => ({ setPendingConnectionError: vi.fn() }));
187189

190+
import { Alert } from "react-native";
188191
import { useThreadComposerState } from "./use-thread-composer-state";
189192
import { useSelectedThreadRequests } from "./use-selected-thread-requests";
190193

@@ -193,7 +196,12 @@ const NO_SIDE_CHATS = { startSideChat: async () => false };
193196
beforeEach(() => {
194197
state.grantedEnvironments = new Set(["primary"]);
195198
state.connectionState = "connected";
196-
state.draft = { text: "Keep my draft", attachments: [], modelSelection: undefined };
199+
state.draft = {
200+
text: "Keep my draft",
201+
attachments: [],
202+
modelSelection: undefined,
203+
runtimeMode: undefined,
204+
};
197205
state.freshPending = false;
198206
state.compactDue = false;
199207
state.thread.latestRun = null;
@@ -345,14 +353,26 @@ describe("mobile task permissions", () => {
345353
...state.serverConfig,
346354
environment: { capabilities: { sideChats: true } },
347355
} as ServerConfig;
348-
state.draft = { ...state.draft, text: "/side why does this fail?" };
356+
// The thread gets the composer's mode and model only on its next send.
357+
const selection: ModelSelection = {
358+
instanceId: ProviderInstanceId.make("codex"),
359+
model: "gpt-5.4",
360+
options: [{ id: "reasoningEffort", value: "xhigh" }],
361+
};
362+
state.draft = {
363+
...state.draft,
364+
text: "/side why does this fail?",
365+
modelSelection: selection,
366+
runtimeMode: "approval-required",
367+
};
349368
const startSideChat = vi.fn(async () => true);
350369
const composer = useThreadComposerState({ startSideChat });
351370
expect(composer.sideChatUnavailableReason).toBeNull();
352371
expect(await composer.onSendMessage()).toBeNull();
353372
expect(startSideChat).toHaveBeenCalledExactlyOnceWith(
354373
{ environmentId: "secondary", threadId: "thread" },
355374
"why does this fail?",
375+
{ runtimeMode: "approval-required", modelSelection: selection },
356376
);
357377
expect(state.enqueue).not.toHaveBeenCalled();
358378
expect(state.clearDraft).toHaveBeenCalled();
@@ -370,6 +390,16 @@ describe("mobile task permissions", () => {
370390
expect(await useThreadComposerState({ startSideChat }).onSendMessage()).toBeNull();
371391
expect(startSideChat).toHaveBeenCalledOnce();
372392
expect(state.clearDraft).not.toHaveBeenCalled();
393+
// A model the send would refuse does not start a side chat either.
394+
vi.clearAllMocks();
395+
state.serverConfig = {
396+
...state.serverConfig,
397+
providers: [{ instanceId: "codex", driver: "codex", enabled: false }],
398+
} as unknown as ServerConfig;
399+
state.draft = { ...state.draft, attachments: [] };
400+
expect(await useThreadComposerState({ startSideChat }).onSendMessage()).toBeNull();
401+
expect(startSideChat).not.toHaveBeenCalled();
402+
expect(Alert.alert).toHaveBeenCalledOnce();
373403
});
374404

375405
it("rechecks a retained send callback before clearing or queueing the draft", async () => {

‎apps/mobile/src/state/use-thread-composer-state.ts‎

Lines changed: 27 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import {
2727
type EnvironmentId,
2828
type ModelSelection,
2929
type ProviderInteractionMode,
30+
type RuntimeMode,
3031
type ScopedThreadRef,
3132
type ServerProvider,
3233
type ThreadId,
@@ -197,7 +198,11 @@ export function updateThreadDraftModelSelection(
197198

198199
export function useThreadComposerState(input: {
199200
/** Forks the thread into a side chat that gets `prompt`; resolves false when it did not start. */
200-
readonly startSideChat: (source: ScopedThreadRef, prompt: string) => Promise<boolean>;
201+
readonly startSideChat: (
202+
source: ScopedThreadRef,
203+
prompt: string,
204+
settings: { readonly runtimeMode: RuntimeMode; readonly modelSelection: ModelSelection },
205+
) => Promise<boolean>;
201206
}) {
202207
const {
203208
selectedThread: selectedThreadShell,
@@ -564,6 +569,19 @@ export function useThreadComposerState(input: {
564569
if (text.length === 0 && attachments.length === 0) {
565570
return null;
566571
}
572+
const modelSelection = draft.modelSelection ?? thread.modelSelection;
573+
const serverConfig = selectedEnvironmentRuntime?.serverConfig;
574+
const modelUnavailable =
575+
selectedEnvironmentRuntime?.connectionState === "connected" &&
576+
isModelSelectionUnavailable(serverConfig, modelSelection, thread.projectId);
577+
const alertModelUnavailable = () => {
578+
const { title, detail } = describeUnavailableModelSelection(
579+
serverConfig,
580+
modelSelection,
581+
thread.projectId,
582+
);
583+
Dialog.alert(title, detail);
584+
};
567585
// A redirect's text answers its approval, so `/side` there is that text, not the command.
568586
const sideChatCommand = beforeDispatch === undefined ? parseSideChatCommand(text) : null;
569587
if (sideChatCommand) {
@@ -576,12 +594,18 @@ export function useThreadComposerState(input: {
576594
);
577595
} else if (sideChatCommand.prompt.length === 0) {
578596
Dialog.alert("Ask a side question", "Type the question after /side, then send it.");
597+
} else if (modelUnavailable) {
598+
alertModelUnavailable();
579599
} else if (!startingSideChatRef.current) {
580600
startingSideChatRef.current = true;
581601
const started = await input
582602
.startSideChat(
583603
{ environmentId: thread.environmentId, threadId: thread.id },
584604
sideChatCommand.prompt,
605+
{
606+
runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
607+
modelSelection,
608+
},
585609
)
586610
.finally(() => {
587611
startingSideChatRef.current = false;
@@ -627,18 +651,8 @@ export function useThreadComposerState(input: {
627651
return null;
628652
}
629653

630-
const modelSelection = draft.modelSelection ?? thread.modelSelection;
631-
const serverConfig = selectedEnvironmentRuntime?.serverConfig;
632-
if (
633-
selectedEnvironmentRuntime?.connectionState === "connected" &&
634-
isModelSelectionUnavailable(serverConfig, modelSelection, thread.projectId)
635-
) {
636-
const { title, detail } = describeUnavailableModelSelection(
637-
serverConfig,
638-
modelSelection,
639-
thread.projectId,
640-
);
641-
Dialog.alert(title, detail);
654+
if (modelUnavailable) {
655+
alertModelUnavailable();
642656
return null;
643657
}
644658
const provider = serverConfig?.providers.find(

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2794,6 +2794,10 @@ export default function ChatView(props: ChatViewProps) {
27942794
serverConfig?.environment.capabilities.sideChats === true;
27952795
const sideChat = useSideChat({
27962796
threadRef: sideChatsOffered && isServerThread ? activeThreadRef : null,
2797+
readSettings: () => ({
2798+
runtimeMode,
2799+
modelSelection: composerRef.current?.getSendContext().selectedModelSelection,
2800+
}),
27972801
onError: (message) => {
27982802
if (activeThread) setThreadError(activeThread.id, message);
27992803
},

‎apps/web/src/components/chat/useSideChat.ts‎

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { ScopedThreadRef } from "@t3tools/contracts";
1+
import type { ModelSelection, RuntimeMode, ScopedThreadRef } from "@t3tools/contracts";
22
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
33
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
44
import {
@@ -9,6 +9,7 @@ import {
99
import { useRef } from "react";
1010

1111
import { newMessageId, newThreadId } from "~/lib/utils";
12+
import { useComposerDraftStore } from "../../composerDraftStore";
1213
import { useStableCallback } from "../../hooks/useStableCallback";
1314
import { useRightPanelStore } from "../../rightPanelStore";
1415
import { readThreadShell, waitForThreadShell } from "../../state/entities";
@@ -18,16 +19,24 @@ import { useOrchestrationCommand } from "../../state/use-orchestration-command";
1819

1920
/**
2021
* Starts side chats from `threadRef`, or offers none when it is null. `open` forks the
21-
* thread's latest stable point, sends `prompt` there, and shows the side chat's tab. It
22-
* resolves false when the side chat did not start, or another one is still starting.
22+
* thread's latest stable point, sends `prompt` there with `readSettings()`, the parent
23+
* composer's settings, and shows the tab. It resolves false when the side chat did not
24+
* start, or another one is still starting.
2325
*/
2426
export function useSideChat(input: {
2527
readonly threadRef: ScopedThreadRef | null;
28+
readonly readSettings: () => {
29+
readonly runtimeMode: RuntimeMode;
30+
readonly modelSelection: ModelSelection | undefined;
31+
};
2632
readonly onError: (message: string) => void;
2733
}) {
2834
const pendingRef = useRef(false);
2935
const forkSideChat = useAtomCommand(threadEnvironment.forkSideChat, { reportFailure: false });
3036
const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
37+
const setThreadRuntimeMode = useOrchestrationCommand(threadEnvironment.setRuntimeMode, {
38+
reportFailure: false,
39+
});
3140
const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
3241
reportFailure: false,
3342
});
@@ -40,6 +49,7 @@ export function useSideChat(input: {
4049
input.onError(error instanceof Error ? error.message : fallback);
4150
};
4251
const start = async (threadRef: ScopedThreadRef, prompt: string | undefined) => {
52+
const { runtimeMode, modelSelection } = input.readSettings();
4353
const targetThreadId = newThreadId();
4454
const fork = await forkSideChat({
4555
environmentId: threadRef.environmentId,
@@ -67,6 +77,17 @@ export function useSideChat(input: {
6777
discard();
6878
return false;
6979
}
80+
if (runtimeMode !== sideChat.runtimeMode) {
81+
const mode = await setThreadRuntimeMode({
82+
environmentId: threadRef.environmentId,
83+
input: { threadId: targetThreadId, runtimeMode, createdAt: new Date().toISOString() },
84+
});
85+
if (mode._tag === "Failure") {
86+
reportFailure(mode, "Could not set the side chat's permission mode.");
87+
discard();
88+
return false;
89+
}
90+
}
7091
const text = prompt?.trim();
7192
// Send before showing the tab: closing a tab whose side chat has no run deletes it.
7293
if (text) {
@@ -75,8 +96,9 @@ export function useSideChat(input: {
7596
input: {
7697
threadId: targetThreadId,
7798
message: { messageId: newMessageId(), role: "user", text, attachments: [] },
99+
...(modelSelection === undefined ? {} : { modelSelection }),
78100
titleSeed: deriveThreadTitleSeed({ text, attachments: [] }),
79-
runtimeMode: sideChat.runtimeMode,
101+
runtimeMode,
80102
interactionMode: "default",
81103
createdAt: new Date().toISOString(),
82104
},
@@ -86,6 +108,8 @@ export function useSideChat(input: {
86108
discard();
87109
return false;
88110
}
111+
} else if (modelSelection !== undefined) {
112+
useComposerDraftStore.getState().setModelSelection(targetRef, modelSelection);
89113
}
90114
useRightPanelStore.getState().openSideChat(threadRef, targetThreadId);
91115
return true;

‎docs/user/thread-sidebar.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -304,9 +304,10 @@ You can also choose **Side chat** from the **+** menu in the right panel. The si
304304
chat opens as a tab there, with its own composer. Side chats do not show in the
305305
sidebar. Find one again under **Side chats** in thread details.
306306

307-
A side chat works in the same folder as the thread and inherits its permissions
308-
when created, including for its first reply. Change permissions for an individual
309-
side chat in its composer. Later changes to the parent do not change existing side chats.
307+
A side chat works in the same folder as the thread and starts with the permissions,
308+
model, and reasoning level shown in the thread's composer, including for its first
309+
reply. Change them for an individual side chat in its composer. Later changes to the
310+
parent do not change existing side chats.
310311

311312
To use what you learned, choose **Bring back**. The thread gets the side chat with
312313
your next message there. Bring back is available while the thread is idle.

0 commit comments

Comments
 (0)