Skip to content

Commit 8bd2d46

Browse files
Yuruzuuclaude
andcommitted
feat(web): ask about selected text in a side chat
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent ce9e016 commit 8bd2d46

8 files changed

Lines changed: 130 additions & 27 deletions

File tree

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

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ import { AsyncResult } from "effect/reactivity";
126126
import { isElectron } from "../env";
127127
import { useDiffPanelStore } from "../diffPanelStore";
128128
import { useActiveThreadRef } from "../hooks/useActiveThreadRef";
129-
import { composerRequiresModifier } from "../composer-logic";
129+
import { composerRequiresModifier, formatAssistantCitationForComposer } from "../composer-logic";
130130
import {
131131
derivePhase,
132132
deriveActiveWorkStartedAt,
@@ -2791,7 +2791,11 @@ export default function ChatView(props: ChatViewProps) {
27912791
? "Available once the thread's worktree is set up."
27922792
: null;
27932793
const openSideChatStable = useStableCallback(() => void sideChat.open());
2794-
const sendSideChatStable = useStableCallback((prompt: string) => sideChat.open(prompt));
2794+
const sendSideChatStable = useStableCallback((prompt: string) => sideChat.open({ prompt }));
2795+
const openCitationInSideChatStable = useStableCallback(
2796+
(citation: AssistantCitation) =>
2797+
void sideChat.open({ draft: formatAssistantCitationForComposer(citation) }),
2798+
);
27952799
const { onConfirmRevertStable, onForkFromRunStable, onRevertTimelineTurnStable } =
27962800
useTimelineRewind({
27972801
environmentId,
@@ -3400,6 +3404,11 @@ export default function ChatView(props: ChatViewProps) {
34003404
citationRequest={citationRequest}
34013405
citationHistory={citationHistory}
34023406
onCiteAssistantText={citeAssistantTextStable}
3407+
onOpenCitationInSideChat={
3408+
sideChat.available && sideChatDisabledReason === null
3409+
? openCitationInSideChatStable
3410+
: undefined
3411+
}
34033412
{...(activeProject
34043413
? { onRunShellCommand: parentPanel?.runShellCommand ?? runShellCommandStable }
34053414
: {})}

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

Lines changed: 39 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import {
44
type AssistantCitation,
55
type ScopedThreadRef,
66
} from "@t3tools/contracts";
7-
import { QuoteIcon } from "lucide-react";
7+
import { MessagesSquareIcon, QuoteIcon } from "lucide-react";
88
import { use, useEffect, useLayoutEffect, useRef, useState } from "react";
99
import { createPortal } from "react-dom";
1010
import {
@@ -18,23 +18,26 @@ import {
1818
type SelectionActionPoint,
1919
} from "~/lib/selectionActions";
2020
import { Button } from "../ui/button";
21+
import { ButtonGroup } from "../ui/group";
2122
import { BackgroundThreadContext } from "./backgroundThread";
2223

2324
export function AssistantSelectionToolbar({
2425
viewport,
2526
threadRef,
2627
onCite,
28+
onOpenInSideChat,
2729
}: {
2830
viewport: HTMLElement | null;
2931
threadRef: ScopedThreadRef;
3032
onCite: (citation: AssistantCitation, sourceAnchor: AssistantCitationSourceAnchor) => boolean;
33+
onOpenInSideChat: ((citation: AssistantCitation) => void) | undefined;
3134
}) {
3235
const [selection, setSelection] = useState<{
3336
citation: AssistantCitation;
3437
position: SelectionActionPoint;
3538
sourceAnchor: AssistantCitationSourceAnchor;
3639
} | null>(null);
37-
const toolbarRef = useRef<HTMLButtonElement>(null);
40+
const toolbarRef = useRef<HTMLDivElement>(null);
3841
const actionsRef = useRef<ReturnType<typeof observeSelectionActions> | null>(null);
3942
const backgroundThread = use(BackgroundThreadContext);
4043

@@ -160,10 +163,11 @@ export function AssistantSelectionToolbar({
160163
) {
161164
return;
162165
}
163-
if (toolbar.disabled) return;
166+
const firstAction = toolbar.querySelector<HTMLButtonElement>("button:not(:disabled)");
167+
if (!firstAction) return;
164168
event.preventDefault();
165169
event.stopPropagation();
166-
toolbar.focus({ preventScroll: true });
170+
firstAction.focus({ preventScroll: true });
167171
};
168172
// Tab belongs to the foreground chat; a background timeline only follows its selection.
169173
if (!backgroundThread) document.addEventListener("keydown", focusActions, true);
@@ -188,18 +192,18 @@ export function AssistantSelectionToolbar({
188192
dismiss();
189193
return true;
190194
};
195+
const openInSideChat = () => {
196+
onOpenInSideChat?.(selection.citation);
197+
window.getSelection()?.removeAllRanges();
198+
dismiss();
199+
};
191200
return createPortal(
192-
<Button
201+
<ButtonGroup
193202
ref={toolbarRef}
194-
type="button"
195-
size="xs"
196-
variant="glass"
197-
disabled={tooLong}
198-
aria-label={tooLong ? "Selection is too long to cite" : "Cite selection in composer"}
203+
aria-label="Selection actions"
199204
className="fixed z-50 max-w-[calc(100vw-1rem)]"
200205
style={{ left: selection.position.x, top: selection.position.y }}
201206
onPointerDown={(event) => event.preventDefault()}
202-
onClick={cite}
203207
onKeyDown={(event) => {
204208
event.stopPropagation();
205209
if (event.key === "Escape" && !event.nativeEvent.isComposing) {
@@ -208,9 +212,30 @@ export function AssistantSelectionToolbar({
208212
}
209213
}}
210214
>
211-
<QuoteIcon aria-hidden="true" className="size-3.5" />
212-
{tooLong ? "Shorten selection" : "Cite"}
213-
</Button>,
215+
<Button
216+
type="button"
217+
size="xs"
218+
variant="glass"
219+
disabled={tooLong}
220+
aria-label={tooLong ? "Selection is too long to cite" : "Cite selection in composer"}
221+
onClick={cite}
222+
>
223+
<QuoteIcon aria-hidden="true" className="size-3.5" />
224+
{tooLong ? "Shorten selection" : "Cite"}
225+
</Button>
226+
{onOpenInSideChat && !tooLong ? (
227+
<Button
228+
type="button"
229+
size="xs"
230+
variant="glass"
231+
aria-label="Ask about selection in a side chat"
232+
onClick={openInSideChat}
233+
>
234+
<MessagesSquareIcon aria-hidden="true" className="size-3.5" />
235+
Ask
236+
</Button>
237+
) : null}
238+
</ButtonGroup>,
214239
document.body,
215240
);
216241
}

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,7 @@ interface MessagesTimelineProps {
223223
citation: AssistantCitation,
224224
sourceAnchor: AssistantCitationSourceAnchor,
225225
) => boolean;
226+
onOpenCitationInSideChat?: ((citation: AssistantCitation) => void) | undefined;
226227
isWorking: boolean;
227228
runlessWorkActive?: boolean;
228229
activeTurnStartedAt?: string | null;
@@ -336,6 +337,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
336337
citationRequest = null,
337338
citationHistory = CITED_HISTORY_LOADING,
338339
onCiteAssistantText,
340+
onOpenCitationInSideChat,
339341
isWorking,
340342
runlessWorkActive = false,
341343
activeTurnStartedAt = null,
@@ -1315,6 +1317,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
13151317
viewport={timelineViewportElement}
13161318
threadRef={citationThreadRef}
13171319
onCite={onCiteAssistantText}
1320+
onOpenInSideChat={onOpenCitationInSideChat}
13181321
/>
13191322
) : null}
13201323
<LegendList<MessagesTimelineRow>

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
import { Trash2Icon, XIcon } from "lucide-react";
1515
import { useEffect, useState } from "react";
1616

17+
import { useComposerDraftStore } from "../../composerDraftStore";
1718
import { ComposerHandleContext } from "../../composerHandleContext";
1819
import { useClientSettings } from "../../hooks/useSettings";
1920
import type { SideChatParentPanel } from "../../lib/sideChatPane";
@@ -111,6 +112,7 @@ export default function SideChatPane(props: {
111112
});
112113
setDeleting(false);
113114
if (result._tag === "Success") {
115+
useComposerDraftStore.getState().clearDraftThread(threadRef);
114116
useRightPanelStore.getState().closeSurface(parentRef, `side-chat:${threadId}`);
115117
} else if (!isAtomCommandInterrupted(result)) {
116118
const error = squashAtomCommandFailure(result);
@@ -123,7 +125,7 @@ export default function SideChatPane(props: {
123125
};
124126

125127
return (
126-
<div data-side-chat-pane className="flex h-full min-h-0 flex-col">
128+
<div data-side-chat-pane={threadId} className="flex h-full min-h-0 flex-col">
127129
<div className="flex h-9 shrink-0 items-center gap-1 border-b border-border pr-1 pl-3">
128130
<span className="min-w-0 flex-1 truncate text-xs font-medium">
129131
{shell?.title ?? "Side chat"}

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

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,24 @@ import {
99
import { useRef } from "react";
1010

1111
import { newMessageId, newThreadId } from "~/lib/utils";
12+
import { requestWorkspaceFocus } from "~/lib/workspaceFocus";
13+
import { useComposerDraftStore } from "../../composerDraftStore";
1214
import { useStableCallback } from "../../hooks/useStableCallback";
1315
import { useRightPanelStore } from "../../rightPanelStore";
1416
import { waitForThreadShell } from "../../state/entities";
1517
import { threadEnvironment } from "../../state/threads";
1618
import { useAtomCommand } from "../../state/use-atom-command";
1719
import { useOrchestrationCommand } from "../../state/use-orchestration-command";
1820

21+
/** `prompt` is sent as the first message; `draft` waits in the side chat's composer. */
22+
interface SideChatSeed {
23+
readonly prompt?: string;
24+
readonly draft?: string;
25+
}
26+
1927
/**
2028
* 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
29+
* thread's latest stable point, applies the seed there, and shows the side chat's tab. It
2230
* resolves false when the side chat did not start, or another one is still starting.
2331
*/
2432
export function useSideChat(input: {
@@ -39,7 +47,7 @@ export function useSideChat(input: {
3947
const error = squashAtomCommandFailure(failure);
4048
input.onError(error instanceof Error ? error.message : fallback);
4149
};
42-
const start = async (threadRef: ScopedThreadRef, prompt: string | undefined) => {
50+
const start = async (threadRef: ScopedThreadRef, seed: SideChatSeed) => {
4351
const targetThreadId = newThreadId();
4452
const fork = await forkSideChat({
4553
environmentId: threadRef.environmentId,
@@ -60,7 +68,12 @@ export function useSideChat(input: {
6068
discard();
6169
return false;
6270
}
63-
const text = prompt?.trim();
71+
const text = seed.prompt?.trim();
72+
if (seed.draft) {
73+
useComposerDraftStore
74+
.getState()
75+
.setPrompt(scopeThreadRef(threadRef.environmentId, targetThreadId), seed.draft);
76+
}
6477
// Send before showing the tab: closing a tab whose side chat has no run deletes it.
6578
if (text) {
6679
// The server asks before edits on a side chat's first turn whatever mode is sent.
@@ -82,13 +95,19 @@ export function useSideChat(input: {
8295
}
8396
}
8497
useRightPanelStore.getState().openSideChat(threadRef, targetThreadId);
98+
if (seed.draft) {
99+
requestWorkspaceFocus({
100+
area: "panel",
101+
selector: `[data-side-chat-pane="${targetThreadId}"] [data-testid="composer-editor"]`,
102+
});
103+
}
85104
return true;
86105
};
87-
const open = async (prompt?: string) => {
106+
const open = async (seed: SideChatSeed = {}) => {
88107
const { threadRef } = input;
89108
if (!threadRef || pendingRef.current) return false;
90109
pendingRef.current = true;
91-
return start(threadRef, prompt).finally(() => {
110+
return start(threadRef, seed).finally(() => {
92111
pendingRef.current = false;
93112
});
94113
};

‎apps/web/src/hooks/useRightPanelSurfaceClose.browser.test.tsx‎

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ const fixture = vi.hoisted(() => ({
1111
allowed: new Set<string>(),
1212
sessions: new Map<string, string>(),
1313
failClose: false,
14+
sideChatShell: null as { latestRun: { runId: string } | null } | null,
15+
clearedDrafts: [] as ScopedThreadRef[],
1416
}));
1517
vi.mock("../lib/terminalCloseConfirm", () => ({
1618
confirmTerminalClose: (labels: readonly string[]) => fixture.confirm(labels),
@@ -31,13 +33,17 @@ vi.mock("../state/session", () => ({
3133
vi.mock("../state/entities", () => ({
3234
useQuietThreadShell: () => null,
3335
useProject: () => null,
34-
readThreadShell: () => null,
36+
readThreadShell: () => fixture.sideChatShell,
3537
}));
3638
vi.mock("../state/terminalSessions", () => ({ useKnownTerminalSessions: () => null }));
3739
vi.mock("../composerDraftStore", async () => {
3840
const Schema = await import("effect/Schema");
3941
return {
40-
useComposerDraftStore: () => null,
42+
useComposerDraftStore: Object.assign(() => null, {
43+
getState: () => ({
44+
clearDraftThread: (ref: ScopedThreadRef) => fixture.clearedDrafts.push(ref),
45+
}),
46+
}),
4147
DraftId: Schema.String.pipe(Schema.brand("DraftId")),
4248
};
4349
});
@@ -59,6 +65,7 @@ vi.mock("../state/terminal", () => ({ terminalEnvironment: { open: {}, close: {}
5965
vi.mock("../state/preview", () => ({ previewEnvironment: { close: {} } }));
6066
vi.mock("../state/threads", () => ({ threadEnvironment: { delete: {} } }));
6167
vi.mock("../state/shell", () => ({ environmentShell: { stateValueAtom: () => null } }));
68+
vi.mock("../rpc/atomRegistry", () => ({ appAtomRegistry: { get: () => ({ status: "live" }) } }));
6269
vi.mock("@t3tools/client-runtime/state/runtime", () => ({
6370
isAtomCommandInterrupted: () => false,
6471
}));
@@ -67,6 +74,8 @@ function setup() {
6774
fixture.allowed = new Set(["environment-a", "environment-b"]);
6875
fixture.sessions = new Map();
6976
fixture.failClose = false;
77+
fixture.sideChatShell = null;
78+
fixture.clearedDrafts = [];
7079
useRightPanelStore.setState({ byThreadKey: {} });
7180
useTerminalUiStateStore.setState({ terminalUiStateByThreadKey: {} });
7281
const original: ScopedThreadRef = {
@@ -135,3 +144,32 @@ it.each(["cancel", "revoked"])(
135144
).toHaveLength(1);
136145
},
137146
);
147+
148+
it.each([
149+
{ latestRun: null, cleared: true },
150+
{ latestRun: { runId: "run-1" }, cleared: false },
151+
])(
152+
"clears a closed side chat's draft only when it never ran, cleared=$cleared",
153+
async ({ latestRun, cleared }) => {
154+
const { original } = setup();
155+
fixture.sideChatShell = { latestRun };
156+
const sideChatId = ThreadId.make("side-chat-a");
157+
useRightPanelStore.getState().openSideChat(original, sideChatId);
158+
const surface = selectThreadRightPanelState(
159+
useRightPanelStore.getState().byThreadKey,
160+
original,
161+
).surfaces.find((entry) => entry.kind === "side-chat")!;
162+
function SideChatHarness() {
163+
const { closeSurface } = useRightPanelSurfaceClose({
164+
threadRef: original,
165+
terminalLabelsById: new Map(),
166+
});
167+
return <button onClick={() => closeSurface(surface)}>Close side chat</button>;
168+
}
169+
await using screen = await render(<SideChatHarness />);
170+
await screen.getByRole("button").click();
171+
expect(fixture.clearedDrafts).toEqual(
172+
cleared ? [{ environmentId: original.environmentId, threadId: sideChatId }] : [],
173+
);
174+
},
175+
);

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
99
import { agentControlledBrowserCloseConfirmation } from "../components/ChatView.logic";
1010
import { closePreviewSession } from "../components/preview/closePreviewSession";
1111
import { useThreadTerminalActions } from "../components/terminal/useThreadTerminalActions";
12+
import { useComposerDraftStore } from "../composerDraftStore";
1213
import { confirmTerminalClose } from "../lib/terminalCloseConfirm";
1314
import { focusPanelTerminalAfterClose } from "../lib/terminalFocus";
1415
import { readLocalApi } from "../localApi";
@@ -79,6 +80,10 @@ export function useRightPanelSurfaceClose(input: {
7980
readThreadShell(scopeThreadRef(ref.environmentId, surface.threadId)) === null
8081
)
8182
) {
83+
const sideChatRef = scopeThreadRef(ref.environmentId, surface.threadId);
84+
if (readThreadShell(sideChatRef)?.latestRun === null) {
85+
useComposerDraftStore.getState().clearDraftThread(sideChatRef);
86+
}
8287
// The server keeps a side chat with a run or message. Reopen skips one it deleted.
8388
void deleteThread({
8489
environmentId: ref.environmentId,

‎docs/user/thread-sidebar.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -291,9 +291,11 @@ A side chat lets you ask a question about a thread without adding to it. It star
291291
with what the thread knows, and the thread keeps working while you ask.
292292

293293
On web and desktop, start a message with `/side` or `/btw`, then your question.
294-
You can also choose **Side chat** from the **+** menu in the right panel. The side
295-
chat opens as a tab there, with its own composer. Side chats do not show in the
296-
sidebar. Find one again under **Side chats** in thread details.
294+
You can also choose **Side chat** from the **+** menu in the right panel, or select
295+
text in an assistant response and choose **Ask** to start one with that text cited
296+
in its composer. The side chat opens as a tab there, with its own composer. Side
297+
chats do not show in the sidebar. Find one again under **Side chats** in thread
298+
details.
297299

298300
A side chat works in the same folder as the thread. Its first reply asks before it
299301
edits files or runs commands. After that, it uses the permission mode you choose

0 commit comments

Comments
 (0)