Skip to content

Commit 7e5cac0

Browse files
PR Batch Testerclaude
andcommitted
fix: side chat permissions, discard race, panel routing and focus
From a deep review of the PR: - Allow edits clears the side chat composer's own permission pick, and the switch shows the mode the next send will use. - Closing an empty side chat asks the server to delete it only while it is still empty (thread.delete expectedEmpty), so a question that already landed is never thrown away. - Side chat actions read the parent projection at call time, so streaming no longer replaces the timeline's shared callbacks. - Expanding older side chats no longer drops thread details to compact mode. - Files, mentions and attachments a mounted side chat opens show in the parent's panel, through one redirect in the panel store. - Only the host thread takes SnapShot and window-focus refocus. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent a1e79a5 commit 7e5cac0

11 files changed

Lines changed: 152 additions & 33 deletions

File tree

‎apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -707,6 +707,15 @@ it.effect("links a side chat under its parent without claiming a fork, and promo
707707
);
708708
// An unknown parent is a rejected command, not a projection failure.
709709
assert.equal(missingParent._tag, "OrchestratorDispatchError");
710+
711+
// "Discard if empty" deletes an empty side chat.
712+
yield* orchestrator.dispatch({
713+
type: "thread.delete",
714+
commandId: CommandId.make("discard-empty-side-chat"),
715+
threadId: sideChatId,
716+
expectedEmpty: true,
717+
});
718+
assert.isNotNull((yield* projections.getThread(sideChatId)).deletedAt);
710719
}).pipe(Effect.provide(layerTest)),
711720
);
712721

