Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions apps/web/src/components/chat/ChatComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,9 @@ import {
import { CollapsedComposerStopAction, ComposerPrimaryActions } from "./ComposerPrimaryActions";
import { ComposerFooterPrimaryActions } from "./ComposerFooterControls";
import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
import { questionReplyInsertion } from "../../questionReply";
import { appAtomRegistry } from "../../rpc/atomRegistry";
import { environmentThreadDetails } from "../../state/threads";
import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
import { buildPullRequestReferenceContext } from "../pullRequest/pullRequestDetail.logic";
import { getComposerPromptInjectionState, getComposerReasoningStep } from "./composerProviderState";
Expand Down Expand Up @@ -3340,6 +3343,25 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
onRemoveFile={removeComposerFileFromDraft}
/>
) : null;
const replyToQuestion = (question: string) => {
const threadId = activeThreadId ?? routeThreadRef.threadId;
const detail = appAtomRegistry.get(
environmentThreadDetails.threadAtom({ environmentId, threadId }),
);
const snapshot = readComposerSnapshotStable();
const fragment = questionReplyInsertion({
question,
answer: snapshot.value,
cursor: snapshot.expandedCursor,
messages: detail?.projection.messages ?? [],
environmentId,
threadId,
});
if (!fragment) return;
const inserted = insertComposerTextStable(fragment, "cursor");
if (inserted && isComposerCollapsedMobile) expandMobileComposerStable();
};
const replyToQuestionStable = useStableCallback(replyToQuestion);
const composerAttachButton = showComposerAttachAction ? (
<ComposerAttachButton
addComposerAttachments={addComposerAttachments}
Expand Down Expand Up @@ -3421,6 +3443,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
onToggleOption={onSelectActivePendingUserInputOption}
onAdvance={onAdvanceActivePendingUserInput}
onDismiss={onDismissActivePendingUserInput}
onReplyToQuestion={replyToQuestionStable}
/>
) : null}
</ComposerBanner.Root>
Expand Down
30 changes: 30 additions & 0 deletions apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { type RuntimeRequestId, type ScopedThreadRef } from "@t3tools/contracts";
import { ReplyIcon } from "lucide-react";
import { markdownProseDirection, textDirection } from "~/textDirection";
import { memo, use, useEffect, useEffectEvent, useRef, useState } from "react";
import { REPLY_TO_QUESTION_LABEL, showReplyToQuestion } from "../../questionReply";
import { BackgroundThreadContext } from "./backgroundThread";
import { useStableCallback } from "~/hooks/useStableCallback";
import { type PendingUserInput } from "../../session-logic";
Expand All @@ -25,6 +27,7 @@ interface PendingUserInputPanelProps {
onToggleOption: (questionId: string, optionValue: string) => void;
onAdvance: () => void;
onDismiss: (requestId: RuntimeRequestId) => void;
onReplyToQuestion?: (question: string) => void;
}

