Skip to content

Commit 22c1ce8

Browse files
feat(web): cite assistant responses with inline citations
Select text in an assistant response and choose "Cite in composer" to insert an inline quote chip at the cursor, with an optional comment bubble anchored at the selected text. Chips carry the quote, its source IDs, and the comment through drafts, stashes, copy/paste, and sending. Clicking a chip navigates to the source response, smooth-scrolls it into view (loading older history when needed), and pulses a highlight on the exact quoted passage that holds briefly before fading. Provider dispatch expands citations into readable quote data for every adapter while persisted messages keep the clickable links; titles, branch names, and stash previews see plain text. Mobile renders sent quotes as blockquotes. The terminal and assistant selection menus share one release-triggered gesture observer. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 0947c30 commit 22c1ce8

49 files changed

Lines changed: 5967 additions & 328 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/mobile/src/features/threads/ThreadFeed.tsx‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import type {
1111
ThreadId,
1212
TurnId,
1313
} from "@t3tools/contracts";
14+
import { renderAssistantCitationsAsText } from "@t3tools/shared/assistantCitations";
1415
import {
1516
codexArtifactTemplatePresentationLabel,
1617
type CodexArtifactTemplate,
@@ -1390,7 +1391,7 @@ function renderFeedEntry(
13901391
if (entry.type === "message") {
13911392
const { message } = entry;
13921393
const isUser = message.role === "user";
1393-
const renderedText = message.text;
1394+
const renderedText = renderAssistantCitationsAsText(message.text);
13941395
const styles = isUser ? markdownStyles.user : markdownStyles.assistant;
13951396
const timestampLabel = formatMessageTime(isUser ? message.createdAt : message.updatedAt);
13961397
const attachments = message.attachments ?? [];
@@ -1432,7 +1433,7 @@ function renderFeedEntry(
14321433
>
14331434
{message.text.trim().length > 0 ? (
14341435
<UserMessageContent
1435-
text={message.text}
1436+
text={renderedText}
14361437
markdownStyles={styles}
14371438
reviewCommentColors={props.reviewCommentColors}
14381439
skills={props.skills}
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import {
2+
EnvironmentId,
3+
MessageId,
4+
ProjectId,
5+
ProviderInstanceId,
6+
ThreadId,
7+
} from "@t3tools/contracts";
8+
import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations";
9+
import { describe, expect, it, vi } from "vite-plus/test";
10+
11+
import {
12+
buildProjectThreadStartTurnInput,
13+
deriveThreadTitleFromPrompt,
14+
} from "./projectThreadStartTurn";
15+
16+
vi.mock("./composerImages", () => ({ toUploadChatImageAttachments: () => [] }));
17+
18+
describe("project thread title", () => {
19+
it("keeps ordinary titles and the empty-prompt fallback", () => {
20+
expect(deriveThreadTitleFromPrompt(" Fix\n the parser ")).toBe("Fix the parser");
21+
expect(deriveThreadTitleFromPrompt(" \n ")).toBe("New thread");
22+
});
23+
24+
it.each([
25+
{
26+
comment: undefined,
27+
title: "Keep `cache[key]` & <parser> shared. Retry!",
28+
},
29+
{
30+
comment: 'Why "shared"?',
31+
title: 'Keep `cache[key]` & <parser> shared. Retry! Comment: Why "shared"?',
32+
},
33+
])("uses readable titles and intact links with comment $comment", ({ comment, title }) => {
34+
const quoteText = "Keep `cache[key]` & <parser> shared.\n Retry!";
35+
const text = serializeAssistantCitation({
36+
version: 1,
37+
environmentId: EnvironmentId.make("source-environment"),
38+
threadId: ThreadId.make("source-thread"),
39+
messageId: MessageId.make("source-message"),
40+
text: quoteText,
41+
...(comment === undefined ? {} : { comment }),
42+
start: 0,
43+
end: quoteText.length,
44+
prefix: "",
45+
suffix: "",
46+
});
47+
const input = buildProjectThreadStartTurnInput({
48+
projectId: ProjectId.make("project"),
49+
projectCwd: "/workspace",
50+
threadId: "new-thread",
51+
commandId: "command",
52+
messageId: "message",
53+
createdAt: "2026-09-01T00:00:00Z",
54+
text,
55+
attachments: [],
56+
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" },
57+
runtimeMode: "full-access",
58+
interactionMode: "default",
59+
workspaceMode: "local",
60+
branch: null,
61+
worktreePath: null,
62+
startFromOrigin: false,
63+
worktreeBranchName: "unused",
64+
});
65+
66+
expect(input.titleSeed).toBe(title);
67+
expect(input.bootstrap.createThread.title).toBe(input.titleSeed);
68+
expect(input.message.text).toBe(text);
69+
});
70+
});

‎apps/mobile/src/lib/projectThreadStartTurn.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,13 @@ import {
77
type ProviderInteractionMode,
88
type RuntimeMode,
99
} from "@t3tools/contracts";
10+
import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";
1011

1112
import { toUploadChatImageAttachments, type DraftComposerAttachment } from "./composerImages";
1213
import type { UploadedMobileAttachment } from "./attachmentUpload";
1314

1415
export function deriveThreadTitleFromPrompt(value: string): string {
15-
const trimmed = value.trim();
16+
const trimmed = assistantCitationsToPlainText(value).trim();
1617
if (trimmed.length === 0) {
1718
return "New thread";
1819
}

‎apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts‎

Lines changed: 80 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,14 @@ import {
1515
ApprovalRequestId,
1616
CommandId,
1717
DEFAULT_PROVIDER_INTERACTION_MODE,
18+
EnvironmentId,
1819
EventId,
1920
MessageId,
2021
ProjectId,
2122
ThreadId,
2223
TurnId,
2324
} from "@t3tools/contracts";
25+
import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations";
2426
import * as Effect from "effect/Effect";
2527
import * as Deferred from "effect/Deferred";
2628
import * as Exit from "effect/Exit";
@@ -69,6 +71,19 @@ const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalReques
6971
const asMessageId = (value: string): MessageId => MessageId.make(value);
7072
const asTurnId = (value: string): TurnId => TurnId.make(value);
7173

74+
const assistantQuoteText = "Retain the reconnect backoff.";
75+
const assistantCitation = {
76+
version: 1 as const,
77+
environmentId: EnvironmentId.make("source-environment"),
78+
threadId: ThreadId.make("source-thread"),
79+
messageId: asMessageId("source-message"),
80+
text: assistantQuoteText,
81+
start: 0,
82+
end: assistantQuoteText.length,
83+
prefix: "",
84+
suffix: "",
85+
};
86+
7287
const deriveServerPathsSync = (baseDir: string, devUrl: URL | undefined) =>
7388
Effect.runSync(deriveServerPaths(baseDir, devUrl).pipe(Effect.provide(NodeServices.layer)));
7489

@@ -824,7 +839,13 @@ describe("ProviderCommandReactor", () => {
824839
it("pins the first user message when regeneration context is truncated", async () => {
825840
const harness = await createHarness();
826841
const now = "2026-01-01T00:00:00.000Z";
827-
const firstUserMessage = `Review subagent monitoring risks. ${"Opening context. ".repeat(200)}`;
842+
const quoteText = "界".repeat(1_000);
843+
const citation = serializeAssistantCitation({
844+
...assistantCitation,
845+
text: quoteText,
846+
end: quoteText.length,
847+
});
848+
const firstUserMessage = `Review subagent monitoring risks. ${citation} ${"Opening context. ".repeat(200)}`;
828849
const recentUserMessage = `LATEST FINDING: ${"implementation detail ".repeat(320)}`;
829850
harness.generateThreadTitle.mockReturnValue(
830851
Effect.succeed({ title: "Review subagent monitoring risks" }),
@@ -927,7 +948,8 @@ describe("ProviderCommandReactor", () => {
927948
throw new Error("Expected a title generation input");
928949
}
929950
const message = input.message;
930-
expect(message.startsWith("USER:\nReview subagent monitoring risks.")).toBe(true);
951+
expect(message.startsWith(`USER:\nReview subagent monitoring risks. ${quoteText} `)).toBe(true);
952+
expect(message).not.toContain("t3-citation://");
931953
expect(message).toContain("[First user message truncated]");
932954
expect(message).toContain("[Earlier content truncated]");
933955
expect(message).toContain("image.png");
@@ -936,6 +958,14 @@ describe("ProviderCommandReactor", () => {
936958
"opening-context-image",
937959
"recent-context-image",
938960
]);
961+
const readModel = await harness.readModel();
962+
expect(
963+
readModel.threads
964+
.find((entry) => entry.id === ThreadId.make("thread-1"))
965+
?.messages.find(
966+
(entry) => entry.id === asMessageId("user-message-before-long-title-regeneration"),
967+
)?.text,
968+
).toBe(firstUserMessage);
939969
});
940970

941971
it("clears title regeneration state left pending across reactor startup", async () => {
@@ -1439,13 +1469,14 @@ describe("ProviderCommandReactor", () => {
14391469
const harness = await createHarness();
14401470
const now = "2026-01-01T00:00:00.000Z";
14411471
const seededTitle = "Fix reconnect spinner on resume";
1472+
const prompt = `[effort:high]\\n\\nFix reconnect spinner on resume ${serializeAssistantCitation(assistantCitation)}`;
14421473
harness.generateThreadTitle.mockReturnValue(
14431474
Effect.succeed({
14441475
title: "Reconnect spinner resume bug",
14451476
}),
14461477
);
14471478

1448-
await Effect.runPromise(
1479+
await harness.runEffect(
14491480
harness.engine.dispatch({
14501481
type: "thread.meta.update",
14511482
commandId: CommandId.make("cmd-thread-title-formatted-seed"),
@@ -1454,15 +1485,27 @@ describe("ProviderCommandReactor", () => {
14541485
}),
14551486
);
14561487

1457-
await Effect.runPromise(
1488+
const titleUpdated = await harness.runEffect(
1489+
harness.engine.streamDomainEvents.pipe(
1490+
Stream.filter(
1491+
(event) =>
1492+
event.type === "thread.meta-updated" &&
1493+
event.payload.title === "Reconnect spinner resume bug",
1494+
),
1495+
Stream.take(1),
1496+
Stream.toPull,
1497+
Scope.provide(scope!),
1498+
),
1499+
);
1500+
await harness.runEffect(
14581501
harness.engine.dispatch({
14591502
type: "thread.turn.start",
14601503
commandId: CommandId.make("cmd-turn-start-title-formatted"),
14611504
threadId: ThreadId.make("thread-1"),
14621505
message: {
14631506
messageId: asMessageId("user-message-title-formatted"),
14641507
role: "user",
1465-
text: "[effort:high]\\n\\nFix reconnect spinner on resume",
1508+
text: prompt,
14661509
attachments: [],
14671510
},
14681511
titleSeed: seededTitle,
@@ -1472,25 +1515,34 @@ describe("ProviderCommandReactor", () => {
14721515
}),
14731516
);
14741517

1475-
await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1);
1476-
await waitFor(async () => {
1477-
const readModel = await harness.readModel();
1478-
return (
1479-
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
1480-
"Reconnect spinner resume bug"
1481-
);
1482-
});
1518+
await harness.runEffect(titleUpdated);
1519+
await harness.drain();
14831520

1521+
expect(harness.generateThreadTitle.mock.calls[0]?.[0].message).toBe(
1522+
`[effort:high]\\n\\nFix reconnect spinner on resume ${assistantQuoteText}`,
1523+
);
1524+
expect(harness.generateThreadTitle.mock.calls[0]?.[0].message).not.toContain("t3-citation://");
14841525
const readModel = await harness.readModel();
14851526
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
14861527
expect(thread?.title).toBe("Reconnect spinner resume bug");
1528+
expect(
1529+
thread?.messages.find((entry) => entry.id === asMessageId("user-message-title-formatted"))
1530+
?.text,
1531+
).toBe(prompt);
1532+
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({ input: prompt });
14871533
});
14881534

14891535
it("generates a worktree branch name for the first turn", async () => {
14901536
const harness = await createHarness();
14911537
const now = "2026-01-01T00:00:00.000Z";
1538+
const prompt = `Add a safer reconnect backoff. ${serializeAssistantCitation(assistantCitation)}`;
1539+
const statusRefreshed = await harness.runEffect(Deferred.make<void>());
1540+
const refreshStatus = harness.refreshStatus.getMockImplementation()!;
1541+
harness.refreshStatus.mockImplementation((cwd) =>
1542+
refreshStatus(cwd).pipe(Effect.tap(() => Deferred.succeed(statusRefreshed, undefined))),
1543+
);
14921544

1493-
await Effect.runPromise(
1545+
await harness.runEffect(
14941546
harness.engine.dispatch({
14951547
type: "thread.meta.update",
14961548
commandId: CommandId.make("cmd-thread-branch"),
@@ -1515,15 +1567,15 @@ describe("ProviderCommandReactor", () => {
15151567
}),
15161568
);
15171569

1518-
await Effect.runPromise(
1570+
await harness.runEffect(
15191571
harness.engine.dispatch({
15201572
type: "thread.turn.start",
15211573
commandId: CommandId.make("cmd-turn-start-branch-model"),
15221574
threadId: ThreadId.make("thread-1"),
15231575
message: {
15241576
messageId: asMessageId("user-message-branch-model"),
15251577
role: "user",
1526-
text: "Add a safer reconnect backoff.",
1578+
text: prompt,
15271579
attachments: [],
15281580
},
15291581
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -1532,12 +1584,19 @@ describe("ProviderCommandReactor", () => {
15321584
}),
15331585
);
15341586

1535-
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
1536-
await waitFor(() => harness.refreshStatus.mock.calls.length === 1);
1537-
expect(harness.generateBranchName.mock.calls[0]?.[0]).toMatchObject({
1538-
message: "Add a safer reconnect backoff.",
1539-
});
1587+
await harness.runEffect(Deferred.await(statusRefreshed));
1588+
await harness.drain();
1589+
expect(harness.generateBranchName.mock.calls[0]?.[0].message).toBe(
1590+
`Add a safer reconnect backoff. ${assistantQuoteText}`,
1591+
);
1592+
expect(harness.generateBranchName.mock.calls[0]?.[0].message).not.toContain("t3-citation://");
15401593
expect(harness.refreshStatus.mock.calls[0]?.[0]).toBe("/tmp/provider-project-worktree");
1594+
const readModel = await harness.readModel();
1595+
expect(
1596+
readModel.threads
1597+
.find((entry) => entry.id === ThreadId.make("thread-1"))
1598+
?.messages.find((entry) => entry.id === asMessageId("user-message-branch-model"))?.text,
1599+
).toBe(prompt);
15411600
});
15421601

15431602
it("recreates a missing worktree from the thread branch before starting a turn", async () => {

‎apps/server/src/orchestration/Layers/ProviderCommandReactor.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
type RuntimeMode,
1313
type TurnId,
1414
} from "@t3tools/contracts";
15+
import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";
1516
import { isTemporaryWorktreeBranch, WORKTREE_BRANCH_PREFIX } from "@t3tools/shared/git";
1617
import * as Cache from "effect/Cache";
1718
import * as Cause from "effect/Cause";
@@ -110,7 +111,7 @@ function formatThreadTitleSection(message: ThreadTitleMessage): string | undefin
110111
if (message.role === "system") {
111112
return undefined;
112113
}
113-
const text = message.text.trim();
114+
const text = assistantCitationsToPlainText(message.text).trim();
114115
const attachmentSummary = (message.attachments ?? [])
115116
.map((attachment) => attachment.name)
116117
.join(", ");
@@ -1153,7 +1154,7 @@ const make = Effect.gen(function* () {
11531154
projects: project ? [project] : [],
11541155
}) ?? process.cwd();
11551156
const generationInput = {
1156-
messageText: message.text,
1157+
messageText: assistantCitationsToPlainText(message.text),
11571158
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
11581159
...(event.payload.titleSeed !== undefined ? { titleSeed: event.payload.titleSeed } : {}),
11591160
};

0 commit comments

Comments
 (0)