@@ -798,5 +807,17 @@ it.effect("forks a side chat from the last finished run while the source is mid-
798807
}),
799808
);
800809
assert.equal(midRun._tag, "Failure");
810+
811+
// "Discard if empty" never deletes a thread that already has runs.
812+
const notEmpty = yield* Effect.flip(
813+
orchestrator.dispatch({
814+
type: "thread.delete",
815+
commandId: CommandId.make("discard-non-empty-thread"),
816+
threadId: sourceId,
817+
expectedEmpty: true,
818+
}),
819+
);
820+
assert.equal(notEmpty._tag, "OrchestratorDispatchError");
821+
assert.isNull((yield* projections.getThread(sourceId)).deletedAt);
801822
}).pipe(Effect.provide(layerTest)),
802823
);

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10674,6 +10674,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1067410674
(cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
1067510675
),
1067610676
);
10677+
// Decided under the thread's command lock, so a message that already
10678+
// landed always wins over "discard if empty".
10679+
if (command.expectedEmpty === true) {
10680+
const messageCount = yield* projectionStore
10681+
.getMessageCount(command.threadId)
10682+
.pipe(mapDispatchError(command));
10683+
if (messageCount > 0 || projection.runs.length > 0) {
10684+
return yield* new OrchestratorDispatchError({
10685+
commandId: command.commandId,
10686+
commandType: command.type,
10687+
cause: `Thread ${command.threadId} is no longer empty.`,
10688+
});
10689+
}
10690+
}
1067710691
return yield* mapDispatchError(command)(
1067810692
planThreadDeletion({
1067910693
command,

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

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,7 @@ import {
255255
selectThreadPanelOpen,
256256
selectThreadRightPanelState,
257257
type RightPanelSurface,
258+
registerEmbeddedPanelHost,
258259
useRightPanelStore,
259260
} from "../rightPanelStore";
260261
import {
@@ -866,8 +867,6 @@ type ChatViewProps =
866867
* terminals or global shortcuts of its own, and no nested side chats.
867868
*/
868869
embedded?: boolean;
869-
/** The host thread whose right panel shows what an embedded side chat opens. */
870-
panelOwnerRef?: ScopedThreadRef;
871870
}
872871
| {
873872
environmentId: EnvironmentId;
@@ -878,7 +877,6 @@ type ChatViewProps =
878877
routeKind: "draft";
879878
draftId: DraftId;
880879
embedded?: never;
881-
panelOwnerRef?: never;
882880
};
883881

884882
interface TerminalLaunchContext {
@@ -1615,7 +1613,6 @@ export default function ChatView(props: ChatViewProps) {
16151613
reserveTitleBarControlInset = true,
16161614
forceExpandedMobileComposer = false,
16171615
embedded = false,
1618-
panelOwnerRef,
16191616
} = props;
16201617
const canOperateThread = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
16211618
const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope);
@@ -3821,14 +3818,12 @@ export default function ChatView(props: ChatViewProps) {
38213818
);
38223819
const openFileAttachment = useCallback(
38233820
(attachment: ChatFileAttachment) => {
3824-
// A side chat has no panel of its own; its attachments open in the host's.
3825-
const panelRef = panelOwnerRef ?? activeThreadRef;
3826-
if (panelRef) {
3827-
useRightPanelStore.getState().openAttachment(panelRef, attachment);
3821+
if (activeThreadRef) {
3822+
useRightPanelStore.getState().openAttachment(activeThreadRef, attachment);
38283823
return;
38293824
}
38303825
},
3831-
[activeThreadRef, panelOwnerRef],
3826+
[activeThreadRef],
38323827
);
38333828
const serverAttachmentResources = useMemo(
38343829
() =>
@@ -4661,7 +4656,12 @@ export default function ChatView(props: ChatViewProps) {
46614656
);
46624657
}
46634658
}, [activeThread, environmentId, interruptThreadTurn, setThreadError]);
4664-
useEffect(() => subscribeSnapShotComposerFocus(focusComposer), [focusComposer]);
4659+
// SnapShot captures land in the route thread's draft, so a side chat never
4660+
// takes the focus that follows one.
4661+
useEffect(
4662+
() => (embedded ? undefined : subscribeSnapShotComposerFocus(focusComposer)),
4663+
[embedded, focusComposer],
4664+
);
46654665
const scheduleComposerFocus = useCallback(() => {
46664666
window.requestAnimationFrame(() => {
46674667
focusComposer();
@@ -6935,7 +6935,8 @@ export default function ChatView(props: ChatViewProps) {
69356935
// terminal is a surface and is recognized by the predicate instead. Mobile is left alone so
69366936
// returning to the app does not raise the keyboard.
69376937
useEffect(() => {
6938-
if (!activeThread?.id || terminalUiState.terminalOpen || isMobileViewport) return;
6938+
// The host thread owns refocus; two composers would race for it.
6939+
if (embedded || !activeThread?.id || terminalUiState.terminalOpen || isMobileViewport) return;
69396940
let frame: number | null = null;
69406941
const onWindowFocus = () => {
69416942
if (frame !== null) window.cancelAnimationFrame(frame);
@@ -6956,7 +6957,7 @@ export default function ChatView(props: ChatViewProps) {
69566957
window.removeEventListener("focus", onWindowFocus);
69576958
if (frame !== null) window.cancelAnimationFrame(frame);
69586959
};
6959-
}, [activeThread?.id, focusComposer, isMobileViewport, terminalUiState.terminalOpen]);
6960+
}, [activeThread?.id, embedded, focusComposer, isMobileViewport, terminalUiState.terminalOpen]);
69606961

69616962
useEffect(() => {
69626963
if (!activeThread?.id) return;
@@ -12350,12 +12351,16 @@ function SideChatPanel(props: { parentRef: ScopedThreadRef; threadId: ThreadId }
1235012351
useRightPanelStore.getState().closeSurface(props.parentRef, `aside:${props.threadId}`);
1235112352
}
1235212353
}, [gone, props.parentRef, props.threadId]);
12354+
// Files and attachments this side chat opens show in the parent's panel.
12355+
useEffect(
12356+
() => registerEmbeddedPanelHost(childRef, props.parentRef),
12357+
[childRef, props.parentRef],
12358+
);
1235312359
if (shell === null || gone) return null;
1235412360
return (
1235512361
<ComposerHandleContext value={composerRef}>
1235612362
<ChatView
1235712363
embedded
12358-
panelOwnerRef={props.parentRef}
1235912364
routeKind="server"
1236012365
environmentId={props.parentRef.environmentId}
1236112366
threadId={props.threadId}

‎apps/web/src/components/chat/SideChatHeader.tsx‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { useNavigate } from "@tanstack/react-router";
88
import { ArrowUpFromLineIcon, MoreHorizontalIcon, PenLineIcon, Trash2Icon } from "lucide-react";
99
import { useState } from "react";
1010

11+
import { useComposerDraftStore } from "../../composerDraftStore";
1112
import { useSideChatActions } from "../../hooks/useSideChatActions";
1213
import { useThreadProjection, useThreadShell } from "../../state/entities";
1314
import { buildThreadRouteParams } from "../../threadRoutes";
@@ -32,9 +33,14 @@ export function SideChatHeader(props: { environmentId: EnvironmentId; threadId:
3233
const parentProjection = useThreadProjection(parentRef)?.projection ?? null;
3334
const actions = useSideChatActions(parentRef);
3435
const [busy, setBusy] = useState(false);
36+
// The composer's own permission pick is what the next send uses, so the
37+
// switch reflects it before falling back to the thread's mode.
38+
const composerRuntimeMode = useComposerDraftStore(
39+
(store) => store.getComposerDraft(childRef)?.runtimeMode ?? null,
40+
);
3541

3642
if (shell === null) return null;
37-
const allowEdits = shell.runtimeMode !== "approval-required";
43+
const allowEdits = (composerRuntimeMode ?? shell.runtimeMode) !== "approval-required";
3844
const mergeRun = childProjection === null ? null : resolveLatestMergeBackRun(childProjection);
3945
const canBringBack = shell.lineage.relationshipToParent === "fork" && mergeRun !== null;
4046
const bringBackReason =

‎apps/web/src/components/chat/SideChatsSection.tsx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,11 @@ export function SideChatsSection(props: { environmentId: EnvironmentId; threadId
201201
Previous{!previousExpanded && ` (${previous.length})`}
202202
</CollapsibleSectionHeader>
203203
{previousExpanded ? (
204-
<ul aria-label="Previous side chats" className="m-0 list-none p-0">
204+
<ul
205+
aria-label="Previous side chats"
206+
className="m-0 list-none p-0"
207+
data-thread-details-unmeasured
208+
>
205209
{previous.map(renderRow)}
206210
</ul>
207211
) : null}

‎apps/web/src/components/chat/ThreadDetailsCard.tsx‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,10 +94,14 @@ export function ThreadDetailsCard({
9494
const measure = () => {
9595
const frame = element.closest<HTMLElement>("[data-thread-details-card]");
9696
const next = element.offsetHeight + (frame ? frame.offsetHeight - frame.clientHeight : 0);
97-
// Lineage scrolls as it expands. Counting it toward density would hide
98-
// the section and workspace controls when the user asks to see more rows.
99-
const lineage = element.querySelector<HTMLElement>("[data-thread-relationships-panel]");
100-
const fittingHeight = next - (lineage?.offsetHeight ?? 0);
97+
// Lineage and older side chats grow when expanded. Counting them toward
98+
// density would hide the section and workspace controls when the user
99+
// asks to see more rows.
100+
const expandable = element.querySelectorAll<HTMLElement>(
101+
"[data-thread-relationships-panel], [data-thread-details-unmeasured]",
102+
);
103+
const fittingHeight =
104+
next - Array.from(expandable).reduce((total, part) => total + part.offsetHeight, 0);
101105
setMeasurements((current) => {
102106
const heights = current.key === measurementKey ? current.heights : { full: 0, compact: 0 };
103107
const fullContentHeight =

‎apps/web/src/hooks/useSideChatActions.ts‎

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
} from "@t3tools/client-runtime/state/runtime";
66
import { resolveSideChatHistoryAvailability } from "@t3tools/client-runtime/state/thread-workflows";
77
import type { RunId, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
8-
import { useCallback } from "react";
8+
import { useCallback, useRef } from "react";
99

1010
import { useComposerDraftStore } from "../composerDraftStore";
1111
import { newMessageId, newThreadId } from "../lib/utils";
@@ -187,8 +187,13 @@ export function useSideChatActions(parentRef: ScopedThreadRef | null) {
187187
[createThread, forkFromRun, startTurn],
188188
);
189189

190+
// Read at call time: depending on the projection would replace `start` (and
191+
// the timeline callbacks built on it) on every streamed update.
192+
const projectionRef = useRef(projection);
193+
projectionRef.current = projection;
190194
const start = useCallback(
191195
async (input: StartSideChatInput): Promise<ScopedThreadRef | null> => {
196+
const projection = projectionRef.current;
192197
if (parentRef === null || projection === null || !supported) return null;
193198
const parentKey = scopedThreadKey(parentRef);
194199
// A second press while the first fork is in flight would create a second side chat.
@@ -200,7 +205,7 @@ export function useSideChatActions(parentRef: ScopedThreadRef | null) {
200205
startingSideChatFor.delete(parentKey);
201206
}
202207
},
203-
[parentRef, projection, startSideChat, supported],
208+
[parentRef, startSideChat, supported],
204209
);
205210

206211
const reopenLatest = useCallback((): boolean => {
@@ -241,9 +246,17 @@ export function useSideChatActions(parentRef: ScopedThreadRef | null) {
241246
runtimeMode: allow ? SIDE_CHAT_EDITABLE_RUNTIME_MODE : SIDE_CHAT_READ_ONLY_RUNTIME_MODE,
242247
},
243248
});
244-
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
245-
reportFailure("Could not change edit access", squashAtomCommandFailure(result));
249+
if (result._tag === "Failure") {
250+
if (!isAtomCommandInterrupted(result)) {
251+
reportFailure("Could not change edit access", squashAtomCommandFailure(result));
252+
}
253+
return;
246254
}
255+
// The composer's own permission pick outranks the thread's mode on the
256+
// next send, so drop it and let the switch decide.
257+
useComposerDraftStore
258+
.getState()
259+
.setRuntimeMode(scopeThreadRef(parentRef.environmentId, childThreadId), null);
247260
},
248261
[parentRef, setRuntimeMode],
249262
);
@@ -266,14 +279,17 @@ export function useSideChatActions(parentRef: ScopedThreadRef | null) {
266279
/** Closing a side chat that never got a message throws it away; otherwise it stays listed. */
267280
const close = useCallback(
268281
async (childThreadId: ThreadId) => {
269-
const shell = readSideChats().find((thread) => thread.id === childThreadId);
270-
if (shell !== undefined && isEmptySideChat(shell)) {
271-
await discard(childThreadId);
272-
return;
273-
}
274282
closeSurface(childThreadId);
283+
const shell = readSideChats().find((thread) => thread.id === childThreadId);
284+
if (parentRef === null || shell === undefined || !isEmptySideChat(shell)) return;
285+
// This client's copy can lag a question that already landed, so the
286+
// server deletes only if the thread is still empty. If not, it stays listed.
287+
await deleteThread({
288+
environmentId: parentRef.environmentId,
289+
input: { threadId: childThreadId, expectedEmpty: true },
290+
});
275291
},
276-
[closeSurface, discard, readSideChats],
292+
[closeSurface, deleteThread, parentRef, readSideChats],
277293
);
278294

279295
/** Clears the flag, so the thread joins the sidebar as an ordinary one. */

‎apps/web/src/rightPanelStore.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
migratePersistedRightPanelState,
88
pullRequestSurface,
99
pullRequestSurfaceId,
10+
registerEmbeddedPanelHost,
1011
selectActiveRightPanel,
1112
selectActiveRightPanelSurface,
1213
selectSelectedRightPanelSurface,
@@ -127,6 +128,22 @@ describe("rightPanelStore", () => {
127128
expect(useClosedViewStore.getState().entries).toHaveLength(1);
128129
});
129130

131+
it("opens a mounted side chat's files in its parent's panel, and its own once unmounted", () => {
132+
const store = useRightPanelStore.getState();
133+
const unregister = registerEmbeddedPanelHost(refB, refA);
134+
store.openFile(refB, "src/app.ts");
135+
const surfaceIds = (ref: typeof refA) =>
136+
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref).surfaces.map(
137+
(surface) => surface.id,
138+
);
139+
expect(surfaceIds(refA)).toEqual(["file:src/app.ts"]);
140+
expect(surfaceIds(refB)).toEqual([]);
141+
142+
unregister();
143+
store.openFile(refB, "src/other.ts");
144+
expect(surfaceIds(refB)).toEqual(["file:src/other.ts"]);
145+
});
146+
130147
it("keeps several side chats open as peer tabs and reloads only well-formed ones", () => {
131148
const store = useRightPanelStore.getState();
132149
store.openAside(refA, "side-1");

‎apps/web/src/rightPanelStore.ts‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,26 @@ const terminalSurface = (terminalId: string): RightPanelSurface => ({
266266
activeTerminalId: terminalId,
267267
});
268268

269+
// A side chat shown inside its parent's panel has no panel of its own, so files
270+
// and attachments it opens go to the parent while it is mounted there. Opened as
271+
// a full thread, it owns its panel again.
272+
const embeddedPanelHosts = new Map<string, ScopedThreadRef>();
273+
274+
export function registerEmbeddedPanelHost(
275+
childRef: ScopedThreadRef,
276+
hostRef: ScopedThreadRef,
277+
): () => void {
278+
const key = scopedThreadKey(childRef);
279+
embeddedPanelHosts.set(key, hostRef);
280+
return () => {
281+
if (embeddedPanelHosts.get(key) === hostRef) embeddedPanelHosts.delete(key);
282+
};
283+
}
284+
285+
function panelOwnerOf(ref: ScopedThreadRef): ScopedThreadRef {
286+
return embeddedPanelHosts.get(scopedThreadKey(ref)) ?? ref;
287+
}
288+
269289
const asideSurface = (threadId: string): RightPanelSurface => ({
270290
id: `aside:${threadId}`,
271291
kind: "aside",
@@ -723,7 +743,7 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
723743
),
724744
openFile: (ref, requestedPath, line) =>
725745
set((state) =>
726-
userAction(state, scopedThreadKey(ref), (current) => {
746+
userAction(state, scopedThreadKey(panelOwnerOf(ref)), (current) => {
727747
if (requestedPath === ".") {
728748
return upsertSurface(current, singletonSurface("files"));
729749
}
@@ -758,7 +778,7 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
758778
),
759779
openAttachment: (ref, attachment) =>
760780
set((state) =>
761-
userAction(state, scopedThreadKey(ref), (current) => {
781+
userAction(state, scopedThreadKey(panelOwnerOf(ref)), (current) => {
762782
const withoutStandaloneExplorer = current.surfaces.filter(
763783
(surface) => surface.kind !== "files",
764784
);

‎packages/client-runtime/src/operations/commands.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,10 @@ export interface ThreadCommandInput extends CommandMetadata {
8585
readonly threadId: ThreadId;
8686
}
8787

88-
export type DeleteThreadInput = ThreadCommandInput;
88+
export interface DeleteThreadInput extends ThreadCommandInput {
89+
/** Delete only while the thread has no message or run yet. */
90+
readonly expectedEmpty?: boolean;
91+
}
8992
export type ArchiveThreadInput = ThreadCommandInput;
9093
export type UnarchiveThreadInput = ThreadCommandInput;
9194
export type SettleThreadInput = ThreadCommandInput;
@@ -441,7 +444,14 @@ function simpleThreadCommand(
441444
export const deleteThread = Effect.fn("EnvironmentCommands.deleteThread")(function* (
442445
input: DeleteThreadInput,
443446
) {
444-
return yield* simpleThreadCommand("thread.delete", input);
447+
if (input.expectedEmpty !== true) return yield* simpleThreadCommand("thread.delete", input);
448+
const commandId = yield* allocateCommandId(input);
449+
return yield* dispatch({
450+
type: "thread.delete",
451+
commandId,
452+
threadId: input.threadId,
453+
expectedEmpty: true,
454+
});
445455
});
446456

447457
export const archiveThread = Effect.fn("EnvironmentCommands.archiveThread")(function* (

0 commit comments

Comments
 (0)