export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPanel({
Expand All @@ -38,6 +41,7 @@ export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserIn
onToggleOption,
onAdvance,
onDismiss,
onReplyToQuestion,
}: PendingUserInputPanelProps) {
if (pendingUserInputs.length === 0) return null;
const activePrompt = pendingUserInputs[0];
Expand All @@ -56,6 +60,7 @@ export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserIn
onToggleOption={onToggleOption}
onAdvance={onAdvance}
onDismiss={onDismiss}
onReplyToQuestion={onReplyToQuestion}
/>
);
});
Expand All @@ -71,6 +76,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
onToggleOption,
onAdvance,
onDismiss,
onReplyToQuestion,
}: {
prompt: PendingUserInput;
cwd: string | undefined;
Expand All @@ -82,6 +88,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
onToggleOption: (questionId: string, optionValue: string) => void;
onAdvance: () => void;
onDismiss: (requestId: RuntimeRequestId) => void;
onReplyToQuestion?: ((question: string) => void) | undefined;
}) {
// Message-mode requests remain answerable after their provider turn ends.
const canRespond = prompt.responseCapability !== "not_resumable";
Expand Down Expand Up @@ -235,6 +242,29 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
</ComposerBanner.Count>
) : null}
<ComposerBanner.ToggleIcon expanded={!isCollapsed} />
{showReplyToQuestion(activeQuestion) ? (
<ComposerBanner.Dismiss
render={<span role="button" tabIndex={responseDisabled ? -1 : 0} />}
aria-label={REPLY_TO_QUESTION_LABEL}
title={REPLY_TO_QUESTION_LABEL}
disabled={responseDisabled}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
if (responseDisabled) return;
onReplyToQuestion?.(activeQuestion.question);
}}
onKeyDown={(event) => {
if (event.key !== "Enter" && event.key !== " ") return;
event.preventDefault();
event.stopPropagation();
if (responseDisabled) return;
onReplyToQuestion?.(activeQuestion.question);
}}
>
<ReplyIcon className="size-3.5" />
</ComposerBanner.Dismiss>
) : null}
{prompt.dismissible ? (
<ComposerBanner.Dismiss
render={<span role="button" tabIndex={0} />}
Expand Down
20 changes: 12 additions & 8 deletions apps/web/src/pendingUserInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {
ThreadContextRecord,
UserInputQuestion,
} from "@t3tools/contracts";
import { expandAssistantCitationsForProvider } from "@t3tools/shared/assistantCitations";
import {
projectComposerContextForProvider,
replaceComposerContextReferences,
Expand Down Expand Up @@ -54,15 +55,18 @@ export function projectPendingUserInputAnswer(
answer: unknown,
records: ReadonlyArray<AnswerContextRecord>,
) {
if (typeof answer !== "string" || records.length === 0) return answer;
if (typeof answer !== "string") return answer;
if (records.length === 0) return expandAssistantCitationsForProvider(answer);
const recordsById = new Map(records.map((record) => [record.contextId, record]));
return replaceComposerContextReferences(answer, (reference) => {
const record = recordsById.get(reference.contextId);
if (record?.kind !== reference.kind) return reference.source;
return record.kind === "thread"
? formatThreadLink(record, reference.label)
: projectComposerContextForProvider({ text: reference.source, records: [record] });
});
return expandAssistantCitationsForProvider(
replaceComposerContextReferences(answer, (reference) => {
const record = recordsById.get(reference.contextId);
if (record?.kind !== reference.kind) return reference.source;
return record.kind === "thread"
? formatThreadLink(record, reference.label)
: projectComposerContextForProvider({ text: reference.source, records: [record] });
}),
);
}

// Question drafts retain deleted chip records for undo; only transfer referenced records.
Expand Down
121 changes: 121 additions & 0 deletions apps/web/src/questionReply.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
import {
collectAssistantCitations,
expandAssistantCitationsForProvider,
parseAssistantCitationHref,
} from "@t3tools/shared/assistantCitations";
import { describe, expect, it } from "vite-plus/test";

import { projectPendingUserInputAnswer } from "./pendingUserInput";
import {
questionReplyInsertion,
REPLY_TO_QUESTION_LABEL,
showReplyToQuestion,
} from "./questionReply";

const environmentId = EnvironmentId.make("env-question");
const threadId = ThreadId.make("thread-question");
const assistantMessageId = MessageId.make("assistant-question");
const founderMessageId = MessageId.make("founder-question");
const question = "Which database should we use?";
const legacyHref =
"t3-citation://v1/a/b/c?text=A+quote+%26+a+newline.%0A&start=0&end=21&prefix=&suffix=+Next.";

function insert(
messages: ReadonlyArray<{ id: MessageId; role: string; text: string }>,
answer = "",
cursor = answer.length,
) {
return questionReplyInsertion({
question,
answer,
cursor,
messages,
environmentId,
threadId,
});
}

describe("question reply", () => {
it("hides the control when a custom answer is not allowed", () => {
expect(REPLY_TO_QUESTION_LABEL).toBe("Reply to this question");
expect(showReplyToQuestion({ allowCustomAnswer: false })).toBe(false);
expect(showReplyToQuestion({})).toBe(true);
expect(showReplyToQuestion({ allowCustomAnswer: true })).toBe(true);
});

it("reuses the assistant citation chip when the question is an assistant message", () => {
const inserted = insert([
{
id: assistantMessageId,
role: "assistant",
text: `Context before. ${question} Context after.`,
},
]);
expect(inserted).toMatch(/^\[Assistant quote\]\(t3-citation:\/\/v1\//);
const citation = collectAssistantCitations(inserted ?? "")[0]?.citation;
expect(citation).toMatchObject({
messageId: assistantMessageId,
environmentId,
threadId,
text: question,
});
const received = projectPendingUserInputAnswer(inserted, []);
expect(received).toContain("earlier assistant responses");
expect(received).toContain(question);
expect(received).not.toContain("t3-citation://");
});

// regression: a founder's own question must not reach the model as an Assistant quote
it("does not describe a founder's own question as an assistant quote", () => {
const inserted = insert([
{
id: assistantMessageId,
role: "assistant",
text: `Earlier the assistant asked: ${question}`,
},
{
id: founderMessageId,
role: "user",
text: question,
},
]);
expect(inserted).toBe(`> Question:\n> ${question}\n\n`);
expect(inserted).not.toContain("Assistant quote");
expect(inserted).not.toContain("assistant-quote");
expect(collectAssistantCitations(inserted ?? "")).toEqual([]);
const received = projectPendingUserInputAnswer(inserted, []);
expect(received).toBe(inserted);
expect(expandAssistantCitationsForProvider(received as string)).not.toContain(
"earlier assistant responses",
);
});

it("quotes a question that is not stored on a message", () => {
const inserted = insert([]);
expect(inserted).toBe(`> Question:\n> ${question}\n\n`);
expect(collectAssistantCitations(inserted ?? "")).toEqual([]);
});

it("keeps an existing assistant-quote link working", () => {
const citation = parseAssistantCitationHref(legacyHref);
expect(citation?.text).toBe("A quote & a newline.\n");
const prompt = `[Assistant quote](${legacyHref})`;
expect(collectAssistantCitations(prompt)).toHaveLength(1);
expect(expandAssistantCitationsForProvider(prompt)).toContain("earlier assistant responses");
});

it("places a chip after the typed answer and a quote on its own paragraph", () => {
const answer = "My answer";
const chip = insert(
[{ id: assistantMessageId, role: "assistant", text: question }],
answer,
answer.length,
);
expect(chip?.startsWith(" ")).toBe(true);
expect(collectAssistantCitations(chip ?? "")).toHaveLength(1);

const quote = insert([], answer, answer.length);
expect(quote).toBe(`\n\n> Question:\n> ${question}\n\n`);
});
});
108 changes: 108 additions & 0 deletions apps/web/src/questionReply.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import {
AssistantCitation,
type EnvironmentId,
type MessageId,
type ThreadId,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";

import { formatAssistantCitationForComposer } from "./composer-logic";
import { createAssistantTextSelector } from "./lib/assistantTextSelection";

const isAssistantCitation = Schema.is(AssistantCitation);

export const REPLY_TO_QUESTION_LABEL = "Reply to this question";

/** Custom answers can hold a quote. Option-only questions cannot. */
export function showReplyToQuestion(question: {
readonly allowCustomAnswer?: boolean | undefined;
}): boolean {
return question.allowCustomAnswer !== false;
}

interface QuestionReplyMessage {
readonly id: MessageId;
readonly role: string;
readonly text: string;
}

/**
* Text to insert at `cursor`.
*
* An assistant message that contains the question reuses the citation chip.
* A founder's own question, or a question that is not a message, is a plain
* quote. That quote must not be labeled as an assistant quote.
*/
export function questionReplyInsertion(input: {
readonly question: string;
readonly answer: string;
readonly cursor: number;
readonly messages: ReadonlyArray<QuestionReplyMessage>;
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
}): string | null {
const questionText = input.question.trim();
if (questionText.length === 0) return null;

const citation = assistantCitationForQuestion(questionText, input);
const quote = citation
? formatAssistantCitationForComposer(citation)
: formatQuestionQuote(questionText);
return placeAtCursor(input.answer, input.cursor, quote, citation ? "inline" : "block");
}

function assistantCitationForQuestion(
questionText: string,
input: {
readonly messages: ReadonlyArray<QuestionReplyMessage>;
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
},
): AssistantCitation | null {
for (let index = input.messages.length - 1; index >= 0; index -= 1) {
const message = input.messages[index];
if (!message) continue;
const start = message.text.indexOf(questionText);
if (start === -1) continue;
// The newest copy wins. A founder's later message is their question, not the assistant's.
if (message.role !== "assistant") return null;
const selector = createAssistantTextSelector(message.text, start, start + questionText.length);
if (!selector) return null;
const citation = {
version: 1 as const,
environmentId: input.environmentId,
threadId: input.threadId,
messageId: message.id,
...selector,
};
return isAssistantCitation(citation) ? citation : null;
}
return null;
}

function formatQuestionQuote(question: string): string {
const body = question
.split("\n")
.map((line) => `> ${line}`)
.join("\n");
return `> Question:\n${body}\n\n`;
}

function placeAtCursor(
answer: string,
cursorInput: number,
quote: string,
kind: "inline" | "block",
): string {
const cursor = Number.isFinite(cursorInput)
? Math.max(0, Math.min(answer.length, Math.floor(cursorInput)))
: answer.length;
const before = answer.slice(0, cursor);
if (before.length === 0) return quote;
if (kind === "inline") {
return /\s/.test(before[before.length - 1] ?? "") ? quote : ` ${quote}`;
}
if (before.endsWith("\n\n")) return quote;
if (before.endsWith("\n")) return `\n${quote}`;
return `\n\n${quote}`;
}
Loading