diff --git a/.pnpmfile.cjs b/.pnpmfile.cjs index 87a153f7b030d..8e79fceda4142 100644 --- a/.pnpmfile.cjs +++ b/.pnpmfile.cjs @@ -1,16 +1,22 @@ const fs = require("node:fs"); const path = require("node:path"); -// Our forks ship as tarballs in apps/mobile/deps. A pnpm patch on one is a second source of -// truth that the next tarball silently drops, so changes go to the fork (apps/mobile/deps/README.md). +// Our forks ship as tarballs in apps/mobile/deps and apps/web/deps. A pnpm patch on one is a +// second source of truth that the next tarball silently drops, so changes go to the fork (see +// the README beside each tarball). +const FORK_APPS = ["apps/mobile", "apps/web"]; + function forkTarballPatches(patchedDependencies) { - const manifestPath = path.join(__dirname, "apps/mobile/package.json"); - // Release staging installs a partial workspace without the mobile app. - if (!patchedDependencies || !fs.existsSync(manifestPath)) return []; - const { dependencies = {} } = JSON.parse(fs.readFileSync(manifestPath, "utf8")); - const forks = Object.keys(dependencies).filter((name) => - String(dependencies[name]).startsWith("file:deps/"), - ); + if (!patchedDependencies) return []; + const forks = FORK_APPS.flatMap((app) => { + const manifestPath = path.join(__dirname, app, "package.json"); + // Release staging installs a partial workspace without every app. + if (!fs.existsSync(manifestPath)) return []; + const { dependencies = {} } = JSON.parse(fs.readFileSync(manifestPath, "utf8")); + return Object.keys(dependencies).filter((name) => + String(dependencies[name]).startsWith("file:deps/"), + ); + }); return Object.keys(patchedDependencies).filter((key) => forks.some((name) => key === name || key.startsWith(`${name}@`)), ); @@ -23,7 +29,7 @@ module.exports = { if (forkPatches.length > 0) { throw new Error( `pnpm-workspace.yaml patches ${forkPatches.join(", ")}, which ships as a fork tarball in ` + - "apps/mobile/deps. Change the fork and replace the tarball instead (apps/mobile/deps/README.md).", + "an app's deps directory. Change the fork and replace the tarball instead (deps/README.md).", ); } // Windows installs need Linux x64 glibc binaries because WSL shares node_modules. diff --git a/apps/mobile/src/components/ComposerContextSheet.tsx b/apps/mobile/src/components/ComposerContextSheet.tsx index e0dc1ace612ff..544f3f4b0560f 100644 --- a/apps/mobile/src/components/ComposerContextSheet.tsx +++ b/apps/mobile/src/components/ComposerContextSheet.tsx @@ -1,4 +1,4 @@ -import { T, useGT, Var } from "gt-react-native"; +import { T, useGT, useMessages, Var } from "gt-react-native"; import { Button } from "./ui/Button"; import * as Dialog from "./ui/Dialog"; @@ -102,6 +102,7 @@ function DeliveredProjectKnowledge(props: { readonly sent: { readonly threadId: ThreadId; readonly messageId: MessageId }; }) { const gt = useGT(); + const m = useMessages(); const config = useAtomValue( serverEnvironment.configValueAtom(props.record.knowledge.environmentId), ); @@ -141,7 +142,7 @@ function DeliveredProjectKnowledge(props: { The copy T3 delivered with this message. It does not show whether the agent used it. - {deliveredKnowledgeNotes(snapshot).map((note) => ( + {deliveredKnowledgeNotes(snapshot, m).map((note) => ( {note} @@ -149,7 +150,7 @@ function DeliveredProjectKnowledge(props: { {snapshot.omission ? ( {gt("Not sent: {reason}", { - reason: KNOWLEDGE_DELIVERY_OMISSION_LABEL[snapshot.omission.reason], + reason: m(KNOWLEDGE_DELIVERY_OMISSION_LABEL[snapshot.omission.reason]), })} ) : snapshot.item.contentRemoved ? null : ( diff --git a/apps/mobile/src/components/ProjectKnowledgeDraftFooter.tsx b/apps/mobile/src/components/ProjectKnowledgeDraftFooter.tsx index 1d1d9675f93bd..d5ca61583cc0c 100644 --- a/apps/mobile/src/components/ProjectKnowledgeDraftFooter.tsx +++ b/apps/mobile/src/components/ProjectKnowledgeDraftFooter.tsx @@ -2,6 +2,7 @@ import { useState } from "react"; import { ScrollView, View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import type { KnowledgeSelection } from "@t3tools/contracts"; +import { T, useGT } from "gt-react-native"; import { MAX_KNOWLEDGE_SELECTIONS, @@ -13,9 +14,6 @@ import { Button } from "./ui/Button"; type SelectionState = ReturnType; -const changedLabel = (selection: KnowledgeSelection) => - selection.kind === "fact" ? "Fact changed since you selected it" : "Source changed"; - /** * Draft selection, kept apart from inspection: pressing a fact or message reads it, and only this * control changes what the draft will reference. @@ -26,10 +24,11 @@ export function SelectForDraftControl(props: { readonly onToggle: (selection: KnowledgeSelection) => void; readonly onRefresh: (selection: KnowledgeSelection) => void; }) { + const gt = useGT(); return ( + ), + }; +} diff --git a/apps/web/src/components/chat/ComposerPlanFollowUpBanner.tsx b/apps/web/src/components/chat/ComposerPlanFollowUpBanner.tsx index aeffd9638065c..82671cb6742ef 100644 --- a/apps/web/src/components/chat/ComposerPlanFollowUpBanner.tsx +++ b/apps/web/src/components/chat/ComposerPlanFollowUpBanner.tsx @@ -1,3 +1,4 @@ +import { msg, useMessages } from "gt-react"; import { memo } from "react"; import { ComposerBanner } from "./ComposerBanner"; @@ -6,11 +7,12 @@ export const ComposerPlanFollowUpBanner = memo(function ComposerPlanFollowUpBann }: { planTitle: string | null; }) { + const m = useMessages(); return ( - Plan ready + {m(msg("Plan ready"))} {planTitle ? ( {planTitle} ) : null} diff --git a/apps/web/src/components/chat/ComposerPrimaryActions.tsx b/apps/web/src/components/chat/ComposerPrimaryActions.tsx index 51d75934c8668..5ef3526564d7b 100644 --- a/apps/web/src/components/chat/ComposerPrimaryActions.tsx +++ b/apps/web/src/components/chat/ComposerPrimaryActions.tsx @@ -55,6 +55,8 @@ interface ComposerPrimaryActionsProps { /** Dictation is running; Send finishes it and submits once the transcript lands. */ voiceInputActive?: boolean; isSendBusy: boolean; + /** A send is armed and waiting for its attachments to finish preparing or uploading. */ + isSendHeld?: boolean; sendDisabledReason: string | null; isEnvironmentUnavailable: boolean; isPreparingWorktree: boolean; @@ -249,6 +251,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ promptHasText, voiceInputActive = false, isSendBusy, + isSendHeld = false, sendDisabledReason, isEnvironmentUnavailable, isPreparingWorktree, @@ -431,7 +434,8 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ if ( (canInterrupt || stopPhase === "pending" || stopPhase === "timedOut") && !hasSendableContent && - !isEditingQueuedMessage + !isEditingQueuedMessage && + !isSendHeld ) { return renderStopGenerationButton(false); } @@ -457,14 +461,16 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ : gt("Submit message"); const submitStatus = isEnvironmentUnavailable ? gt("Environment disconnected") - : (sendDisabledReason ?? - (isPreparingWorktree - ? gt("Preparing worktree") - : isSendBusy - ? isEditingQueuedMessage - ? gt("Updating queued message") - : gt("Submitting message") - : null)); + : isSendHeld + ? gt("Sending when ready") + : (sendDisabledReason ?? + (isPreparingWorktree + ? gt("Preparing worktree") + : isSendBusy + ? isEditingQueuedMessage + ? gt("Updating queued message") + : gt("Submitting message") + : null)); const modifier = isMacPlatform(navigator.platform) ? "⌘" : "Ctrl"; const dispatchTooltip = alternateAction === "queue" @@ -488,6 +494,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ ? dispatchTooltip : submitLabel); + const isBusyOrHeld = isSendBusy || isSendHeld; const sendButton = ( + + + ); + } + return (
- } - className={MARKDOWN_FILE_LINK_CLASS_NAME} - data-markdown-copy={copyMarkdown} - onClick={(event) => { - event.preventDefault(); - event.stopPropagation(); - if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) { - handleOpenInEditor(); - return; - } - if (useBrowserPrimaryAction) { - handleOpenInBrowser(); - return; - } - handleOpenInFilePreview(); - }} - onContextMenu={handleContextMenu} - > - - ) : undefined - } - path={iconPath} - environmentId={environmentId} - label={label} - theme={theme} - /> - - ) : ( - } - aria-label={gt("File options for {label}", { label })} - aria-haspopup="menu" - className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")} - data-markdown-copy={copyMarkdown} - onClick={handleContextMenu} - onContextMenu={handleContextMenu} - > - - ) : undefined - } - path={iconPath} - environmentId={environmentId} - label={label} - theme={theme} - /> - - ) + const tooltipContent = ( + + ); + const sharedTooltip = useSharedTooltip({ + render: () => tooltipContent, + contentKey: `${iconPath}\u0000${targetPath}`, + variant: "code", + }); + const chip = hasPrimaryAction ? ( + } + className={MARKDOWN_FILE_LINK_CLASS_NAME} + data-markdown-copy={copyMarkdown} + onClick={(event) => { + event.preventDefault(); + event.stopPropagation(); + if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) { + handleOpenInEditor(); + return; + } + if (useBrowserPrimaryAction) { + handleOpenInBrowser(); + return; } + handleOpenInFilePreview(); + }} + onContextMenu={handleContextMenu} + > + : undefined + } + path={iconPath} + environmentId={environmentId} + label={label} + theme={theme} + /> + + ) : ( + } + aria-label={gt("File options for {label}", { label })} + aria-haspopup="menu" + className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")} + data-markdown-copy={copyMarkdown} + onClick={handleContextMenu} + onContextMenu={handleContextMenu} + > + : undefined + } + path={iconPath} + environmentId={environmentId} + label={label} + theme={theme} /> + + ); + if (sharedTooltip) return withSharedTooltip(chip, sharedTooltip); + return ( + + - + {tooltipContent} ); diff --git a/apps/web/src/components/chat/MarkdownMath.browser.test.tsx b/apps/web/src/components/chat/MarkdownMath.browser.test.tsx deleted file mode 100644 index ec5b38541ddc4..0000000000000 --- a/apps/web/src/components/chat/MarkdownMath.browser.test.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { expect, it } from "vite-plus/test"; -import { userEvent } from "vite-plus/test/browser"; - -import { render } from "../../../test/render"; -import "../../index.css"; - -import { MarkdownMath } from "./MarkdownMath"; - -it("keeps keyboard scrolling available as a streamed equation outgrows its viewport", async () => { - const equation = (tex: string, width = 180) => ( -
- - - -
- ); - await using screen = await render(equation("x")); - await screen.getByRole("button", { name: "Before equation" }).click(); - await userEvent.keyboard("{Tab}"); - await expect.element(screen.getByRole("button", { name: "After equation" })).toHaveFocus(); - - await screen.rerender(equation("x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_7 + x_8")); - const scroller = screen.getByLabelText("Scroll display equation"); - await expect.element(scroller).toHaveAttribute("tabindex", "0"); - await screen.getByRole("button", { name: "Before equation" }).click(); - await userEvent.keyboard("{Tab}"); - await expect.element(scroller).toHaveFocus(); - await userEvent.keyboard("{ArrowRight}"); - await expect.element(scroller).not.toHaveProperty("scrollLeft", 0); - - await screen.rerender(equation("x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_7 + x_8", 1000)); - await expect.element(screen.getByLabelText("Scroll display equation")).not.toBeInTheDocument(); - await screen.getByRole("button", { name: "Before equation" }).click(); - await userEvent.keyboard("{Tab}"); - await expect.element(screen.getByRole("button", { name: "After equation" })).toHaveFocus(); -}); diff --git a/apps/web/src/components/chat/MarkdownMath.tsx b/apps/web/src/components/chat/MarkdownMath.tsx deleted file mode 100644 index 8070d64ac3c18..0000000000000 --- a/apps/web/src/components/chat/MarkdownMath.tsx +++ /dev/null @@ -1,81 +0,0 @@ -import { useGT } from "gt-react"; -import { lazy, memo, Suspense, useLayoutEffect, useRef, useState } from "react"; - -import { observeResize } from "../../lib/observeResize"; - -import { RenderErrorBoundary } from "../RenderErrorBoundary"; - -const MathTypeset = lazy(() => import("./MathTypeset")); - -/** - * One formula from `remark-math`. Shows its TeX until KaTeX loads, and - * keeps showing it when KaTeX cannot parse it, such as mid-stream. Copying - * any part of a formula copies its whole TeX source. - */ -export const MarkdownMath = memo(function MarkdownMath(props: { - tex: string; - display: boolean; - focusable?: boolean; -}) { - const gt = useGT(); - const viewportRef = useRef(null); - const contentRef = useRef(null); - const [overflows, setOverflows] = useState(false); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes formula DOM width to make overflowing equations keyboard scrollable - useLayoutEffect(() => { - const viewport = viewportRef.current; - const content = contentRef.current; - if (!viewport || !content || props.focusable === false) return; - const measure = () => setOverflows(viewport.scrollWidth > viewport.clientWidth); - measure(); - // Typesetting and streamed TeX can change content width without resizing the viewport. - return observeResize([viewport, content], measure); - }, [props.focusable]); - const scrollable = props.focusable !== false && overflows; - const tex = props.tex.trim(); - const source = props.display ? `\\[\n${tex}\n\\]` : `\\(${tex}\\)`; - const fallback = {source}; - return ( - - - - - - - - - - - - ); -}); diff --git a/apps/web/src/components/chat/MathTypeset.logic.test.ts b/apps/web/src/components/chat/MathTypeset.logic.test.ts deleted file mode 100644 index 634f5146475ac..0000000000000 --- a/apps/web/src/components/chat/MathTypeset.logic.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import katex from "katex"; -import { describe, expect, it } from "vite-plus/test"; - -import { escapeLiteralPercents } from "./MathTypeset.logic"; - -describe("escapeLiteralPercents", () => { - it.each([ - ["\\text{3.18% yield}", "\\text{3.18\\% yield}"], - ["\\text{100%% yield}", "\\text{100\\%\\% yield}"], - ["6\\% + 2\\%", "6\\% + 2\\%"], - ["x\\\\%", "x\\\\\\%"], - ["x % note\n+ 1", "x % note\n+ 1"], - ["% note\n\\text{2%}", "% note\n\\text{2\\%}"], - ["x &= 1 % +9%\n\\text{2%}", "x &= 1 % +9%\n\\text{2\\%}"], - ["\\verb|50%|+\\text{2%}", "\\verb|50%|+\\text{2\\%}"], - ["\\verb*%a%b%+c%", "\\verb*%a%b\\%+c\\%"], - ["\\verb|50%+\\text{2%}", "\\verb|50%+\\text{2%}"], - ])("repairs %j", (tex, expected) => { - expect(escapeLiteralPercents(tex)).toBe(expected); - }); - - it("lets the reported multiline equation typeset", () => { - const tex = - "R_e=\\underbrace{\\frac{1.0176}{32}}_{\\text{3.18% dividend yield}}\n+\\underbrace{6\\%}_{\\text{growth}}\n=\\boxed{9.18\\%}"; - expect(() => katex.renderToString(tex, { throwOnError: true })).toThrow(); - expect(() => - katex.renderToString(escapeLiteralPercents(tex), { throwOnError: true }), - ).not.toThrow(); - }); -}); diff --git a/apps/web/src/components/chat/MathTypeset.logic.ts b/apps/web/src/components/chat/MathTypeset.logic.ts deleted file mode 100644 index 04111ab4a70b4..0000000000000 --- a/apps/web/src/components/chat/MathTypeset.logic.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Escapes each `%` written right after other text, as in `\text{3.18% yield}`. - * A `%` at a line start or after whitespace stays a comment. Skips escapes and - * `\verb` like KaTeX's lexer, in one linear pass. - */ -export function escapeLiteralPercents(tex: string): string { - let repaired = ""; - let copied = 0; - let index = 0; - while (index < tex.length) { - const char = tex[index]; - if (char === "\\") { - if (tex.startsWith("\\verb", index)) { - const starred = tex[index + 5] === "*"; - const delimiter = tex[index + (starred ? 6 : 5)]; - if (delimiter !== undefined && (starred || !/[*a-zA-Z]/.test(delimiter))) { - const bodyStart = index + (starred ? 7 : 6); - let close = bodyStart; - while (close < tex.length && ![delimiter, "\n", "\r"].includes(tex[close]!)) close++; - // KaTeX rejects a \verb that does not close on its own line. - if (tex[close] !== delimiter) return tex; - index = close + 1; - continue; - } - } - // A control symbol such as `\%` or `\\` is two characters. - index += 2; - } else if (char === "%" && index > 0 && !/\s/.test(tex[index - 1]!)) { - repaired += `${tex.slice(copied, index)}\\%`; - copied = ++index; - } else if (char === "%") { - const newline = tex.indexOf("\n", index); - index = newline === -1 ? tex.length : newline + 1; - } else { - index++; - } - } - return copied === 0 ? tex : repaired + tex.slice(copied); -} diff --git a/apps/web/src/components/chat/MathTypeset.tsx b/apps/web/src/components/chat/MathTypeset.tsx deleted file mode 100644 index 16d3dba409ee6..0000000000000 --- a/apps/web/src/components/chat/MathTypeset.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import katex from "katex"; -import "katex/dist/katex.min.css"; -import type { ReactNode } from "react"; - -import { LRUCache } from "../../lib/lruCache"; -import { escapeLiteralPercents } from "./MathTypeset.logic"; - -// Virtualized threads remount messages while scrolling; cached markup keeps -// that from typesetting the same formulas again. "" records a parse error. -const typesetCache = new LRUCache(1000, 4 * 1024 * 1024); - -function typeset(tex: string, display: boolean): string { - const key = `${display ? "display" : "inline"}:${tex}`; - const cached = typesetCache.get(key); - if (cached !== null) return cached; - const options = { - displayMode: display, - output: "htmlAndMathml" as const, - throwOnError: true, - // No \href, \url, \htmlClass, or other commands that emit active HTML. - trust: false, - strict: "ignore" as const, - maxSize: 20, - maxExpand: 1000, - }; - let html = ""; - try { - html = katex.renderToString(tex, options); - } catch { - const repaired = escapeLiteralPercents(tex); - if (repaired !== tex) { - try { - html = katex.renderToString(repaired, options); - } catch { - // Unfinished or unsupported TeX stays readable as its source. - } - } - } - typesetCache.set(key, html, (key.length + html.length) * 2); - return html; -} - -/** KaTeX lives in this lazily loaded chunk, so it is only fetched once a formula renders. */ -export default function MathTypeset(props: { tex: string; display: boolean; fallback: ReactNode }) { - const html = typeset(props.tex, props.display); - if (!html) return props.fallback; - // KaTeX escapes the TeX it renders, and `trust: false` keeps it from emitting links or attributes. - return ; -} diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index e1e5be0de01cd..f387a1daeb6cd 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -44,11 +44,10 @@ import { type PendingApproval, deriveTimelineEntriesFromVisibleTurnItems, } from "../../session-logic"; -import type { Root } from "mdast"; import { ViewedImagesTimelineRow } from "./TimelineWorkEntryRow"; -import { remarkThoughtPreview, THOUGHT_PREVIEW_MAX_LENGTH } from "./TimelineWorkEntryRow.logic"; +import { THOUGHT_PREVIEW_MAX_LENGTH, thoughtPreviewMarkdown } from "./TimelineWorkEntryRow.logic"; +import { wordsHast } from "~/markdown/wordsHast"; import { TimelineRowCtx } from "./timelineRowContext"; -import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath"; import { searchableMessageSegments } from "@t3tools/shared/threadFindText"; import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { collectThreadFindRanges } from "./threadFindHighlights"; @@ -2136,49 +2135,22 @@ describe("compact reasoning math", () => { ["hard \nbreak\\\nagain", [["text", "hard break again"]]], ["
only html
", [["text", "Reasoning"]]], ])("keeps formulas while flattening compact reasoning previews: %j", (source, expected) => { - const tree = parseMarkdownWithMath(source); - remarkThoughtPreview("Reasoning")(tree); - expect(tree.children.map((node) => [node.type, "value" in node ? node.value : null])).toEqual( - expected, - ); - }); - - it("stops reading the tree once the preview is full", () => { - const beyondCap = (): string => { - throw new Error("read beyond cap"); - }; - const head = "x".repeat(THOUGHT_PREVIEW_MAX_LENGTH - 2); - const tree: Root = { - type: "root", - children: [ - { - type: "paragraph", - children: [ - { type: "text", value: head }, - { type: "strong", children: [{ type: "text", value: "yz beyond" }] }, - { - type: "inlineMath", - get value() { - return beyondCap(); - }, - }, - ], - }, - { - type: "paragraph", - children: [ - { - type: "text", - get value() { - return beyondCap(); - }, - }, - ], - }, - ], - }; - remarkThoughtPreview("Reasoning")(tree); - expect(tree.children).toEqual([{ type: "text", value: `${head}yz` }]); + const tree = wordsHast(source, { + math: true, + breaks: false, + escapeHtml: false, + insights: false, + extensions: thoughtPreviewMarkdown("Reasoning"), + }); + expect( + tree.children.map((node) => + node.type === "text" + ? ["text", node.value] + : node.type === "element" && node.children[0]?.type === "element" + ? ["inlineMath", String(node.children[0].properties.ariaLabel).trim()] + : [node.type, null], + ), + ).toEqual(expected); }); }); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 19cf11cefa886..6559f85af24ce 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -14,7 +14,7 @@ import { IDLE_COMPACTION_TITLES, } from "@t3tools/client-runtime/user-message"; import type { HandoffTimelineRun } from "@t3tools/client-runtime/handoff"; -import { renderCodexDirectivesForCopy } from "@t3tools/shared/codexMarkdownDirectives"; +import { renderCodexDirectivesForCopy } from "~/markdown/markdownText"; import { commandDisplayText, commandProgramName, diff --git a/apps/web/src/components/chat/ThreadCodeIndexRow.tsx b/apps/web/src/components/chat/ThreadCodeIndexRow.tsx index 48ee7809e59ca..a75de0c6f3bdc 100644 --- a/apps/web/src/components/chat/ThreadCodeIndexRow.tsx +++ b/apps/web/src/components/chat/ThreadCodeIndexRow.tsx @@ -1,6 +1,7 @@ import { useAtomValue } from "@effect/atom-react"; import type { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts"; import { WaypointsIcon } from "lucide-react"; +import { T } from "gt-react"; import { cn } from "../../lib/utils"; import { projectCode } from "../../state/projectCode"; @@ -33,7 +34,9 @@ export function ThreadCodeIndexRow(props: { )} > - Code index + + Code index + setOpen(true)}> - Conversation summaries + {m(msg("Conversation summaries"))} diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx index a684a5d16b38f..d2f0eda822336 100644 --- a/apps/web/src/components/chat/TimelineAssistantRows.tsx +++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx @@ -4,7 +4,7 @@ import { quietPassLine, withoutCloseLine, } from "@t3tools/client-runtime/state/thread-group"; -import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline"; +import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/assistantInsights"; import { trimThreadAutolinkPadding } from "@t3tools/shared/threadLinks"; import { MessageId, type RunId, type TurnItemId } from "@t3tools/contracts"; import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows"; diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index 59623876f0157..e953f86527831 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -1,10 +1,7 @@ import { copySnapshot as copySnapshotToClipboard } from "./copySnapshot"; import { InlineAudioPreview } from "../files/InlineAudioPreview"; import { filePreviewKind } from "@t3tools/shared/filePreview"; -import { - CHAT_USER_MARKDOWN_REMARK_PLUGINS, - remarkEnableOrderedListNumbers, -} from "@t3tools/shared/markdownPipeline"; +import type { MarkdownExtensions } from "~/markdown/wordsHast"; import { T, useGT, useMessages, Var } from "gt-react"; import { findRevealRef } from "./markdownFindContext"; import { @@ -1294,10 +1291,7 @@ const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(prop ); }); -const USER_MESSAGE_REMARK_PLUGINS = [ - ...CHAT_USER_MARKDOWN_REMARK_PLUGINS, - remarkEnableOrderedListNumbers, -]; +const USER_MESSAGE_MARKDOWN: MarkdownExtensions = { userMessage: true, leadingWhitespace: true }; const UserMessageBody = memo(function UserMessageBody(props: { text: string; @@ -1319,7 +1313,7 @@ const UserMessageBody = memo(function UserMessageBody(props: { className="text-message-foreground user-message-markdown" lineBreaks parseRawHtml={false} - extraRemarkPlugins={USER_MESSAGE_REMARK_PLUGINS} + extensions={USER_MESSAGE_MARKDOWN} renderContextReference={props.renderContextReference} headingLevelOffset={MESSAGE_HEADING_LEVEL} /> diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts b/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts index 3dff15b026799..12d26a9c183f2 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts @@ -1,6 +1,5 @@ import { msg } from "gt-react"; -import type { PluggableList } from "unified"; -import type { Root, RootContent } from "mdast"; +import type { MarkdownExtensions } from "~/markdown/wordsHast"; import { resolveWorkEntryToolPresentation, toolGroupAction, @@ -211,67 +210,14 @@ export function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconNa export const THOUGHT_PREVIEW_SOURCE_MAX_LENGTH = 8_192; export const THOUGHT_PREVIEW_MAX_LENGTH = 2_048; -/** Compact reasoning keeps formulas while flattening other Markdown into label text. */ -export function remarkThoughtPreview(fallback: string) { - return (tree: Root) => { - const children: RootContent[] = []; - let remaining = THOUGHT_PREVIEW_MAX_LENGTH; - let fragments: string[] = []; - const flush = () => { - if (fragments.length === 0) return; - children.push({ type: "text", value: fragments.join("").replace(/\s+/g, " ") }); - fragments = []; - }; - const take = (value: string) => { - const text = value.slice(0, remaining); - remaining = text.length < value.length ? 0 : remaining - text.length; - // A cut here or at the source limit must not leave half a surrogate pair. - return text.replace(/[\uD800-\uDBFF]$/, ""); - }; - const append = (value: string) => { - fragments.push(take(value)); - }; - const visit = (node: Root | RootContent) => { - if (remaining === 0 || node.type === "html" || node.type === "definition") return; - if (node.type === "math" || node.type === "inlineMath") { - flush(); - const value = take(node.value); - children.push({ - type: "inlineMath", - value, - position: node.position, - data: { - hName: "code", - hProperties: { className: ["language-math", "math-inline"] }, - hChildren: [{ type: "text", value }], - }, - }); - } else if ("alt" in node) append(node.alt ?? ""); - else if ("value" in node) append(node.value); - else if ("children" in node) { - for (const [index, child] of node.children.entries()) { - if (remaining === 0) break; - if ( - index && - ["root", "blockquote", "list", "listItem", "table", "tableRow"].includes(node.type) - ) - append(" "); - visit(child); - } - } else if (node.type === "break") append(" "); - }; - visit(tree); - flush(); - const first = children[0]; - const last = children.at(-1); - if (first?.type === "text") first.value = first.value.trimStart(); - if (last?.type === "text") last.value = last.value.trimEnd(); - tree.children = children.some((child) => child.type !== "text" || child.value) - ? children - : [{ type: "text", value: fallback }]; - }; -} +const thoughtPreviews = new Map(); -export function thoughtPreviewPlugins(fallback: string): PluggableList { - return [[remarkThoughtPreview, fallback]]; +/** Compact reasoning keeps formulas while flattening other Markdown into label text. */ +export function thoughtPreviewMarkdown(fallback: string): MarkdownExtensions { + let extensions = thoughtPreviews.get(fallback); + if (!extensions) { + extensions = { preview: { fallback, maxLength: THOUGHT_PREVIEW_MAX_LENGTH } }; + thoughtPreviews.set(fallback, extensions); + } + return extensions; } diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx index 8e7f03618e59d..4cd6fc0e8dee6 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx @@ -73,7 +73,7 @@ import { workEntryRawCommand, buildToolCallExpandedBody, workEntryIconName, - thoughtPreviewPlugins, + thoughtPreviewMarkdown, THOUGHT_PREVIEW_SOURCE_MAX_LENGTH, } from "./TimelineWorkEntryRow.logic"; @@ -590,10 +590,10 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { )} cwd={ctx.markdownCwd} parseRawHtml={false} - extraRemarkPlugins={ + extensions={ workEntry.toolLifecycleStatus === "inProgress" - ? thoughtPreviewPlugins(gt("Thinking")) - : thoughtPreviewPlugins(gt("Thought")) + ? thoughtPreviewMarkdown(gt("Thinking")) + : thoughtPreviewMarkdown(gt("Thought")) } /> ) : threadLabel ? ( diff --git a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx index 745a7aff68fdf..c67c76bf4cca3 100644 --- a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx +++ b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx @@ -56,7 +56,7 @@ import { SimpleWorkEntryRow, } from "./TimelineWorkEntryRow"; import { - thoughtPreviewPlugins, + thoughtPreviewMarkdown, THOUGHT_PREVIEW_SOURCE_MAX_LENGTH, toolGroupSummaryIconName, workEntryIconName, @@ -640,7 +640,7 @@ export function LiveWorkEntryTimelineRow({ text={thoughtLine} cwd={ctx.markdownCwd} parseRawHtml={false} - extraRemarkPlugins={thoughtPreviewPlugins(gt("Thought"))} + extensions={thoughtPreviewMarkdown(gt("Thought"))} />
} @@ -661,10 +661,10 @@ export function LiveWorkEntryTimelineRow({ text={(row.entry.detail ?? label).slice(0, THOUGHT_PREVIEW_SOURCE_MAX_LENGTH)} cwd={ctx.markdownCwd} parseRawHtml={false} - extraRemarkPlugins={ + extensions={ row.active - ? thoughtPreviewPlugins(gt("Thinking")) - : thoughtPreviewPlugins(gt("Thought")) + ? thoughtPreviewMarkdown(gt("Thinking")) + : thoughtPreviewMarkdown(gt("Thought")) } /> ) : threadLabel ? ( diff --git a/apps/web/src/components/chat/V2LifecycleRow.tsx b/apps/web/src/components/chat/V2LifecycleRow.tsx index 5edad8855864f..2f48a4d2d9154 100644 --- a/apps/web/src/components/chat/V2LifecycleRow.tsx +++ b/apps/web/src/components/chat/V2LifecycleRow.tsx @@ -88,6 +88,7 @@ export function V2LifecycleRow(props: { }) { const { item } = props; const gt = useGT(); + const m = useMessages(); if (item.type === "run_interrupt_result") { return ( ); diff --git a/apps/web/src/components/chat/composerAttachmentFiles.test.ts b/apps/web/src/components/chat/composerAttachmentFiles.test.ts index 2a487b1f237de..f842566d7cd60 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.test.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.test.ts @@ -121,10 +121,26 @@ describe("composer attachment files", () => { ).toBe(true); }); - it("leaves an image-and-text clipboard to the text path under Paste as Text", () => { + it("leaves a Word image-and-text clipboard to the text path, with or without Paste as Text", () => { const image = new File(["png"], "image.png", { type: "image/png" }); const input = { files: [image], plainText: "Hello from Word", bypassAutoAttachment: true }; expect(shouldHandleComposerAttachmentPaste(input)).toBe(false); + // A plain paste of the same Word clipboard keeps the text too. + expect(shouldHandleComposerAttachmentPaste({ ...input, bypassAutoAttachment: false })).toBe( + false, + ); + // Firefox's Copy Image adds the image URL as text and only an as HTML; the image attaches. + expect( + shouldHandleComposerAttachmentPaste({ + files: [image], + plainText: "https://example.com/image.png", + htmlIsOnlyImage: true, + }), + ).toBe(true); + // Finder adds a copied file's name as text. + expect(shouldHandleComposerAttachmentPaste({ files: [image], plainText: "image.png" })).toBe( + true, + ); }); it("preserves text when the clipboard also includes generic image files", () => { diff --git a/apps/web/src/components/chat/composerAttachmentFiles.ts b/apps/web/src/components/chat/composerAttachmentFiles.ts index 041db7193d2e2..191c5841185ff 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.ts @@ -239,30 +239,46 @@ export function attachmentsToReleaseOnUploadCapabilityLoss( ); } +function isOnlyFileNames(text: string, files: ReadonlyArray): boolean { + const names = new Set(files.map((file) => file.name)); + return text + .split(/\r?\n/) + .filter((line) => line.length > 0) + .every((line) => names.has(line)); +} + +/** A browser's Copy Image puts only an in text/html; rich text sources put the text there. */ +export function isImageOnlyClipboardHtml(html: string): boolean { + if (html.length === 0) return false; + const body = new DOMParser().parseFromString(html, "text/html").body; + return body.querySelector("img") !== null && (body.textContent ?? "").trim().length === 0; +} + export function shouldHandleComposerAttachmentPaste(input: { readonly files: ReadonlyArray; readonly plainText: string; readonly bypassAutoAttachment?: boolean; + readonly htmlIsOnlyImage?: boolean; }): boolean { // Paste as Text keeps the text even when the source also put an image of it on the clipboard. if (input.bypassAutoAttachment && input.plainText.length > 0) return false; if ( - input.files.some((file) => { - if (isDngFile(file)) return true; - const classification = classifyComposerAttachmentFile(file); - return ( - classification === "image" || - classification === "unsupported-image" || - isSvgAttachment({ name: file.name, mimeType: file.type }) - ); - }) + input.files.some( + (file) => isDngFile(file) || isSvgAttachment({ name: file.name, mimeType: file.type }), + ) ) { return true; } - - if (input.plainText.length > 0) { - return false; + const hasImage = input.files.some((file) => { + const classification = classifyComposerAttachmentFile(file); + return classification === "image" || classification === "unsupported-image"; + }); + if (input.plainText.length === 0) { + return hasImage || input.files.some((file) => classifyComposerAttachmentFile(file) === "file"); } - - return input.files.some((file) => classifyComposerAttachmentFile(file) === "file"); + // Rich text sources (Word, Pages) add a picture of the text. Copy Image adds the image URL as + // text beside an , and a Finder copy adds the file names. + return ( + hasImage && (input.htmlIsOnlyImage === true || isOnlyFileNames(input.plainText, input.files)) + ); } diff --git a/apps/web/src/components/chat/composerSend.logic.test.ts b/apps/web/src/components/chat/composerSend.logic.test.ts index b87f4798ca6a9..8210494c94a10 100644 --- a/apps/web/src/components/chat/composerSend.logic.test.ts +++ b/apps/web/src/components/chat/composerSend.logic.test.ts @@ -84,6 +84,18 @@ it("detects draft edits during upload preparation without treating upload metada expect(composerDraftContentChanged(draft, { ...draft, threadContexts: [localThread] })).toBe( true, ); + const knowledge = projectKnowledgeContextRecord({ + environmentId: local, + projectId: ProjectId.make("project"), + selections: [{ kind: "fact", factId: ProjectFactId.make("fact"), revision: 1 }], + maxBytes: 48000, + }); + const withKnowledge = { ...draft, knowledgeContexts: [knowledge] }; + expect(composerDraftContentChanged(draft, withKnowledge)).toBe(true); + expect(composerDraftContentChanged(withKnowledge, { ...draft, knowledgeContexts: [] })).toBe( + true, + ); + expect(composerDraftContentChanged(draft, { ...draft, knowledgeContexts: [] })).toBe(false); }); describe("referencedThreadContexts", () => { diff --git a/apps/web/src/components/chat/composerSend.logic.ts b/apps/web/src/components/chat/composerSend.logic.ts index 1b8ee3aea7652..9e8b255ed3510 100644 --- a/apps/web/src/components/chat/composerSend.logic.ts +++ b/apps/web/src/components/chat/composerSend.logic.ts @@ -27,6 +27,9 @@ export function composerDraftContentChanged( before.reviewComments !== after.reviewComments || before.threadContexts !== after.threadContexts || before.environmentContexts !== after.environmentContexts || + (before.knowledgeContexts !== after.knowledgeContexts && + ((before.knowledgeContexts?.length ?? 0) > 0 || + (after.knowledgeContexts?.length ?? 0) > 0)) || before.replyTo !== after.replyTo ); } diff --git a/apps/web/src/components/chat/groupAvailability.ts b/apps/web/src/components/chat/groupAvailability.ts index e9afef0ba04f5..657b540029f20 100644 --- a/apps/web/src/components/chat/groupAvailability.ts +++ b/apps/web/src/components/chat/groupAvailability.ts @@ -1,3 +1,5 @@ +import { msg } from "gt-react"; +import { m } from "../../i18n/messages"; import { useAtomValue } from "@effect/atom-react"; import { isAtomCommandInterrupted, @@ -53,7 +55,7 @@ export function reportGroupCommandFailure( stackedThreadToast({ type: "error", title, - description: error instanceof Error ? error.message : "An error occurred.", + description: error instanceof Error ? error.message : m(msg("An error occurred.")), }), ); } diff --git a/apps/web/src/components/chat/markdownIslands.test.ts b/apps/web/src/components/chat/markdownIslands.test.ts new file mode 100644 index 0000000000000..f328c9ea51251 --- /dev/null +++ b/apps/web/src/components/chat/markdownIslands.test.ts @@ -0,0 +1,50 @@ +import type { Root } from "hast"; +import { renderToStaticMarkup } from "react-dom/server"; +import { createElement, Fragment } from "react"; +import { describe, expect, it } from "vite-plus/test"; + +import { renderHastWithIslands } from "./markdownIslands"; + +describe("renderHastWithIslands", () => { + it("writes SVG attributes by their SVG names in static HTML", () => { + const tree: Root = { + type: "root", + children: [ + { + type: "element", + tagName: "p", + properties: {}, + children: [ + { + type: "element", + tagName: "svg", + properties: { viewBox: "0 0 1 1" }, + children: [ + { + type: "element", + tagName: "text", + properties: { fontSize: "700", strokeWidth: "2" }, + children: [{ type: "text", value: "x" }], + }, + ], + }, + ], + }, + ], + }; + const html = renderToStaticMarkup( + createElement( + Fragment, + null, + renderHastWithIslands(tree, { + components: {}, + variant: "", + isIsland: () => false, + staticElement: (node) => node, + }), + ), + ); + expect(html).toContain('x'); + expect(html).toContain('viewBox="0 0 1 1"'); + }); +}); diff --git a/apps/web/src/components/chat/markdownIslands.ts b/apps/web/src/components/chat/markdownIslands.ts new file mode 100644 index 0000000000000..8c434daf099ce --- /dev/null +++ b/apps/web/src/components/chat/markdownIslands.ts @@ -0,0 +1,214 @@ +import type { Element, ElementContent, Properties, Root, RootContent } from "hast"; +import { find, html as htmlSchema, svg as svgSchema } from "property-information"; +import { toJsxRuntime, type Components } from "hast-util-to-jsx-runtime"; +import { createElement, Fragment as ReactFragment, type ReactNode } from "react"; +import { Fragment, jsx, jsxs } from "react/jsx-runtime"; + +export interface MarkdownIslandOptions { + readonly components: Partial; + /** Elements that need their React component; everything else renders as static HTML. */ + readonly isIsland: (node: Element) => boolean; + /** What a static element's component would have added, or the node itself when nothing. */ + readonly staticElement: (node: Element) => Element; + /** Separates static HTML that `staticElement` renders differently, such as a heading offset. */ + readonly variant: string; +} + +const VOID_ELEMENTS = new Set( + "area base br col embed hr img input link meta source track wbr".split(" "), +); + +const jsxOptions = (components: Partial) => + ({ + Fragment, + components, + ignoreInvalidStyle: true, + jsx, + jsxs, + passKeys: true, + passNode: true, + }) as const; + +// Static HTML depends only on the cached, immutable tree and the variant. +const innerHtmlCache = new WeakMap(); + +function transformStatic( + node: ElementContent, + staticElement: MarkdownIslandOptions["staticElement"], +): ElementContent { + if (node.type !== "element") return node; + const element = staticElement(node); + let children: ElementContent[] | undefined; + for (let index = 0; index < element.children.length; index++) { + const child = element.children[index]!; + const next = transformStatic(child, staticElement); + if (next !== child) { + children ??= element.children.slice(); + children[index] = next; + } + } + return children ? { ...element, children } : element; +} + +function innerHtml(node: Element, options: MarkdownIslandOptions): string { + const cached = innerHtmlCache.get(node); + if (cached?.variant === options.variant) return cached.html; + let html = ""; + for (const child of node.children) { + html += serialize(transformStatic(child, options.staticElement)); + } + innerHtmlCache.set(node, { variant: options.variant, html }); + return html; +} + +interface AttributeInfo { + readonly name: string; + readonly boolean: boolean; + readonly separator: string; +} + +const attributeInfo = new Map(); + +// SVG names its attributes differently (`fontSize` is `font-size`), so its lookups key apart. +function infoFor(property: string, inSvg: boolean): AttributeInfo { + const key = inSvg ? `svg:${property}` : property; + let info = attributeInfo.get(key); + if (!info) { + const found = find(inSvg ? svgSchema : htmlSchema, property); + info = { + name: found.attribute, + boolean: found.boolean || found.overloadedBoolean, + separator: found.commaSeparated ? ", " : " ", + }; + attributeInfo.set(key, info); + } + return info; +} + +const escapeText = (value: string) => + value.includes("&") || value.includes("<") || value.includes(">") + ? value.replace(/&/g, "&").replace(//g, ">") + : value; +const escapeAttribute = (value: string) => + value.includes("&") || value.includes('"') + ? value.replace(/&/g, "&").replace(/"/g, """) + : value; + +/** HTML for the elements and text this pipeline builds; the DOM matches hast-util-to-html's. */ +function serialize(node: ElementContent, inSvg = false): string { + if (node.type === "text") return escapeText(node.value); + if (node.type !== "element") return ""; + const svg = inSvg || node.tagName === "svg"; + let html = `<${node.tagName}`; + const { properties } = node; + for (const key in properties) { + const value = properties[key]; + if (value === null || value === undefined || value === false || Number.isNaN(value)) continue; + const info = infoFor(key, svg); + if (info.boolean && value) { + html += ` ${info.name}`; + continue; + } + const text = Array.isArray(value) + ? value.join(info.separator) + : value === true + ? "" + : String(value); + html += ` ${info.name}="${escapeAttribute(text)}"`; + } + html += ">"; + if (VOID_ELEMENTS.has(node.tagName)) return html; + for (const child of node.children) html += serialize(child, svg); + return `${html}`; +} + +/** React props for an element, converted as hast-util-to-jsx-runtime converts them. */ +function shallowProps(node: Element, components: Partial): Record { + const element = toJsxRuntime( + { ...node, children: [] }, + { ...jsxOptions(components), components: {}, passNode: false }, + ) as { props: Record }; + const { children: _children, ...props } = element.props; + return props; +} + +interface Plan { + readonly islands: Set; + /** Elements with an island somewhere below them. */ + readonly ancestors: Set; +} + +function renderContent( + node: RootContent, + key: number, + options: MarkdownIslandOptions, + plan: Plan, +): ReactNode { + if (node.type === "text") return node.value; + if (node.type !== "element") return null; + if (plan.islands.has(node)) { + return createElement( + ReactFragment, + { key }, + toJsxRuntime(node, jsxOptions(options.components)), + ); + } + const element = options.staticElement(node); + const props: Record = { ...shallowProps(element, options.components), key }; + if (plan.ancestors.has(node)) { + return createElement( + element.tagName, + props, + ...element.children.map((child, index) => renderContent(child, index, options, plan)), + ); + } + if (element.children.length > 0 && !VOID_ELEMENTS.has(element.tagName)) { + props.dangerouslySetInnerHTML = { __html: innerHtml(node, options) }; + } + return createElement(element.tagName, props); +} + +/** + * Renders a hast tree with React only on the path to elements that need a component: subtrees + * without one become static HTML, which the browser builds without React reconciling each node. + */ +export function renderHastWithIslands(tree: Root, options: MarkdownIslandOptions): ReactNode { + // The same elements again let React skip the block; islands still follow their context. + let signature = options.variant; + const plan: Plan = { islands: new Set(), ancestors: new Set() }; + const visit = (node: Root | Element): boolean => { + let below = false; + for (const child of node.children) { + if (child.type !== "element") continue; + const island = options.isIsland(child); + signature += island ? "1" : "0"; + if (island) { + plan.islands.add(child); + below = true; + continue; + } + if (visit(child)) { + plan.ancestors.add(child); + below = true; + } + } + return below; + }; + visit(tree); + const cached = renderedTrees.get(tree); + if (cached?.signature === signature && cached.components === options.components) { + return cached.node; + } + const node = tree.children.map((child, index) => renderContent(child, index, options, plan)); + renderedTrees.set(tree, { signature, components: options.components, node }); + return node; +} + +const renderedTrees = new WeakMap< + Root, + { signature: string; components: Partial; node: ReactNode } +>(); + +export function withProperties(node: Element, properties: Properties): Element { + return { ...node, properties: { ...node.properties, ...properties } }; +} diff --git a/apps/web/src/components/chat/markdownRenderer.test.tsx b/apps/web/src/components/chat/markdownRenderer.test.tsx index f15fe49584aea..a9a60c545b37b 100644 --- a/apps/web/src/components/chat/markdownRenderer.test.tsx +++ b/apps/web/src/components/chat/markdownRenderer.test.tsx @@ -1,88 +1,41 @@ -import { - CHAT_MARKDOWN_REHYPE_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS, -} from "@t3tools/shared/markdownPipeline"; import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; import { describe, expect, it } from "vite-plus/test"; -import { createIncrementalMarkdownPlugin } from "../../markdown-incremental"; import { createMarkdownRenderer } from "./markdownRenderer"; // Visible in the markup, so every URL attribute must pass through it. const urlTransform = (url: string) => `${url}#seen`; describe("createMarkdownRenderer", () => { - const render = createMarkdownRenderer({ - remarkPlugins: CHAT_MARKDOWN_REMARK_PLUGINS, - rehypePlugins: CHAT_MARKDOWN_REHYPE_PLUGINS, + const renderer = createMarkdownRenderer({ + markdown: { math: false, breaks: false, escapeHtml: false, insights: false, extensions: {} }, components: {}, urlTransform, }); + const render = (text: string) => renderer.element(renderer.parse(text)); + const renderAndRemember = (text: string) => { + const entry = renderer.parse(text); + renderer.remember(text, entry); + return renderer.element(entry); + }; - it.each([ - '# Title\n\nText with `code`, **bold**, [a link](https://example.com "t") and https://bare.example.com.', - "![shot](./shot.png) and [file](file:///C:/repo/a.ts) and [bad](javascript:alert(1))", - "
More\n\nHidden bold \n\n
", - "| a | b |\n| - | - |\n|
| [x](#frag) |\n\n- [ ] task\n- [x] done", - '```ts title="a.ts"\nconst a = 1;\n```\n\n> [!WARNING]\n> careful bare', - "Footnote[^1] and ~~strike~~\n\n[^1]: the note", - // Each GFM construct the parser skips when its text cannot match, next to one that can. - "Mail me@example.com, see www.example.com and HTTPS://example.com/a, not [x](https://y.z).", - "a.b-c_d+e@x.io and @user\n\n`me@x.io` ", - "A table without pipes\n:--", - "> | quoted |\n> | - |\n> | body |\n\n- [ ] open\n- [X] done", - "Escaped www\\.example.com and me@example.com", - "\ufeffA byte order mark\n\n| a |\n| - |\n| b |", - "> - | a |\r\n> | - |\r\n> | me@x.io |\r\n\n-\t[ ] tab\n\n ~~lazy~~", - ])("renders what react-markdown renders: %j", (source) => { - const expected = renderToStaticMarkup( - - {source} - , + it("passes every URL attribute through the transform", () => { + const html = renderToStaticMarkup( + render('![shot](./shot.png) and [a link](https://example.com "t") and '), ); - const element = render(source); - expect(renderToStaticMarkup(element)).toBe(expected); - render.remember(source, element); - expect(render(source)).toBe(element); + expect(html).toContain('src="./shot.png#seen"'); + expect(html).toContain('href="https://example.com#seen"'); + expect(html).toContain('src="b.png#seen"'); }); - it("renders what react-markdown renders while a reply streams through the incremental parser", () => { - const reply = - "```ts\nconst a = 1;\n```\n\n| a | b |\n| - | - |\n| me@x.io | www.x.io |\n\nDone ~~now~~."; - // As ChatMarkdown streams: one incremental plugin for the reply, a fresh renderer per update. - const incremental = createIncrementalMarkdownPlugin(); - for (let end = 1; end <= reply.length; end++) { - const source = reply.slice(0, end); - const streamed = createMarkdownRenderer({ - remarkPlugins: [...CHAT_MARKDOWN_REMARK_PLUGINS, incremental], - rehypePlugins: CHAT_MARKDOWN_REHYPE_PLUGINS, - components: {}, - urlTransform, - })(source); - expect(renderToStaticMarkup(streamed)).toBe( - renderToStaticMarkup( - - {source} - , - ), - ); - } + it("reuses a remembered message's element", () => { + const element = renderAndRemember("# Title\n\nText with `code` and **bold**."); + expect(render("# Title\n\nText with `code` and **bold**.")).toBe(element); }); it("keeps cached messages when one far larger than the cache is rendered", () => { - const element = render("Kept *message*"); - render.remember("Kept *message*", element); - const large = "x".repeat(600_000); - render.remember(large, render(large)); + const element = renderAndRemember("Kept *message*"); + renderAndRemember("x".repeat(600_000)); expect(render("Kept *message*")).toBe(element); }); }); diff --git a/apps/web/src/components/chat/markdownRenderer.ts b/apps/web/src/components/chat/markdownRenderer.ts index 9637d68e8f158..c2aa499a9583d 100644 --- a/apps/web/src/components/chat/markdownRenderer.ts +++ b/apps/web/src/components/chat/markdownRenderer.ts @@ -3,18 +3,13 @@ import { toJsxRuntime, type Components } from "hast-util-to-jsx-runtime"; import { urlAttributes } from "html-url-attributes"; import type { ReactElement } from "react"; import { Fragment, jsx, jsxs } from "react/jsx-runtime"; -import remarkParse from "remark-parse"; -import remarkRehype from "remark-rehype"; -import { type PluggableList, unified } from "unified"; -import { VFile } from "vfile"; -import { remarkParseWithoutUnusedSyntax } from "./markdownSyntaxGates"; +import { wordsHast, type WordsHastOptions } from "../../markdown/wordsHast"; export type MarkdownUrlTransform = (url: string, key: string, node: Element) => string; interface MarkdownRendererOptions { - readonly remarkPlugins: PluggableList; - readonly rehypePlugins: PluggableList; + readonly markdown: WordsHastOptions; readonly components: Partial; readonly urlTransform: MarkdownUrlTransform; } @@ -23,7 +18,11 @@ interface MarkdownRendererOptions { // reuses one instead of parsing again. Parsing is most of the cost of rendering markdown. // An element and the hast it keeps hold about 20 bytes per source character, so ~10 MB. const MAX_CACHED_CHARS = 500_000; -const rendered = new Map(); +interface Rendered { + readonly tree: Root; + element?: ReactElement; +} +const rendered = new Map(); let cachedChars = 0; let nextRendererId = 0; @@ -31,10 +30,10 @@ let nextRendererId = 0; const ENTRY_OVERHEAD_CHARS = 200; const entrySize = (key: string) => key.length + ENTRY_OVERHEAD_CHARS; -function remember(key: string, element: ReactElement) { +function remember(key: string, entry: Rendered) { // One huge message would otherwise evict everything else. if (entrySize(key) > MAX_CACHED_CHARS / 4) return; - rendered.set(key, element); + rendered.set(key, entry); cachedChars += entrySize(key); for (const oldest of rendered.keys()) { if (cachedChars <= MAX_CACHED_CHARS) break; @@ -43,32 +42,18 @@ function remember(key: string, element: ReactElement) { } } -/** Renders markdown as react-markdown does, with one processor per plugin set. */ +/** Renders markdown with Words, keeping one parse cache per option set. */ export function createMarkdownRenderer({ - remarkPlugins, - rehypePlugins, + markdown, components, urlTransform, }: MarkdownRendererOptions) { - const processor = unified() - .use(remarkParse) - .use(remarkParseWithoutUnusedSyntax) - .use(remarkPlugins) - .use(remarkRehype, { allowDangerousHtml: true }) - .use(rehypePlugins) - .freeze(); const keyPrefix = `${nextRendererId++}\u0000`; - // Literal raw HTML that survived the rehype plugins, and URL attributes, as react-markdown treats them. + // URL attributes, as react-markdown transformed them. const prepare = (node: Nodes) => { if (!("children" in node)) return; - const { children } = node; - for (let index = 0; index < children.length; index++) { - const child = children[index]!; - if (child.type === "raw") { - children[index] = { type: "text", value: child.value }; - continue; - } + for (const child of node.children) { if (child.type !== "element") continue; const { properties } = child; for (const key in properties) { @@ -82,7 +67,7 @@ export function createMarkdownRenderer({ } }; - const render = (text: string): ReactElement => { + const parse = (text: string): Rendered => { const key = keyPrefix + text; const cached = rendered.get(key); if (cached !== undefined) { @@ -91,24 +76,27 @@ export function createMarkdownRenderer({ rendered.set(key, cached); return cached; } - const file = new VFile(text); - const tree = processor.runSync(processor.parse(file), file) as Root; + const tree = wordsHast(text, markdown); prepare(tree); - return toJsxRuntime(tree, { - Fragment, - components, - ignoreInvalidStyle: true, - jsx, - jsxs, - passKeys: true, - passNode: true, - }); + return { tree }; }; - return Object.assign(render, { - remember(text: string, element: ReactElement) { + return { + /** A cached entry, or a fresh one that `remember` can keep. Cached trees are shared, so callers must not change them. */ + parse, + element: (entry: Rendered): ReactElement => + (entry.element ??= toJsxRuntime(entry.tree, { + Fragment, + components, + ignoreInvalidStyle: true, + jsx, + jsxs, + passKeys: true, + passNode: true, + })), + remember(text: string, entry: Rendered) { const key = keyPrefix + text; - if (!rendered.has(key)) remember(key, element); + if (!rendered.has(key)) remember(key, entry); }, - }); + }; } diff --git a/apps/web/src/components/chat/markdownStreamBlocks.test.tsx b/apps/web/src/components/chat/markdownStreamBlocks.test.ts similarity index 81% rename from apps/web/src/components/chat/markdownStreamBlocks.test.tsx rename to apps/web/src/components/chat/markdownStreamBlocks.test.ts index 38ecff7666508..b89940489ec32 100644 --- a/apps/web/src/components/chat/markdownStreamBlocks.test.tsx +++ b/apps/web/src/components/chat/markdownStreamBlocks.test.ts @@ -1,32 +1,19 @@ -import { - CHAT_MARKDOWN_REHYPE_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS, - remarkAssistantInsights, -} from "@t3tools/shared/markdownPipeline"; -import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; -import remarkMath from "remark-math"; -import type { PluggableList } from "unified"; +import { toHtml } from "hast-util-to-html"; import { describe, expect, it } from "vite-plus/test"; +import { wordsHast } from "~/markdown/wordsHast"; import { splitMarkdownBlocks } from "./markdownStreamBlocks"; -import { rehypeHeadingIds } from "./markdownFragments"; - -const MATH_PLUGINS: PluggableList = [[remarkMath, { singleDollarTextMath: true }]]; // Whitespace between top-level blocks collapses in the rendered message. const renderMarkdown = (source: string, math = false) => - renderToStaticMarkup( - - {source} - , + toHtml( + wordsHast(source, { + math, + breaks: false, + escapeHtml: false, + insights: source.includes("★ Insight"), + extensions: {}, + }), ) .replace(/>\s+<") .trim(); diff --git a/apps/web/src/components/chat/markdownSyntaxGates.ts b/apps/web/src/components/chat/markdownSyntaxGates.ts deleted file mode 100644 index 57587a51b9d13..0000000000000 --- a/apps/web/src/components/chat/markdownSyntaxGates.ts +++ /dev/null @@ -1,204 +0,0 @@ -import type { Nodes as MdastNodes } from "mdast"; -import { - type Extension as MdastExtension, - fromMarkdown, - type Options as FromMarkdownOptions, - type Transform, -} from "mdast-util-from-markdown"; -import { combineExtensions } from "micromark-util-combine-extensions"; -import type { Construct, Extension, TokenizeContext } from "micromark-util-types"; -import type { Processor } from "unified"; - -// A table needs a delimiter row: dashes with a `|` or `:`, after any `>` or indent. -// One character class per pattern: overlapping ones backtrack quadratically on a run of dashes. -const DELIMITER_LINE = /^[ \t>|:-]+$/gm; -const isDelimiterRow = (line: string) => line.includes("-") && /[|:]/.test(line); -const NEXT_LINE = /[^\r\n]*(?:\r\n?|\n)([^\r\n]*)/y; - -function hasDelimiterRow(text: string) { - for (const [line] of text.matchAll(DELIMITER_LINE)) if (isDelimiterRow(line)) return true; - return false; -} -const PROTOCOL = /https?:\/\//iy; -const WWW = /www\./iy; -const EMAIL_ATEXT = /[\w+.-]*@/y; - -const matchesAt = (pattern: RegExp, text: string, offset: number) => { - pattern.lastIndex = offset; - return pattern.test(text); -}; - -interface Gate { - readonly names: ReadonlyArray; - /** False when the construct cannot match anywhere in the text. */ - readonly inText: (text: string) => boolean; - /** False when it cannot start at this offset, which keeps micromark from trying it there. */ - readonly at?: (context: TokenizeContext, text: string, offset: number) => boolean; -} - -// micromark tries these at every candidate character: email autolinks at every word, tables -// at every line. That is most of what GFM adds to a parse, and most texts cannot match them. -const GATES: ReadonlyArray = [ - { - names: ["emailAutolink"], - inText: (text) => text.includes("@"), - at: (_, text, offset) => matchesAt(EMAIL_ATEXT, text, offset), - }, - { - names: ["protocolAutolink"], - inText: (text) => /https?:\/\//i.test(text), - at: (_, text, offset) => matchesAt(PROTOCOL, text, offset), - }, - { - names: ["wwwAutolink"], - inText: (text) => /www\./i.test(text), - at: (_, text, offset) => matchesAt(WWW, text, offset), - }, - { - names: ["table"], - inText: hasDelimiterRow, - at: (context, text, offset) => { - NEXT_LINE.lastIndex = offset; - const nextLine = NEXT_LINE.exec(text)?.[1]; - return (nextLine !== undefined && hasDelimiterRow(nextLine)) || continuesTable(context); - }, - }, - { names: ["strikethrough"], inText: (text) => text.includes("~") }, - { - names: ["gfmFootnoteCall", "gfmPotentialFootnoteCall", "gfmFootnoteDefinition"], - inText: (text) => text.includes("[^"), - }, - { names: ["tasklistCheck"], inText: (text) => /\[[\sxX]\]/.test(text) }, -]; - -// A body row follows the head or another row. Mirrors `start` in micromark-extension-gfm-table's -// lib/syntax.js: recheck it when that package changes. -function continuesTable({ events }: TokenizeContext) { - let index = events.length - 1; - while (index > -1 && /^(?:lineEnding|linePrefix)$/.test(events[index]![1].type)) index--; - // The table extension's token types are not in micromark's map unless its types are loaded. - const tail: string | undefined = events[index]?.[1].type; - return tail === "tableHead" || tail === "tableRow"; -} - -let parsing = ""; -const gated = new WeakMap(); - -function gatedConstruct(construct: Construct, gate: Gate): Construct { - const at = gate.at; - if (!at) return construct; - let wrapped = gated.get(construct); - if (!wrapped) { - const { previous, tokenize } = construct; - wrapped = { - ...construct, - tokenize(effects, ok, nok) { - return at(this, parsing, this.now().offset) ? tokenize.call(this, effects, ok, nok) : nok; - }, - ...(previous && { - previous(code) { - return previous.call(this, code) && at(this, parsing, this.now().offset); - }, - }), - }; - gated.set(construct, wrapped); - } - return wrapped; -} - -type ConstructMap = Record; - -function gateExtension(extension: Extension, absent: ReadonlySet): Extension { - const gateOf = (name: string | undefined) => - GATES.find((gate) => name && gate.names.includes(name)); - const result: Record = {}; - for (const [field, value] of Object.entries(extension)) { - if (field === "disable" || field === "attentionMarkers" || !value) { - result[field] = value; - continue; - } - const map: ConstructMap = {}; - for (const [code, entry] of Object.entries(value as ConstructMap)) { - const kept = (Array.isArray(entry) ? entry : [entry]).flatMap((construct) => { - const gate = construct && gateOf(construct.name); - if (!construct || !gate) return construct ? [construct] : []; - return absent.has(gate) ? [] : [gatedConstruct(construct, gate)]; - }); - if (kept.length > 0) map[code] = Array.isArray(entry) ? kept : kept[0]; - } - result[field] = map; - } - return result as Extension; -} - -type MdastExtensions = NonNullable; - -// Merged once, as mdast-util-from-markdown merges them on every call: lists in order, handlers by key. -function mergeMdastExtensions(extensions: MdastExtensions): MdastExtension { - const merged = { - canContainEols: [] as string[], - enter: {}, - exit: {}, - transforms: [] as Transform[], - }; - for (const extension of extensions.flat()) { - merged.canContainEols.push(...(extension.canContainEols ?? [])); - Object.assign(merged.enter, extension.enter); - Object.assign(merged.exit, extension.exit); - // GFM looks for autolink literals again in the decoded text outside links, so `www\.x.io` - // links too. Most texts have URLs only in link destinations and code, where it finds nothing. - for (const transform of extension.transforms ?? []) { - merged.transforms.push( - extension.enter?.literalAutolink - ? (tree) => (hasAutolinkText(tree) ? transform(tree) : undefined) - : transform, - ); - } - } - return merged; -} - -const AUTOLINK_TEXT = /@|https?:\/\/|www\./i; - -function hasAutolinkText(node: MdastNodes): boolean { - if (node.type === "text") return AUTOLINK_TEXT.test(node.value); - if (node.type === "link" || node.type === "linkReference" || !("children" in node)) return false; - return node.children.some(hasAutolinkText); -} - -/** - * Parses as remark-parse does, without the syntax extension constructs that cannot match the - * text. Same tree, in about half the time. - */ -function attachParserWithoutUnusedSyntax(this: Processor) { - const data = this.data(); - const byMask = new Map(); - let mdastExtensions: MdastExtension[] | undefined; - this.parser = (document) => { - let mask = 0; - GATES.forEach((gate, index) => { - if (!gate.inText(document)) mask |= 1 << index; - }); - let extensions = byMask.get(mask); - if (!extensions) { - const absent = new Set(GATES.filter((_, index) => mask & (1 << index))); - extensions = [ - combineExtensions( - (data.micromarkExtensions ?? []).map((extension) => gateExtension(extension, absent)), - ), - ]; - byMask.set(mask, extensions); - } - mdastExtensions ??= [mergeMdastExtensions(data.fromMarkdownExtensions ?? [])]; - const outer = parsing; - // Gates read micromark offsets, which skip a leading byte order mark. - parsing = document.charCodeAt(0) === 0xfeff ? document.slice(1) : document; - try { - return fromMarkdown(document, { ...data.settings, extensions, mdastExtensions }); - } finally { - parsing = outer; - } - }; -} - -export const remarkParseWithoutUnusedSyntax = attachParserWithoutUnusedSyntax; diff --git a/apps/web/src/components/chat/markdownTextDirection.ts b/apps/web/src/components/chat/markdownTextDirection.ts index ffdbde76c1148..a4c78d3342754 100644 --- a/apps/web/src/components/chat/markdownTextDirection.ts +++ b/apps/web/src/components/chat/markdownTextDirection.ts @@ -1,4 +1,4 @@ -import { textDirection } from "~/textDirection"; +import { LETTER, RTL_LETTER, textDirection } from "~/textDirection"; type HastNode = { type?: string; @@ -57,11 +57,32 @@ function isolateInlineCode(node: HastNode): void { */ export function rehypeTextDirection() { return (tree: HastNode) => { - for (const block of tree.children ?? []) { - if (block.type !== "element" || block.tagName === "pre") continue; - const dir = textDirection(proseText(block)); - if (dir) block.properties = { ...block.properties, dir }; - } + blockTextDirections(tree); isolateInlineCode(tree); }; } + +/** Each top-level block's direction, from its prose; an RTL letter decides as textDirection does. */ +function blockTextDirections(tree: HastNode) { + for (const block of tree.children ?? []) { + if (block.type !== "element" || block.tagName === "pre") continue; + const dir = scriptOf(block) === "rtl" ? textDirection(proseText(block)) : scriptOf(block); + if (dir) block.properties = { ...block.properties, dir }; + } +} + +/** "rtl" when any prose letter is right-to-left; otherwise what textDirection would say. */ +function scriptOf(node: HastNode): "rtl" | "ltr" | undefined { + let found: "ltr" | undefined; + const visit = (current: HastNode): boolean => { + if (current.type === "text") { + const value = current.value ?? ""; + if (RTL_LETTER.test(value)) return true; + if (!found && LETTER.test(value)) found = "ltr"; + return false; + } + if (current.tagName === "code") return false; + return (current.children ?? []).some(visit); + }; + return visit(node) ? "rtl" : found; +} diff --git a/apps/web/src/components/chat/preparingComposerImages.test.ts b/apps/web/src/components/chat/preparingComposerImages.test.ts new file mode 100644 index 0000000000000..29a0f80f52386 --- /dev/null +++ b/apps/web/src/components/chat/preparingComposerImages.test.ts @@ -0,0 +1,58 @@ +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { EnvironmentId, ProviderDriverKind, ThreadId } from "@t3tools/contracts"; +import { expect, it } from "vite-plus/test"; + +import { composerTargetKey, useComposerDraftStore } from "../../composerDraftStore"; +import { + addPreparingComposerImages, + cancelHeldComposerSend, + cancelPreparingComposerImages, + holdComposerSend, + joinPreparedImagesToDraft, + removePreparingComposerImages, +} from "./preparingComposerImages"; + +function preparingImage(id: string) { + return { id, name: `${id}.png`, file: new File(["png"], `${id}.png`), hidden: false }; +} + +it("holds a message send until its images join the draft, and cancels on edit, cancel, or new paste", async () => { + const draftTarget = scopeThreadRef(EnvironmentId.make("environment-held"), ThreadId.make("held")); + const target = composerTargetKey(draftTarget); + const drafts = useComposerDraftStore.getState(); + using _store = { + [Symbol.dispose]: () => { + cancelPreparingComposerImages(target); + drafts.clearComposerContent(draftTarget); + }, + }; + drafts.setPrompt(draftTarget, "check"); + expect(holdComposerSend(draftTarget)).toBeNull(); + + // Two pastes compress separately; the first joining the draft is not an edit. + addPreparingComposerImages(target, [preparingImage("first")]); + addPreparingComposerImages(target, [preparingImage("second")]); + const held = holdComposerSend(draftTarget); + await expect(holdComposerSend(draftTarget)).resolves.toEqual({ status: "cancelled" }); + removePreparingComposerImages(target, new Set(["first"])); + joinPreparedImagesToDraft(() => drafts.setPrompt(draftTarget, "check first")); + removePreparingComposerImages(target, new Set(["second"])); + await expect(held).resolves.toEqual({ status: "ready" }); + + for (const cancel of [ + () => drafts.setPrompt(draftTarget, "check again"), + () => + drafts.setProviderModelOptions(draftTarget, ProviderDriverKind.make("codex"), [ + { id: "reasoningEffort", value: "high" }, + ]), + () => cancelHeldComposerSend(target), + () => addPreparingComposerImages(target, [preparingImage("added-mid-wait")]), + () => removePreparingComposerImages(target, new Set(["later"]), { cancelSubmission: true }), + ]) { + addPreparingComposerImages(target, [preparingImage("later")]); + const cancelled = holdComposerSend(draftTarget); + cancel(); + await expect(cancelled).resolves.toEqual({ status: "cancelled" }); + cancelPreparingComposerImages(target); + } +}); diff --git a/apps/web/src/components/chat/preparingComposerImages.ts b/apps/web/src/components/chat/preparingComposerImages.ts index 47d24ab5f7a89..951e7f661221c 100644 --- a/apps/web/src/components/chat/preparingComposerImages.ts +++ b/apps/web/src/components/chat/preparingComposerImages.ts @@ -3,7 +3,13 @@ import type { ScopedThreadRef } from "@t3tools/contracts"; import { useEffect, useRef } from "react"; import { create } from "zustand"; +import { + composerTargetKey, + type ComposerThreadTarget, + useComposerDraftStore, +} from "../../composerDraftStore"; import { useStableCallback } from "../../hooks/useStableCallback"; +import { composerDraftContentChanged } from "./composerSend.logic"; export interface PreparingComposerImage { readonly id: string; @@ -69,6 +75,9 @@ export function addPreparingComposerImages( targetKey: string, images: ReadonlyArray, ): void { + if (images.length > 0) { + heldSends.get(targetKey)?.({ status: "cancelled" }); + } usePreparingComposerImageStore.setState((state) => ({ byTargetKey: { ...state.byTargetKey, @@ -116,8 +125,89 @@ export function removePreparingComposerImages( // Bumped on cancel so a send held for the cancelled images is dropped rather than released. const cancelGenerations = new Map(); +export type HeldComposerSendResult = + | { readonly status: "ready" } + | { readonly status: "cancelled" }; + +const heldSends = new Map void>(); +const useHeldSendStore = create<{ readonly targetKeys: Readonly> }>(() => ({ + targetKeys: {}, +})); +let preparedImagesJoiningDraft = false; + function invalidatePendingSubmit(targetKey: string) { cancelGenerations.set(targetKey, (cancelGenerations.get(targetKey) ?? 0) + 1); + heldSends.get(targetKey)?.({ status: "cancelled" }); +} + +/** Whether a send from the target's draft is waiting on its images to finish preparing. */ +export function useComposerSendHeld(targetKey: string): boolean { + return useHeldSendStore((state) => state.targetKeys[targetKey] === true); +} + +export function cancelHeldComposerSend(targetKey: string): void { + heldSends.get(targetKey)?.({ status: "cancelled" }); +} + +/** Inserts finished images into the draft without counting as an edit to a held send. */ +export function joinPreparedImagesToDraft(insert: () => T): T { + preparedImagesJoiningDraft = true; + try { + return insert(); + } finally { + preparedImagesJoiningDraft = false; + } +} + +/** + * Holds a send made while the draft still has images compressing. Resolves ready once they join + * the draft, or cancelled if the draft is edited or the send cancelled. Null means nothing needs + * to wait. Lives outside the composer so leaving the thread still completes the send. + */ +export function holdComposerSend( + draftTarget: ComposerThreadTarget, +): Promise | null { + const targetKey = composerTargetKey(draftTarget); + if (countPreparingComposerImages(targetKey) === 0) return null; + if (heldSends.has(targetKey)) return Promise.resolve({ status: "cancelled" }); + return new Promise((resolve) => { + let draft = useComposerDraftStore.getState().getComposerDraft(draftTarget); + const settle = (result: HeldComposerSendResult) => { + if (heldSends.get(targetKey) !== settle) return; + heldSends.delete(targetKey); + stopWatchingImages(); + stopWatchingDraft(); + useHeldSendStore.setState((state) => { + const targetKeys = { ...state.targetKeys }; + delete targetKeys[targetKey]; + return { targetKeys }; + }); + resolve(result); + }; + heldSends.set(targetKey, settle); + const stopWatchingImages = usePreparingComposerImageStore.subscribe((state) => { + if (state.byTargetKey[targetKey]) return; + // Let joinPreparedImagesToDraft finish inserting compressed images in this tick first. + queueMicrotask(() => settle({ status: "ready" })); + }); + const stopWatchingDraft = useComposerDraftStore.subscribe((state) => { + const next = state.getComposerDraft(draftTarget); + if ( + !preparedImagesJoiningDraft && + (composerDraftContentChanged(draft, next) || + draft?.modelSelectionByProvider !== next?.modelSelectionByProvider || + draft?.activeProvider !== next?.activeProvider || + draft?.runtimeMode !== next?.runtimeMode || + draft?.interactionMode !== next?.interactionMode) + ) { + settle({ status: "cancelled" }); + } + draft = next; + }); + useHeldSendStore.setState((state) => ({ + targetKeys: { ...state.targetKeys, [targetKey]: true }, + })); + }); } /** Drops every image still preparing for the target, so its compression result is discarded. */ diff --git a/apps/web/src/components/chat/threadFindHighlights.ts b/apps/web/src/components/chat/threadFindHighlights.ts index c8ce0b31b9c9e..fe6a3ba5d3056 100644 --- a/apps/web/src/components/chat/threadFindHighlights.ts +++ b/apps/web/src/components/chat/threadFindHighlights.ts @@ -1,6 +1,6 @@ import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { useEffect, useEffectEvent, useRef } from "react"; -import { THREAD_FIND_BLOCK_TAGS } from "@t3tools/shared/threadFindText"; +import { THREAD_FIND_BLOCK_TAGS } from "@t3tools/shared/threadFindBlockTags"; import { observeResize } from "~/lib/observeResize"; diff --git a/apps/web/src/components/chat/timelineMinimapItems.ts b/apps/web/src/components/chat/timelineMinimapItems.ts index 151a02d88175e..57f6229c99526 100644 --- a/apps/web/src/components/chat/timelineMinimapItems.ts +++ b/apps/web/src/components/chat/timelineMinimapItems.ts @@ -4,10 +4,9 @@ import { isAttachmentOnlyBootstrapPrompt, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; -import type { Nodes } from "mdast"; -import remarkGfm from "remark-gfm"; -import remarkParse from "remark-parse"; -import { unified } from "unified"; +import type { Nodes } from "hast"; + +import { markdownTree } from "~/markdown/wordsHast"; import type { MessagesTimelineRow } from "./MessagesTimeline.logic"; @@ -58,50 +57,49 @@ function resolveFinalAssistantTextForTurn( return finalAssistantText; } -const markdownPreviewParser = unified().use(remarkParse).use(remarkGfm).freeze(); - -const INLINE_PARENT_TYPES = new Set([ - "paragraph", - "heading", - "tableCell", - "emphasis", +// Elements whose children run together; every other element is separated by a space. +const INLINE_PARENTS = new Set([ + "p", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "td", + "th", + "em", "strong", - "delete", - "link", - "linkReference", + "del", + "a", + "code", + "span", + "sup", + "sub", ]); function markdownNodeText(node: Nodes): string { - if (node.type === "html") { - return node.value - .replace(/|$)/g, "") - .replace(/<\/?([a-z][\w-]*)(?:[^"'<>]|"[^"]*"|'[^']*')*>/gi, (_, tag: string) => - /^(?:address|article|aside|blockquote|br|dd|details|div|dl|dt|figcaption|figure|footer|h[1-6]|header|hr|li|main|nav|ol|p|pre|section|summary|table|tbody|td|th|thead|tr|ul)$/i.test( - tag, - ) - ? " " - : "", - ); - } - if (node.type === "break") return " "; - if ("value" in node) return node.value; - if (node.type === "image" || node.type === "imageReference") return node.alt ?? ""; - if (!("children" in node)) return ""; - const separator = INLINE_PARENT_TYPES.has(node.type) ? "" : " "; + if (node.type === "text") return node.value; + if (node.type === "element" && node.tagName === "br") return " "; + if (node.type === "element" && node.tagName === "img") return String(node.properties.alt ?? ""); + if (node.type !== "element" && node.type !== "root") return ""; + const separator = node.type === "element" && INLINE_PARENTS.has(node.tagName) ? "" : " "; const text = node.children.map(markdownNodeText).join(separator); // A thread autolink's only text is its URL. - return node.type === "link" && parseThreadLinkHref(text) !== null ? "a thread" : text; + return node.type === "element" && node.tagName === "a" && parseThreadLinkHref(text) !== null + ? "a thread" + : text; } /** Markdown as one line of the text it renders, without markup or link targets. */ export function markdownPlainText(markdown: string): string { - return markdownNodeText(markdownPreviewParser.parse(markdown)).replace(/\s+/g, " ").trim(); + return markdownNodeText(markdownTree(markdown)).replace(/\s+/g, " ").trim(); } // The tooltip shows a few lines; bound parsing work for long messages and streaming responses. function markdownMinimapPreview(markdown: string | null) { if (markdown === null) return null; - const compact = markdownNodeText(markdownPreviewParser.parse(markdown.slice(0, 1_500))) + const compact = markdownNodeText(markdownTree(markdown.slice(0, 1_500))) .replace(/\s+/g, " ") .trim(); return compact.length > 0 ? compact : null; diff --git a/apps/web/src/components/chat/useComposerAttachmentIntake.ts b/apps/web/src/components/chat/useComposerAttachmentIntake.ts index cfd8fde657713..08b362b866e1a 100644 --- a/apps/web/src/components/chat/useComposerAttachmentIntake.ts +++ b/apps/web/src/components/chat/useComposerAttachmentIntake.ts @@ -57,6 +57,7 @@ import { addPreparingComposerImages, getPreparingComposerImages, isPreparingComposerImage, + joinPreparedImagesToDraft, movedPreparingImageThread, removePreparingComposerImages, } from "./preparingComposerImages"; @@ -338,16 +339,19 @@ export function useComposerAttachmentIntake(input: { })); const unrestoredImageNames: string[] = []; const draftStore = useComposerDraftStore.getState(); - const storedImageIds = new Set( - movedThread - ? draftStore.addImages(movedThread, nextImages, { - onCapacityExceeded: (image) => unrestoredImageNames.push(image.name), - }) - : nextImages.length === 1 && nextImages[0] - ? addComposerImage(nextImages[0]) - : nextImages.length > 1 - ? addComposerImagesToDraft(nextImages) - : [], + const storedImageIds = joinPreparedImagesToDraft( + () => + new Set( + movedThread + ? draftStore.addImages(movedThread, nextImages, { + onCapacityExceeded: (image) => unrestoredImageNames.push(image.name), + }) + : nextImages.length === 1 && nextImages[0] + ? addComposerImage(nextImages[0]) + : nextImages.length > 1 + ? addComposerImagesToDraft(nextImages) + : [], + ), ); // Keep the placeholders until the draft decides whether the recovered images fit, // so a held send can be cancelled before the last placeholder disappears. @@ -365,10 +369,12 @@ export function useComposerAttachmentIntake(input: { } if (storedImages.length > 0 && imageAttachmentsGetChips && !movedThread) { insertedAny = - insertAttachmentReferences( - storedImages.map(imageContextReference), - undefined, - pendingInsertion, + joinPreparedImagesToDraft(() => + insertAttachmentReferences( + storedImages.map(imageContextReference), + undefined, + pendingInsertion, + ), ) || insertedAny; } // Only failures are reported here. Success must not pass `null`: by diff --git a/apps/web/src/components/chat/useComposerSelection.ts b/apps/web/src/components/chat/useComposerSelection.ts index 409b394be009a..90d3ca70bf2fb 100644 --- a/apps/web/src/components/chat/useComposerSelection.ts +++ b/apps/web/src/components/chat/useComposerSelection.ts @@ -26,10 +26,12 @@ import { threadHasStarted, } from "../../lib/chatThreadActions"; import { + composerTargetKey, type DraftThreadEnvMode, isSameModel, useComposerDraftStore, } from "../../composerDraftStore"; +import { cancelHeldComposerSend } from "./preparingComposerImages"; import { getStartedThreadModelChangeBlockReason, deriveLockedProvider, @@ -104,6 +106,7 @@ export function useComposerSelection(input: ComposerSelectionInput) { const handleRuntimeModeChange = (mode: RuntimeMode) => { if (mode === runtimeMode) return; + cancelHeldComposerSend(composerTargetKey(composerDraftTarget)); setComposerDraftRuntimeMode(composerDraftTarget, mode); if (isLocalDraftThread) { setDraftThreadContext(composerDraftTarget, { runtimeMode: mode }); @@ -158,6 +161,7 @@ export function useComposerSelection(input: ComposerSelectionInput) { options?: { focusComposer?: boolean }, ) => { if (!activeThread) return; + cancelHeldComposerSend(composerTargetKey(composerDraftTarget)); const entry = providerStatuses.find((snapshot) => snapshot.instanceId === instanceId); const resolvedDriverKind = entry?.driver ?? null; if ( @@ -263,6 +267,7 @@ export function useComposerSelection(input: ComposerSelectionInput) { const onProviderModelSelectStable = useStableCallback(onProviderModelSelect); const onEnvModeChange = (mode: DraftThreadEnvMode) => { if (multipleModelSelections !== null) return; + cancelHeldComposerSend(composerTargetKey(composerDraftTarget)); if (canOverrideServerThreadEnvMode) { if (activeThread) setPendingServerThreadEnvModeEntry({ threadId: activeThread.id, mode }); scheduleComposerFocus(); @@ -286,6 +291,7 @@ export function useComposerSelection(input: ComposerSelectionInput) { // re-renders the branch toolbar and thread details panel with it. const activeThreadId = activeThread?.id; const onStartFromOriginChange = (nextStartFromOrigin: boolean) => { + cancelHeldComposerSend(composerTargetKey(composerDraftTarget)); if (canOverrideServerThreadEnvMode && activeThreadId !== undefined) { setPendingServerThreadStartFromOriginByThreadId((current) => current[activeThreadId] === nextStartFromOrigin diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index dc6a0d7e77ba4..34399d1b2f909 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -84,6 +84,7 @@ import { restoreFailedDraftThread, checkoutPullRequestUrlToLink, composerDraftHasUserContent, + composerTargetKey, type ComposerFileAttachment, type ComposerImageAttachment, type DraftThreadEnvMode, @@ -128,6 +129,7 @@ import { startAttachmentUpload, } from "../../lib/attachmentUploadQueue"; import { appAtomRegistry } from "../../rpc/atomRegistry"; +import { countPreparingComposerImages, holdComposerSend } from "./preparingComposerImages"; import { fileAttachmentCapabilityBlockReason } from "./composerAttachmentFiles"; import { useLinkedEnvironments } from "../../state/peerLinks"; import { readEnvironmentScope } from "../../state/session"; @@ -479,12 +481,13 @@ export function useComposerSend(input: ComposerSendInput) { e?.preventDefault(); // What the user pressed send on; uploads below can take a while, and a redirect must not // decline approvals for a draft that changed meanwhile. - const promptAtSend = detachedOverride ? detachedOverride.prompt : promptRef.current; + let promptAtSend = detachedOverride ? detachedOverride.prompt : promptRef.current; if ( usageLimitsOffered && usageLimitsKey !== null && !directAnnotation && !draftHasNonPromptContent(composerDraftTarget) && + countPreparingComposerImages(composerTargetKey(composerDraftTarget)) === 0 && isUsageLimitsCommand(promptAtSend) ) { if (openUsageLimits()) { @@ -497,9 +500,11 @@ export function useComposerSend(input: ComposerSendInput) { return; } - const sendCtx = detachedOverride + // Read before any wait; the composer on screen may belong to another thread after it. + let sendCtx = detachedOverride ? detachedOverride.sendContext : composerRef.current?.getSendContext(); + const isCurrentRouteThread = () => currentRouteThreadKeyRef.current === routeThreadKey; // `/side` beats an open question and a plan follow-up, which would send the text to main. const sideChatCommand = sendCtx && !directAnnotation && !queuedRunEdit.isEditing @@ -595,6 +600,28 @@ export function useComposerSend(input: ComposerSendInput) { ); return; } + const heldForImages = directAnnotation ? null : holdComposerSend(composerDraftTarget); + if (heldForImages) { + if ((await heldForImages).status === "cancelled") return; + const draftAfterHold = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget); + if (!draftAfterHold) return; + // A dictation sent after leaving the thread carries its transcript outside the draft. + promptAtSend = detachedOverride ? detachedOverride.prompt : draftAfterHold.prompt; + if (sendCtx) { + sendCtx = { + ...sendCtx, + prompt: promptAtSend, + images: draftAfterHold.images, + files: draftAfterHold.files, + terminalContexts: draftAfterHold.terminalContexts, + previewAnnotations: draftAfterHold.previewAnnotations, + reviewComments: draftAfterHold.reviewComments, + threadContexts: draftAfterHold.threadContexts, + environmentContexts: draftAfterHold.environmentContexts, + knowledgeContexts: draftAfterHold.knowledgeContexts ?? [], + }; + } + } const startDraftAttachmentUploads = ( attachments: ReadonlyArray, ) => { @@ -1214,7 +1241,6 @@ export function useComposerSend(input: ComposerSendInput) { effort: ctxSelectedPromptEffort, text: messageTextForSend || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, }); - const isCurrentRouteThread = () => currentRouteThreadKeyRef.current === routeThreadKey; if ( isCurrentRouteThread() && composerRef.current?.validateProviderInput(outgoingMessageText) === false @@ -1270,6 +1296,7 @@ export function useComposerSend(input: ComposerSendInput) { if (turnUsesAttachmentUploads) startDraftAttachmentUploads(composerAttachmentsSnapshot); if ( + isCurrentRouteThread() && multipleModelSelections === null && shouldDockDraftHeroForSubmission({ isDraftHeroState, activeThreadKey, submissionIntent }) && activeThreadKey @@ -1485,7 +1512,7 @@ export function useComposerSend(input: ComposerSendInput) { } if (sendQueuesBehindSetup) { setSetupQueueSendThreadKey(activeThreadKey); - } else { + } else if (isCurrentRouteThread()) { beginLocalDispatch({ preparingWorktree: multipleModelSelections !== null || Boolean(baseBranchForWorktree), submissionIntent: @@ -1903,7 +1930,7 @@ export function useComposerSend(input: ComposerSendInput) { setDockedDraftHeroThreadKey((currentThreadKey) => currentThreadKey === activeThreadKey ? null : currentThreadKey, ); - if (!sendQueuesBehindSetup) resetLocalDispatch(); + if (!sendQueuesBehindSetup && isCurrentRouteThread()) resetLocalDispatch(); } }; diff --git a/apps/web/src/components/chat/useProposedPlanSend.ts b/apps/web/src/components/chat/useProposedPlanSend.ts index eb945e3e056a4..77d896e4d8500 100644 --- a/apps/web/src/components/chat/useProposedPlanSend.ts +++ b/apps/web/src/components/chat/useProposedPlanSend.ts @@ -1,3 +1,4 @@ +import { msg, useMessages } from "gt-react"; import { AuthOrchestrationOperateScope, type EnvironmentId, @@ -78,6 +79,7 @@ interface PlanFollowUpSendInput extends PlanSendBase { * (which links the turn to the plan). Resolves whether the turn started. */ export function usePlanFollowUpSend(input: PlanFollowUpSendInput) { + const m = useMessages(); const { environmentId, routeThreadKey, @@ -224,7 +226,7 @@ export function usePlanFollowUpSend(input: PlanFollowUpSendInput) { const error = squashAtomCommandFailure(failure); setThreadError( threadIdForSend, - error instanceof Error ? error.message : "Failed to send plan follow-up.", + error instanceof Error ? error.message : m(msg("Failed to send plan follow-up.")), ); } sendInFlightRef.current = false; @@ -244,6 +246,7 @@ interface ImplementPlanInNewThreadInput extends PlanSendBase { * thread is deleted again if it cannot be started or opened. */ export function useImplementPlanInNewThread(input: ImplementPlanInNewThreadInput) { + const m = useMessages(); const { environmentId, routeThreadKey, @@ -382,11 +385,11 @@ export function useImplementPlanInNewThread(input: ImplementPlanInNewThreadInput toastManager.add( stackedThreadToast({ type: "error", - title: "Could not start implementation thread", + title: m(msg("Could not start implementation thread")), description: error instanceof Error ? error.message - : "An error occurred while creating the new thread.", + : m(msg("An error occurred while creating the new thread.")), }), ); } diff --git a/apps/web/src/components/codeExplorer/CodeExplorer.tsx b/apps/web/src/components/codeExplorer/CodeExplorer.tsx index fca18562f7d54..af37d043b060f 100644 --- a/apps/web/src/components/codeExplorer/CodeExplorer.tsx +++ b/apps/web/src/components/codeExplorer/CodeExplorer.tsx @@ -11,10 +11,12 @@ import type { } from "@t3tools/contracts"; import { ArrowLeftIcon, ExternalLinkIcon } from "lucide-react"; import { useState, type FormEvent } from "react"; +import { msg, T, useMessages } from "gt-react"; import { Button } from "~/components/ui/button"; import { Input } from "~/components/ui/input"; import { Toggle, ToggleGroup } from "~/components/ui/toggle-group"; +import type { MessageResolver } from "~/i18n/messages"; import { cn } from "~/lib/utils"; import { projectCode } from "~/state/projectCode"; import { useEnvironmentQuery } from "~/state/query"; @@ -78,11 +80,23 @@ function openLine(node: ExplorerNode): number { : node.symbol.startLine; } -function nodeDetail(node: ExplorerNode): string { - const hop = `${node.hop} ${node.hop === 1 ? "hop" : "hops"}`; - if (node.via === null) return hop; - const sites = node.via.sites > 1 ? ` · ${node.via.sites} call sites` : ""; - return `${hop} · ${GRADE_LABEL[node.via.grade]}${sites}`; +function nodeDetail(node: ExplorerNode, resolve: MessageResolver): string { + if (node.via === null) + return resolve(msg("{count, plural, one {{count} hop} other {{count} hops}}"), { + count: node.hop, + }); + const grade = resolve(GRADE_LABEL[node.via.grade]); + return node.via.sites > 1 + ? resolve( + msg( + "{count, plural, one {{count} hop} other {{count} hops}} · {grade} · {sites} call sites", + ), + { count: node.hop, grade, sites: node.via.sites }, + ) + : resolve(msg("{count, plural, one {{count} hop} other {{count} hops}} · {grade}"), { + count: node.hop, + grade, + }); } function worstCoverage(results: ReadonlyArray): ProjectCodeCoverage { @@ -96,12 +110,13 @@ function CallGraph(props: { readonly onRecenter: (symbol: ProjectCodeSymbol) => void; readonly onOpen: (path: string, line: number) => void; }) { + const m = useMessages(); const layout = layoutExplorer(props.model); return (
@@ -135,7 +150,7 @@ function CallGraph(props: { markerEnd="url(#code-explorer-arrow)" data-grade={edge.grade} > - {`${edge.kind} · ${GRADE_LABEL[edge.grade]}`} + {`${edge.kind} · ${m(GRADE_LABEL[edge.grade])}`} ))} @@ -148,8 +163,16 @@ function CallGraph(props: { type="button" aria-label={ isFocus - ? `Open ${node.symbol.name} at ${location}` - : `Re-center on ${node.symbol.name}, ${node.side === "callers" ? "caller" : "callee"} ${nodeDetail(node)}` + ? m(msg("Open {name} at {location}"), { name: node.symbol.name, location }) + : node.side === "callers" + ? m(msg("Re-center on {name}, caller {detail}"), { + name: node.symbol.name, + detail: nodeDetail(node, m), + }) + : m(msg("Re-center on {name}, callee {detail}"), { + name: node.symbol.name, + detail: nodeDetail(node, m), + }) } onClick={() => isFocus @@ -179,6 +202,7 @@ function SymbolList(props: { readonly onRecenter: (symbol: ProjectCodeSymbol) => void; readonly onOpen: (path: string, line: number) => void; }) { + const m = useMessages(); return (

@@ -196,14 +220,17 @@ function SymbolList(props: { props.onRecenter(node.symbol)} />

{submitted === null ? null : searchResult === null ? ( @@ -288,13 +325,13 @@ function PathQuery( pending error={search.error} onRetry={search.refresh} - pendingLabel="Searching symbols…" + pendingLabel={m(msg("Searching symbols…"))} /> ) : target === null ? ( searchResult.matches.length === 0 ? ( - No indexed symbol matches that search. + {m(msg("No indexed symbol matches that search."))} ) : ( -
    +
      {searchResult.matches.map(({ symbol }) => (
    • ) : ( @@ -327,34 +364,53 @@ function PathResult(props: { readonly to: ProjectCodeSymbol; readonly onRecenter: (symbol: ProjectCodeSymbol) => void; }) { + const m = useMessages(); const search = props.result.pathSearch; if (search === undefined) { - return This server cannot answer path queries.; + return {m(msg("This server cannot answer path queries."))}; } if (search.unresolvedEndpoint !== null) { const name = search.unresolvedEndpoint === "from" ? props.from.name : props.to.name; return ( {props.result.selection.state === "ambiguous" - ? `Several declarations match ${name}; the index cannot tell which one you mean.` - : `${name} is no longer in the index. Refresh after saving the file.`} + ? m(msg("Several declarations match {name}; the index cannot tell which one you mean."), { + name, + }) + : m(msg("{name} is no longer in the index. Refresh after saving the file."), { name })} ); } if (!search.found) { return (

      - {`No call path from ${props.from.name} to ${props.to.name} within ${search.maxDepth} hops (${search.visitedSymbols} symbols walked). That does not prove there is none.`} - {search.walkTruncated - ? " The walk stopped at its symbol budget before reaching that depth." - : ""} + {m( + msg( + "No call path from {from} to {to} within {depth} hops ({visited} symbols walked). That does not prove there is none.", + ), + { + from: props.from.name, + to: props.to.name, + depth: search.maxDepth, + visited: search.visitedSymbols, + }, + )} + {search.walkTruncated ? ( + <> + {" "} + The walk stopped at its symbol budget before reaching that depth. + + ) : null}

      ); } const nodes = new Map(props.result.nodes.map((node) => [node.id, node])); return (
        {props.result.nodes.slice(0, 1).map((node) => ( @@ -362,7 +418,7 @@ function PathResult(props: { props.onRecenter(node)} /> @@ -375,7 +431,11 @@ function PathResult(props: { props.onRecenter(node)} /> @@ -396,6 +456,7 @@ export default function CodeExplorer( readonly onOpen: (path: string, line: number) => void; }, ) { + const m = useMessages(); const config = useAtomValue(serverEnvironment.configValueAtom(props.environmentId)); const canQueryPath = config?.environment.capabilities.projectCodePath === true; const [history, setHistory] = useState>([props.symbol]); @@ -403,10 +464,10 @@ export default function CodeExplorer( const current = history.at(-1) ?? props.symbol; const relation = (operation: "callers" | "callees", depth: ExplorerHops) => codeQuery(props, { operation, symbol: selectorFor(current), depth, limit: SIDE_LIMIT }); - const callers = useEnvironmentQuery(relation("callers", 1)); - const callees = useEnvironmentQuery(relation("callees", 1)); - const callersFar = useEnvironmentQuery(hops === 2 ? relation("callers", 2) : null); - const calleesFar = useEnvironmentQuery(hops === 2 ? relation("callees", 2) : null); + const callers = useEnvironmentQuery(relation("callers", 1), m); + const callees = useEnvironmentQuery(relation("callees", 1), m); + const callersFar = useEnvironmentQuery(hops === 2 ? relation("callers", 2) : null, m); + const calleesFar = useEnvironmentQuery(hops === 2 ? relation("callees", 2) : null, m); const recenter = (symbol: ProjectCodeSymbol) => { if (symbol.id !== current.id) setHistory([...history, symbol]); }; @@ -420,7 +481,7 @@ export default function CodeExplorer( onClick={() => setHistory(history.slice(0, -1))} > - Back + Back

        {current.name}

        @@ -434,14 +495,18 @@ export default function CodeExplorer( threadId={props.serverThreadId ?? undefined} /> { if (next[0] === "1" || next[0] === "2") setHops(next[0] === "1" ? 1 : 2); }} > - 1 hop - 2 hops + + 1 hop + + + 2 hops +
        ); @@ -479,8 +544,13 @@ export default function CodeExplorer( {header} {selection.state === "ambiguous" - ? `${selection.candidates.length} symbols match this name here; the index cannot tell which one you mean.` - : "This symbol is no longer in the index. Refresh after saving the file."} + ? m( + msg( + "{count} symbols match this name here; the index cannot tell which one you mean.", + ), + { count: selection.candidates.length }, + ) + : m(msg("This symbol is no longer in the index. Refresh after saving the file."))}
); @@ -509,8 +579,14 @@ export default function CodeExplorer( {coverage.state === "stale" || coverage.state === "unavailable" ? (

{coverage.state === "stale" - ? "The index is stale for some of these files. Verify calls in source before relying on them." - : "The code index is not ready for this checkout, so no calls can be shown yet."} + ? m( + msg( + "The index is stale for some of these files. Verify calls in source before relying on them.", + ), + ) + : m( + msg("The code index is not ready for this checkout, so no calls can be shown yet."), + )}

) : null} {farPending || farError !== null ? ( @@ -521,40 +597,50 @@ export default function CodeExplorer( callersFar.refresh(); calleesFar.refresh(); }} - pendingLabel="Reading the second hop…" + pendingLabel={m(msg("Reading the second hop…"))} /> ) : null} {limited ? (

- {`Showing ${drawn} symbols. More were found than the explorer draws (${NODE_CAP} at most, ${SIDE_LIMIT} per side).`} + {m( + msg( + "Showing {drawn} symbols. More were found than the explorer draws ({max} at most, {perSide} per side).", + ), + { drawn, max: NODE_CAP, perSide: SIDE_LIMIT }, + )}

) : null} {drawn === 0 ? ( - No static callers or callees found. Calls through values or dynamic dispatch are not - tracked, so that does not prove nothing calls it. + {m( + msg( + "No static callers or callees found. Calls through values or dynamic dispatch are not tracked, so that does not prove nothing calls it.", + ), + )} ) : ( )}

- Solid lines are compiler indexed, dashed lines static candidates, dotted lines heuristic. + + Solid lines are compiler indexed, dashed lines static candidates, dotted lines heuristic. +

- Choose a symbol to center on it; the arrow opens it in the file preview. + Choose a symbol to center on it; the arrow opens it in the file preview.

@@ -569,7 +655,7 @@ export default function CodeExplorer( onRecenter={recenter} /> ) : ( - Update the server to use call paths. + {m(msg("Update the server to use call paths."))} )}
); diff --git a/apps/web/src/components/codeExplorer/CodeExplorerDialogHost.tsx b/apps/web/src/components/codeExplorer/CodeExplorerDialogHost.tsx index aedba716dd374..f2a1388a51c2f 100644 --- a/apps/web/src/components/codeExplorer/CodeExplorerDialogHost.tsx +++ b/apps/web/src/components/codeExplorer/CodeExplorerDialogHost.tsx @@ -1,6 +1,7 @@ import { useAtom } from "@effect/atom-react"; import type { EnvironmentId, ProjectId } from "@t3tools/contracts"; import { lazy, Suspense, useEffect } from "react"; +import { T } from "gt-react"; import { Dialog, @@ -38,9 +39,11 @@ export function CodeExplorerDialogHost(props: { > - Code explorer + + Code explorer + - Static callers and callees around a symbol, read from this checkout's code index. + Static callers and callees around a symbol, read from this checkout's code index. @@ -48,7 +51,7 @@ export function CodeExplorerDialogHost(props: { - Opening code explorer… + Opening code explorer…

} > diff --git a/apps/web/src/components/conversationSummaries/ConversationSummariesDialog.browser.test.tsx b/apps/web/src/components/conversationSummaries/ConversationSummariesDialog.browser.test.tsx index bc1ea71d69d10..2e6c288673617 100644 --- a/apps/web/src/components/conversationSummaries/ConversationSummariesDialog.browser.test.tsx +++ b/apps/web/src/components/conversationSummaries/ConversationSummariesDialog.browser.test.tsx @@ -186,7 +186,7 @@ it("shows current summaries with their sources, hides outdated text, and opts th await expect .element(page.getByText("Last pass failed. No model 3 older sources wait for a summary.")) .toBeVisible(); - await expect.element(page.getByText(/Outdated: source changed\./)).toBeVisible(); + await expect.element(page.getByText(/Outdated: Source changed\./)).toBeVisible(); await userEvent.click(page.getByRole("button", { name: "Show sources" }).first()); await expect.element(page.getByText("Please sign every release bundle.")).toBeVisible(); diff --git a/apps/web/src/components/conversationSummaries/ConversationSummariesDialog.tsx b/apps/web/src/components/conversationSummaries/ConversationSummariesDialog.tsx index da6c2c3c7aaee..f4c3a118227d8 100644 --- a/apps/web/src/components/conversationSummaries/ConversationSummariesDialog.tsx +++ b/apps/web/src/components/conversationSummaries/ConversationSummariesDialog.tsx @@ -1,3 +1,4 @@ +import { msg, useMessages } from "gt-react"; import { useAtomValue } from "@effect/atom-react"; import { AuthSettingsWriteScope, @@ -52,6 +53,7 @@ interface Scope { /** The project opt-in. Summaries cost model calls, so it starts off. */ function SummariesToggle(props: Scope) { + const m = useMessages(); const config = useAtomValue(serverEnvironment.configValueAtom(props.environmentId)); const canWrite = useEnvironmentScope(props.environmentId, AuthSettingsWriteScope); const update = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false }); @@ -82,24 +84,27 @@ function SummariesToggle(props: Scope) { }; return (
- Summarize older messages + {m(msg("Summarize older messages"))} void toggle(checked)} />

- After turns complete in this project, your text generation model summarizes settled - stretches of older messages and tool output. Each summary costs one model call. + {m( + msg( + "After turns complete in this project, your text generation model summarizes settled stretches of older messages and tool output. Each summary costs one model call.", + ), + )}

{!canWrite ? ( -

This connection cannot change project settings.

+

{m(msg("This connection cannot change project settings."))}

) : null} {error ?

{error}

: null}
@@ -113,6 +118,7 @@ function SummarySourcePage(props: { readonly onPrevious: () => void; readonly onNext: (cursor: ConversationSummarySourceCursor) => void; }) { + const m = useMessages(); const { sources, nextOffset, nextTextOffset } = props.data; return (
@@ -120,18 +126,18 @@ function SummarySourcePage(props: { {sources.map(({ ref, result }, index) => (
  • - #{props.cursor.offset + index + 1} · {conversationSummarySourceLabel(ref, result)} + #{props.cursor.offset + index + 1} · {conversationSummarySourceLabel(ref, result, m)}

    - {conversationSummarySourceRangeLabel(ref, result) ? ( + {conversationSummarySourceRangeLabel(ref, result, m) ? (

    - {conversationSummarySourceRangeLabel(ref, result)} + {conversationSummarySourceRangeLabel(ref, result, m)}

    ) : null} {result.state === "available" ? (

    {result.text}

    ) : (

    - {KNOWLEDGE_SOURCE_UNAVAILABLE_LABEL[result.reason]}. + {m(KNOWLEDGE_SOURCE_UNAVAILABLE_LABEL[result.reason])}.

    )}
  • @@ -145,7 +151,7 @@ function SummarySourcePage(props: { disabled={!props.hasPrevious} onClick={props.onPrevious} > - Previous sources + {m(msg("Previous sources"))}
    ) : null} @@ -183,6 +189,7 @@ function SummaryStatements(props: { readonly summary: ConversationSummary }) { } function SummaryCard(props: Scope & { readonly read: ConversationSummaryRead }) { + const m = useMessages(); const [showSources, setShowSources] = useState(false); const [sourceCursors, setSourceCursors] = useState | null>(null); @@ -212,20 +219,25 @@ function SummaryCard(props: Scope & { readonly read: ConversationSummaryRead }) return (

    - {sourceCount} sources · written {new Date(createdAt).toLocaleString()} + {m(msg("{count, plural, one {# source} other {# sources}} · written {date}"), { + count: sourceCount, + date: new Date(createdAt).toLocaleString(), + })}

    {read === null ? (

    {expansion.error - ? "Summary unavailable until its sources can be checked." - : "Checking sources…"} + ? m(msg("Summary unavailable until its sources can be checked.")) + : m(msg("Checking sources…"))}

    ) : read.state === "available" ? ( ) : (

    - Outdated: {KNOWLEDGE_SOURCE_UNAVAILABLE_LABEL[read.reason].toLowerCase()}. The summary - text is hidden and agents no longer receive it. + {m( + msg("Outdated: {reason}. The summary text is hidden and agents no longer receive it."), + { reason: m(KNOWLEDGE_SOURCE_UNAVAILABLE_LABEL[read.reason]) }, + )}

    )}
    @@ -237,7 +249,7 @@ function SummaryCard(props: Scope & { readonly read: ConversationSummaryRead }) setShowSources((value) => !value); }} > - {showSources ? "Hide sources" : "Show sources"} + {showSources ? m(msg("Hide sources")) : m(msg("Show sources"))}
    {showSources ? ( @@ -246,7 +258,7 @@ function SummaryCard(props: Scope & { readonly read: ConversationSummaryRead }) {expansion.error}

    ) : expansion.data === null ? ( -

    Loading sources…

    +

    {m(msg("Loading sources…"))}

    ) : ( >([]); const [searchText, setSearchText] = useState(""); const [query, setQuery] = useState(""); @@ -277,14 +290,14 @@ function SummaryList(props: Scope & { readonly searchSupported: boolean }) { }} > setSearchText(event.target.value)} /> {searchText || query ? ( ) : null} ) : ( -

    Update this server to search summaries.

    +

    + {m(msg("Update this server to search summaries."))} +

    )} void; }, ) { + const m = useMessages(); const cursor = props.cursors.at(-1); const list = useEnvironmentQuery( conversationSummaries.list({ @@ -343,21 +359,27 @@ function SummaryListPage( {list.error}

    ); - if (!list.data) return

    Loading summaries…

    ; + if (!list.data) + return

    {m(msg("Loading summaries…"))}

    ; const { lastPass, summaries, nextCursor, enabled } = list.data; return (
    {lastPass ? ( -

    {conversationSummaryPassLabel(lastPass)}

    +

    {conversationSummaryPassLabel(lastPass, m)}

    ) : enabled ? (

    - The first summary is written after a turn completes and enough older messages have - settled. + {m( + msg( + "The first summary is written after a turn completes and enough older messages have settled.", + ), + )}

    ) : null} {summaries.length === 0 ? (

    - {props.query ? "No summaries match your search." : "This thread has no summaries yet."} + {props.query + ? m(msg("No summaries match your search.")) + : m(msg("This thread has no summaries yet."))}

    ) : ( summaries.map((read) => ( @@ -376,7 +398,7 @@ function SummaryListPage( disabled={props.cursors.length === 0} onClick={props.onEarlier} > - Earlier + {m(msg("Earlier"))}
    ) : null} @@ -397,6 +419,7 @@ function SummaryListPage( export function ConversationSummariesDialog( props: Scope & { readonly open: boolean; readonly onOpenChange: (open: boolean) => void }, ) { + const m = useMessages(); const config = useAtomValue(serverEnvironment.configValueAtom(props.environmentId)); const project = useProject({ environmentId: props.environmentId, projectId: props.projectId }); const searchSupported = config?.environment.capabilities.conversationSummarySourceFormat === 2; @@ -404,11 +427,13 @@ export function ConversationSummariesDialog( - Conversation summaries + {m(msg("Conversation summaries"))} - Model-written summaries of this thread's older messages and tool output. When the thread - moves to another provider or is forked, agents receive them in place of messages that no - longer fit, and can open the exact sources behind each one. + {m( + msg( + "Model-written summaries of this thread's older messages and tool output. When the thread moves to another provider or is forked, agents receive them in place of messages that no longer fit, and can open the exact sources behind each one.", + ), + )} diff --git a/apps/web/src/components/externalHistory/ExternalHistoryDialog.tsx b/apps/web/src/components/externalHistory/ExternalHistoryDialog.tsx index e2c9112b73b78..0b72ecc2c0701 100644 --- a/apps/web/src/components/externalHistory/ExternalHistoryDialog.tsx +++ b/apps/web/src/components/externalHistory/ExternalHistoryDialog.tsx @@ -1,8 +1,10 @@ +import { msg, useMessages } from "gt-react"; import { useAtomValue } from "@effect/atom-react"; import { externalHistoryPagingReducer, initialExternalHistoryPaging, externalHistoryRangeLabel, + externalHistoryRoleLabel, externalHistorySearchFilters, externalHistorySourceStatusLabel, } from "@t3tools/client-runtime/externalHistory"; @@ -39,21 +41,25 @@ export function ExternalHistoryButton(props: { readonly currentProjectPath?: string; readonly label?: string; }) { + const m = useMessages(); const [open, setOpen] = useState(false); const config = useAtomValue(serverEnvironment.configValueAtom(props.environmentId)); if (config?.environment.capabilities.externalHistory !== 1) return null; return ( <> - External history + {m(msg("External history"))} - Search agent conversations found on this environment. Open the original evidence - behind each match. + {m( + msg( + "Search agent conversations found on this environment. Open the original evidence behind each match.", + ), + )} @@ -70,6 +76,7 @@ function ExternalHistorySettingsEditor(props: { readonly settings: ExternalHistorySettings; readonly children: ReactNode; }) { + const m = useMessages(); const canWrite = useAtomValue( serverEnvironment.updateSettings.permissionAtom(props.environmentId), ); @@ -91,24 +98,27 @@ function ExternalHistorySettingsEditor(props: {
    - Allow external history search + {m(msg("Allow external history search"))} void save({ ...props.settings, enabled })} />

    - Makes these sources available to this environment's connected clients and agents with - thread access. Source files stay in their existing locations. + {m( + msg( + "Makes these sources available to this environment's connected clients and agents with thread access. Source files stay in their existing locations.", + ), + )}

    {!canWrite ? (

    - This connection cannot change environment settings. + {m(msg("This connection cannot change environment settings."))}

    ) : null} {error ? ( @@ -126,11 +136,12 @@ function ExternalHistoryPanel(props: { readonly environmentId: EnvironmentId; readonly currentProjectPath?: string; }) { + const m = useMessages(); const config = useAtomValue(serverEnvironment.configValueAtom(props.environmentId)); if (config?.environment.capabilities.externalHistory !== 1) return (

    - Update this server to search external history. + {m(msg("Update this server to search external history."))}

    ); const settings = config.settings.externalHistory; @@ -141,7 +152,7 @@ function ExternalHistoryPanel(props: { ) : (

    - External history search is off for this environment. + {m(msg("External history search is off for this environment."))}

    )} @@ -153,6 +164,7 @@ function HistorySources(props: { readonly environmentId: EnvironmentId; readonly currentProjectPath?: string; }) { + const m = useMessages(); const query = useEnvironmentQuery( externalHistory.query({ environmentId: props.environmentId, @@ -167,11 +179,11 @@ function HistorySources(props: {

    ); if (!query.data || query.data.operation !== "sources") - return

    Loading history sources…

    ; + return

    {m(msg("Loading history sources…"))}

    ; if (!query.data.enabled) return (

    - External history search is off for this environment. + {m(msg("External history search is off for this environment."))}

    ); const sources = query.data.sources; @@ -180,11 +192,11 @@ function HistorySources(props: { sources.find((item) => item.status === "ready"); return (
    -
    -

    Found on this environment

    +
    +

    {m(msg("Found on this environment"))}

    {sources.length === 0 ? (

    - No local history found. Refresh after adding conversations on this server. + {m(msg("No local history found. Refresh after adding conversations on this server."))}

    ) : null}
      @@ -202,7 +214,7 @@ function HistorySources(props: {

    - {externalHistorySourceStatusLabel(item.status)} + {externalHistorySourceStatusLabel(item.status, m)} {item.message ? ` · ${item.message}` : ""}

    @@ -210,7 +222,7 @@ function HistorySources(props: { {query.data.unsupported.length > 0 ? (
      {query.data.unsupported.map((item) => ( @@ -222,7 +234,7 @@ function HistorySources(props: { ) : null}
    @@ -244,6 +256,7 @@ function HistorySearch(props: { readonly capabilities: ExternalHistorySource["capabilities"]; readonly currentProjectPath?: string; }) { + const m = useMessages(); const [text, setText] = useState(""); const [filterCwd, setFilterCwd] = useState(""); const [includeArchived, setIncludeArchived] = useState(false); @@ -266,8 +279,8 @@ function HistorySearch(props: { }} > setText(event.target.value)} maxLength={256} @@ -275,8 +288,8 @@ function HistorySearch(props: { {props.capabilities.cwdFilter ? ( <> { setFilterCwd(event.target.value); @@ -295,7 +308,7 @@ function HistorySearch(props: { setSearch(null); }} > - This project + {m(msg("This project"))}
    ) : null} @@ -314,9 +327,9 @@ function HistorySearch(props: { ) : null} {props.capabilities.archived ? (
    - Include archived threads + {m(msg("Include archived threads"))} { setIncludeArchived(value); @@ -327,7 +340,7 @@ function HistorySearch(props: { ) : null}
    @@ -339,7 +352,7 @@ function HistorySearch(props: { /> ) : (

    - Search messages and tool evidence from the selected source. + {m(msg("Search messages and tool evidence from the selected source."))}

    )}
    @@ -347,6 +360,7 @@ function HistorySearch(props: { } function HistoryResults(props: { readonly environmentId: EnvironmentId; readonly search: Search }) { + const m = useMessages(); const [paging, dispatch] = useReducer( externalHistoryPagingReducer, undefined, @@ -373,7 +387,7 @@ function HistoryResults(props: { readonly environmentId: EnvironmentId; readonly

    - Searched {paging.examinedItems.toLocaleString()} items - {paging.status === "searching" ? "…" : "."} + {m(msg("Searched {count, plural, one {# item} other {# items}}{ending}"), { + count: paging.examinedItems, + ending: paging.status === "searching" ? "…" : ".", + })}

    {paging.status === "searching" ? (
    ) : paging.status === "stopped" ? (
    - Search stopped. + {m(msg("Search stopped."))}
    ) : null} - {data?.matches.length === 0 ?

    No more matches found.

    : null} + {data?.matches.length === 0 ? ( +

    {m(msg("No more matches found."))}

    + ) : null} {data?.matches.map((match) => (

    {match.threadTitle}

    - {match.role} · {match.totalChars.toLocaleString()} characters + {m(msg("{role} · {count, plural, one {# character} other {# characters}}"), { + role: externalHistoryRoleLabel(match.role, m), + count: match.totalChars, + })}

    {match.excerpt}

    @@ -437,7 +458,7 @@ function HistoryResults(props: { readonly environmentId: EnvironmentId; readonly disabled={paging.previous.length === 0} onClick={() => dispatch({ type: "previous" })} > - Previous page + {m(msg("Previous page"))}
    ) : null} @@ -457,6 +478,7 @@ function HistorySource(props: { readonly environmentId: EnvironmentId; readonly match: ExternalHistoryMatch; }) { + const m = useMessages(); const [offsets, setOffsets] = useState>([0]); const query = useEnvironmentQuery( externalHistory.query({ @@ -476,16 +498,19 @@ function HistorySource(props: {

    ); if (!query.data || query.data.operation !== "read") - return

    Reading source…

    ; + return

    {m(msg("Reading source…"))}

    ; const data = query.data; return (

    {data.threadTitle}

    - {data.role} · {externalHistoryRangeLabel(data)} + {externalHistoryRoleLabel(data.role, m)} · {externalHistoryRangeLabel(data, m)}

    - Thread {data.ref.threadId} · Item {props.match.itemId} + {m(msg("Thread {threadId} · Item {itemId}"), { + threadId: data.ref.threadId, + itemId: props.match.itemId, + })}

             {data.text}
    @@ -498,7 +523,7 @@ function HistorySource(props: {
                 disabled={offsets.length === 1 || query.isPending}
                 onClick={() => setOffsets((current) => current.slice(0, -1))}
               >
    -            Previous source text
    +            {m(msg("Previous source text"))}
               
               
             
    ) : null} diff --git a/apps/web/src/components/files/CodeIndexBadge.tsx b/apps/web/src/components/files/CodeIndexBadge.tsx index 11e6783ccf2f0..3e5e1cae1086a 100644 --- a/apps/web/src/components/files/CodeIndexBadge.tsx +++ b/apps/web/src/components/files/CodeIndexBadge.tsx @@ -1,6 +1,7 @@ import { useAtomValue } from "@effect/atom-react"; import { projectCodeIndexBadge } from "@t3tools/client-runtime/projectCode"; import type { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts"; +import { msg, useMessages } from "gt-react"; import { Badge } from "~/components/ui/badge"; import { projectCode } from "~/state/projectCode"; @@ -19,6 +20,7 @@ export function CodeIndexBadge(props: { /** A draft has no server thread; the project's own checkout is read instead. */ readonly threadId?: ThreadId | undefined; }) { + const m = useMessages(); const config = useAtomValue(serverEnvironment.configValueAtom(props.environmentId)); const canQuery = useAtomValue(projectCode.freshness.permissionAtom(props.environmentId)); const supported = @@ -36,19 +38,23 @@ export function CodeIndexBadge(props: { }, }) : null, + m, ); if (!supported) return null; if (freshness.data === null && freshness.error === null) return null; const badge = freshness.data === null - ? { label: "Unavailable", tone: "muted" as const, detail: freshness.error ?? "" } - : projectCodeIndexBadge(freshness.data.index); + ? { label: m(msg("Unavailable")), tone: "muted" as const, detail: freshness.error ?? "" } + : projectCodeIndexBadge(freshness.data.index, m); return ( {badge.label} diff --git a/apps/web/src/components/files/FileCodeRelationships.tsx b/apps/web/src/components/files/FileCodeRelationships.tsx index 8db93617357de..9ff2d7eb9c862 100644 --- a/apps/web/src/components/files/FileCodeRelationships.tsx +++ b/apps/web/src/components/files/FileCodeRelationships.tsx @@ -17,12 +17,14 @@ import { import { useNavigate } from "@tanstack/react-router"; import { NetworkIcon } from "lucide-react"; import { useState } from "react"; +import { msg, T, useMessages } from "gt-react"; import { CollapsibleSectionHeader } from "~/components/ui/collapsible-section-header"; import { ScrollArea } from "~/components/ui/scroll-area"; import { Toggle, ToggleGroup } from "~/components/ui/toggle-group"; import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip"; import { Button } from "~/components/ui/button"; +import type { MessageResolver } from "~/i18n/messages"; import { randomUUID } from "~/lib/utils"; import { useRightPanelStore } from "~/rightPanelStore"; import { useQuietThreadShell } from "~/state/entities"; @@ -83,6 +85,7 @@ function relationLocations( mode: RelationMode, result: ProjectCodeQueryResult, selectedId: string, + resolve: MessageResolver, ): ReadonlyArray { const nodes = new Map(result.nodes.map((node) => [node.id, node])); if (mode === "tests") { @@ -96,7 +99,12 @@ function relationLocations( label: node.name, path: node.path, line: node.startLine, - detail: hops === null ? "static" : `${hops} ${hops === 1 ? "hop" : "hops"} · static`, + detail: + hops === null + ? resolve(msg("static")) + : resolve(msg("{count, plural, one {{count} hop} other {{count} hops}} · static"), { + count: hops, + }), isTest: true, }, ]; @@ -131,7 +139,14 @@ function relationLocations( label: path, path, line, - detail: `${count} ${count === 1 ? "symbol" : "symbols"}${grade ? ` · ${GRADE_LABEL[grade]}` : ""}`, + detail: grade + ? resolve( + msg("{count, plural, one {{count} symbol} other {{count} symbols}} · {grade}"), + { count, grade: resolve(GRADE_LABEL[grade]) }, + ) + : resolve(msg("{count, plural, one {{count} symbol} other {{count} symbols}}"), { + count, + }), isTest: isLikelyTestPath(path), }; }) @@ -156,7 +171,7 @@ function relationLocations( label: other.name, path: other.path, line, - detail: GRADE_LABEL[edge.evidenceGrade], + detail: resolve(GRADE_LABEL[edge.evidenceGrade]), isTest: isLikelyTestPath(other.path), }); } @@ -164,18 +179,20 @@ function relationLocations( } const EMPTY_RELATION: Record = { - callers: "No static callers found. That does not prove nothing calls it.", - callees: "No static callees found. Calls through values or dynamic dispatch are not tracked.", - references: "No static references found. That does not prove it is unused.", - impact: "No other files found in its static impact radius.", - tests: "No test file reaches it within 3 static hops. That does not mean it is untested.", + callers: msg("No static callers found. That does not prove nothing calls it."), + callees: msg( + "No static callees found. Calls through values or dynamic dispatch are not tracked.", + ), + references: msg("No static references found. That does not prove it is unused."), + impact: msg("No other files found in its static impact radius."), + tests: msg("No test file reaches it within 3 static hops. That does not mean it is untested."), }; const RELATION_MODES: ReadonlyArray = [ - ["callers", "Callers"], - ["callees", "Callees"], - ["references", "References"], - ["impact", "Impact"], - ["tests", "Tests"], + ["callers", msg("Callers")], + ["callees", msg("Callees")], + ["references", msg("References")], + ["impact", msg("Impact")], + ["tests", msg("Tests")], ]; function RelationResults(props: { @@ -185,6 +202,7 @@ function RelationResults(props: { readonly symbol: ProjectCodeSymbol; readonly canQueryTests: boolean; }) { + const m = useMessages(); const [mode, setMode] = useState("callers"); const symbol = { name: props.symbol.name, @@ -202,13 +220,14 @@ function RelationResults(props: { query: { operation: mode, symbol, limit: RESULT_LIMIT }, }, }), + m, ); const data = relation.data; - const locations = data ? relationLocations(mode, data, props.symbol.id) : []; + const locations = data ? relationLocations(mode, data, props.symbol.id, m) : []; return (
    { @@ -218,30 +237,41 @@ function RelationResults(props: { > {RELATION_MODES.map(([value, label]) => ( - {label} + {m(label)} ))} {mode === "tests" && !props.canQueryTests ? ( - Update the server to use tests. + {m(msg("Update the server to use tests."))} ) : data === null ? ( ) : data.selection.state === "ambiguous" ? ( - {`${data.selection.candidates.length} symbols match this name here; the index cannot tell which one you mean.`} + {m( + msg("{count} symbols match this name here; the index cannot tell which one you mean."), + { count: data.selection.candidates.length }, + )} ) : data.selection.state === "not-found" ? ( - This symbol is no longer in the index. Refresh after saving the file. + + {m(msg("This symbol is no longer in the index. Refresh after saving the file."))} + ) : ( <> {locations.length === 0 ? ( - {EMPTY_RELATION[mode]} + {m(EMPTY_RELATION[mode])} ) : ( locations.map((location) => ( @@ -281,6 +311,7 @@ function SymbolsTab(props: { readonly relativePath: string; readonly canQueryTests: boolean; }) { + const m = useMessages(); const [selected, setSelected] = useState(null); const openExplorer = useOpenCodeExplorer(); const outline = useEnvironmentQuery( @@ -290,6 +321,7 @@ function SymbolsTab(props: { props.threadRef.threadId, props.relativePath, ), + m, ); const data = outline.data; if (data === null) return ; @@ -305,23 +337,29 @@ function SymbolsTab(props: { disabled={outline.isPending} onClick={outline.refresh} > - Refresh + Refresh
    {data.coverage.state === "unavailable" ? null : data.nodes.length === 0 ? ( - No indexed declarations in this file. Its language may be unsupported, or it declares - nothing the index recognizes. + {m( + msg( + "No indexed declarations in this file. Its language may be unsupported, or it declares nothing the index recognizes.", + ), + )} ) : ( -
    +
    {data.nodes.map((node) => (
    { setSelected(selected?.id === node.id ? null : node); @@ -337,7 +375,7 @@ function SymbolsTab(props: {
    ))} @@ -401,10 +441,12 @@ function DecisionsTab(props: { readonly relativePath: string; readonly canReadCode: boolean; }) { + const m = useMessages(); const outline = useEnvironmentQuery( props.canReadCode ? outlineQuery(props.environmentId, props.projectId, props.threadId, props.relativePath) : null, + m, ); const outlineSettled = !props.canReadCode || outline.data !== null || outline.error !== null; const pathNames = new Set([ @@ -425,7 +467,7 @@ function DecisionsTab(props: { pending error={null} onRetry={outline.refresh} - pendingLabel="Searching project knowledge…" + pendingLabel={m(msg("Searching project knowledge…"))} /> ); return ( @@ -450,6 +492,7 @@ function DecisionPages(props: { readonly pathNames: ReadonlySet; readonly symbolNames: ReadonlySet; }) { + const m = useMessages(); const [page, setPage] = useState(() => ({ id: CommandId.make(randomUUID()), cursor: null as FactSearchPage["nextCursor"], @@ -471,6 +514,7 @@ function DecisionPages(props: { }; const search = useEnvironmentQuery( projectKnowledge.search({ environmentId: props.environmentId, input }), + m, ); if (search.data === null && page.previous.length === 0) { return ( @@ -478,13 +522,17 @@ function DecisionPages(props: { pending error={search.error} onRetry={search.refresh} - pendingLabel="Searching project knowledge…" + pendingLabel={m(msg("Searching project knowledge…"))} /> ); } const facts = search.data?.facts; if (facts?.state === "unavailable") { - return Project knowledge search is unavailable on this server right now.; + return ( + + {m(msg("Project knowledge search is unavailable on this server right now."))} + + ); } const matches = [ ...new Map( @@ -499,29 +547,39 @@ function DecisionPages(props: { return (

    - Facts whose entities name this file - {props.symbolNames.size > 0 ? " or one of its symbols" : ""}. - {props.canReadCode ? "" : " Symbol names need file access, so only the path is matched."} + {props.canReadCode + ? props.symbolNames.size > 0 + ? m(msg("Facts whose entities name this file or one of its symbols.")) + : m(msg("Facts whose entities name this file.")) + : m( + msg( + "Facts whose entities name this file. Symbol names need file access, so only the path is matched.", + ), + )}

    {rows.length === 0 ? ( - No project knowledge names this file or its symbols. + {m(msg("No project knowledge names this file or its symbols."))} ) : ( -
      +
        {rows.map(({ fact, match }) => (
      • {fact.kind} {match.by === "path" - ? `matched by path ${match.label}` - : `matched by name ${match.label}`} + ? m(msg("matched by path {label}"), { label: match.label }) + : m(msg("matched by name {label}"), { label: match.label })} {fact.content} {match.by === "name" ? ( - Name, not identity: a fact about another {match.label} elsewhere in the project - matches too. + {m( + msg( + "Name, not identity: a fact about another {name} elsewhere in the project matches too.", + ), + { name: match.label }, + )} ) : null}
      • @@ -533,7 +591,7 @@ function DecisionPages(props: { pending error={search.error} onRetry={search.refresh} - pendingLabel="Searching project knowledge…" + pendingLabel={m(msg("Searching project knowledge…"))} /> ) : null} {facts?.nextCursor ? ( @@ -550,12 +608,14 @@ function DecisionPages(props: { }) } > - Show more + Show more
    ) : null} {facts?.coverage === "partial" ? ( - Only the most relevant facts were ranked; some may be missing. + + {m(msg("Only the most relevant facts were ranked; some may be missing."))} + ) : null}
    ); @@ -570,12 +630,14 @@ function PriorWorkTab(props: { readonly projectId: ProjectId; readonly relativePath: string; }) { + const m = useMessages(); const navigate = useNavigate(); const history = useEnvironmentQuery( projectCode.fileHistory({ environmentId: props.environmentId, input: { projectId: props.projectId, path: props.relativePath, limit: 20 }, }), + m, ); const data = history.data; if (data === null) { @@ -584,26 +646,42 @@ function PriorWorkTab(props: { pending error={history.error} onRetry={history.refresh} - pendingLabel="Reading checkpoint history…" + pendingLabel={m(msg("Reading checkpoint history…"))} /> ); } return (

    - Present at checkpoint: the file changed in that thread's workspace during a turn, by the - agent or anyone sharing the workspace. + + Present at checkpoint: the file changed in that thread's workspace during a turn, by the + agent or anyone sharing the workspace. +

    {data.entries.length === 0 ? ( - No thread checkpoint in this project has listed this file. + + {m(msg("No thread checkpoint in this project has listed this file."))} + ) : ( -
    +
    {data.entries.map((entry) => (
    void navigate({ to: "/$environmentId/$threadId", @@ -617,14 +695,18 @@ function PriorWorkTab(props: { ))}
    )} - {data.limitReached ? Showing the 20 most recent threads. : null} + {data.limitReached ? ( + {m(msg("Showing the 20 most recent threads."))} + ) : null} {data.index.state === "catching-up" ? (
    - {`${data.index.pendingCheckpoints} older checkpoints are not indexed yet.`} + {m(msg("{count} older checkpoints are not indexed yet."), { + count: data.index.pendingCheckpoints, + })}
    ) : null} @@ -633,9 +715,9 @@ function PriorWorkTab(props: { } const TAB_LABEL: Record = { - symbols: "Symbols", - decisions: "Decisions", - history: "Prior work", + symbols: msg("Symbols"), + decisions: msg("Decisions"), + history: msg("Prior work"), }; /** @@ -648,6 +730,7 @@ export function FileCodeRelationships(props: { readonly threadRef: ScopedThreadRef; readonly relativePath: string; }) { + const m = useMessages(); const config = useAtomValue(serverEnvironment.configValueAtom(props.environmentId)); const canQueryCode = useAtomValue(projectCode.query.permissionAtom(props.environmentId)); // File history and knowledge search both need thread read; history's guard carries it. @@ -665,7 +748,10 @@ export function FileCodeRelationships(props: { if (thread === null || tabs.length === 0) return null; const tab = available[chosenTab] ? chosenTab : tabs[0]!; return ( -
    +
    - Code relationships + Code relationships {expanded ? (
    {tabs.length > 1 ? ( { @@ -697,7 +783,7 @@ export function FileCodeRelationships(props: { > {tabs.map((value) => ( - {TAB_LABEL[value]} + {m(TAB_LABEL[value])} ))} @@ -719,7 +805,7 @@ export function FileCodeRelationships(props: { canReadCode={available.symbols} /> ) : capabilities?.projectCodeFileHistory !== true ? ( - Update the server to use prior work. + {m(msg("Update the server to use prior work."))} ) : ( { - if (node.type === "html" || node.type === "definition") return []; - if (node.type === "image" || node.type === "imageReference") - return [{ type: "text", value: node.alt ?? "" }]; - if (node.type === "link" || node.type === "linkReference") return clean(node.children); - if (node.type === "inlineCode") return [{ type: "text", value: node.value }]; - if (node.type === "code" && node.lang === "mermaid") return [{ ...node, lang: "text" }]; - if ("children" in node) node.children = clean(node.children) as typeof node.children; - return [node]; - }); - } - return (tree: Root) => { - tree.children = clean(tree.children) as Root["children"]; - }; -} -const NOTEBOOK_PLUGINS = [inertNotebookMarkdown]; +const NOTEBOOK_MARKDOWN: MarkdownExtensions = { inert: true }; function NotebookSource(props: { readonly name: string; readonly text: string }) { const [height, setHeight] = useState(Math.min(360, props.text.split("\n").length * 20 + 16)); @@ -129,7 +112,7 @@ export default function NotebookPreview(props: { text={cell.source} cwd={undefined} parseRawHtml={false} - extraRemarkPlugins={NOTEBOOK_PLUGINS} + extensions={NOTEBOOK_MARKDOWN} className="px-4 py-3" /> ) : cell.source.trim() ? ( diff --git a/apps/web/src/components/files/codeRelationshipRows.tsx b/apps/web/src/components/files/codeRelationshipRows.tsx index ab1a8b5689edf..1346497780a3d 100644 --- a/apps/web/src/components/files/codeRelationshipRows.tsx +++ b/apps/web/src/components/files/codeRelationshipRows.tsx @@ -1,4 +1,6 @@ import type { ProjectCodeCoverage, ProjectCodeEdge } from "@t3tools/contracts"; +import { msg, T, useMessages } from "gt-react"; +import type { MessageResolver } from "~/i18n/messages"; import { Button } from "~/components/ui/button"; import { cn } from "~/lib/utils"; @@ -9,9 +11,9 @@ export const GRADE_RANK: Record = { "heuristic-candidate": 2, }; export const GRADE_LABEL: Record = { - "compiler-indexed": "compiler indexed", - "static-candidate": "static candidate", - "heuristic-candidate": "heuristic", + "compiler-indexed": msg("compiler indexed"), + "static-candidate": msg("static candidate"), + "heuristic-candidate": msg("heuristic"), }; // Only languages seen in this checkout; `languages` is the analyzer's catalog. @@ -19,26 +21,37 @@ function indexedLanguagesSuffix(coverage: ProjectCodeCoverage): string { return coverage.indexedLanguages?.length ? ` (${coverage.indexedLanguages.join(", ")})` : ""; } -function coverageSummary(coverage: ProjectCodeCoverage): string { +function coverageSummary(coverage: ProjectCodeCoverage, resolve: MessageResolver): string { switch (coverage.state) { case "complete": - return `Static candidates · ${coverage.filesIndexed} files indexed${indexedLanguagesSuffix(coverage)}`; + return resolve(msg("Static candidates · {files} files indexed{languages}"), { + files: coverage.filesIndexed, + languages: indexedLanguagesSuffix(coverage), + }); case "partial": - return `Static candidates · partial coverage, ${coverage.filesIndexed} of ${coverage.filesListed} files indexed${indexedLanguagesSuffix(coverage)}`; + return resolve( + msg("Static candidates · partial coverage, {indexed} of {listed} files indexed{languages}"), + { + indexed: coverage.filesIndexed, + listed: coverage.filesListed, + languages: indexedLanguagesSuffix(coverage), + }, + ); case "stale": - return "Stale · some returned files changed since indexing. Verify in source."; + return resolve(msg("Stale · some returned files changed since indexing. Verify in source.")); case "unavailable": - return "The code index is not ready for this checkout."; + return resolve(msg("The code index is not ready for this checkout.")); } } export function CoverageNote(props: { readonly coverage: ProjectCodeCoverage }) { + const m = useMessages(); const { coverage } = props; const warn = coverage.state === "stale" || coverage.state === "unavailable"; return (
    - {coverageSummary(coverage)} + {coverageSummary(coverage, m)}
      {coverage.limitations.map((limitation) => ( @@ -81,12 +94,13 @@ export function QueryState(props: { readonly onRetry: () => void; readonly pendingLabel?: string; }) { + const m = useMessages(); if (props.error !== null) { return (
      {props.error}
      ); @@ -94,7 +108,7 @@ export function QueryState(props: { if (props.pending) { return (

      - {props.pendingLabel ?? "Indexing… the first query on a checkout can take a while."} + {props.pendingLabel ?? m(msg("Indexing… the first query on a checkout can take a while."))}

      ); } diff --git a/apps/web/src/components/projectKnowledge/AssistedLearningSection.tsx b/apps/web/src/components/projectKnowledge/AssistedLearningSection.tsx index 41b32f024a3e8..7aa685a3e7006 100644 --- a/apps/web/src/components/projectKnowledge/AssistedLearningSection.tsx +++ b/apps/web/src/components/projectKnowledge/AssistedLearningSection.tsx @@ -1,4 +1,5 @@ import { useState } from "react"; +import { T, useGT, useMessages } from "gt-react"; import { useAtomValue } from "@effect/atom-react"; import { AuthSettingsWriteScope, @@ -19,6 +20,8 @@ export function AssistedLearningSection(props: { readonly projectId: ProjectId; readonly status: ProjectKnowledgeStatus | null; }) { + const gt = useGT(); + const m = useMessages(); const config = useAtomValue(serverEnvironment.configValueAtom(props.environmentId)); const canWrite = useEnvironmentScope(props.environmentId, AuthSettingsWriteScope); const update = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false }); @@ -48,23 +51,32 @@ export function AssistedLearningSection(props: { if (result._tag === "Failure") setError(String(squashAtomCommandFailure(result))); }; return ( -
      +
      - Save facts from finished runs + + Save facts from finished runs + void toggle(checked)} />

      - Completed runs are grouped into background learning batches. Your text generation model - saves up to three cited facts per batch; eligible batches use at most one model call. + + Completed runs are grouped into background learning batches. Your text generation model + saves up to three cited facts per batch; eligible batches use at most one model call. +

      - {lastRun ?

      {assistedLearningRunLabel(lastRun)}

      : null} + {lastRun ?

      {assistedLearningRunLabel(lastRun, m)}

      : null} {!canWrite ? ( -

      This connection cannot change project settings.

      +

      + This connection cannot change project settings. +

      ) : null} {error ?

      {error}

      : null}
      diff --git a/apps/web/src/components/projectKnowledge/ProjectFactDetail.tsx b/apps/web/src/components/projectKnowledge/ProjectFactDetail.tsx index 554bb12c9f3c6..f042a7a486329 100644 --- a/apps/web/src/components/projectKnowledge/ProjectFactDetail.tsx +++ b/apps/web/src/components/projectKnowledge/ProjectFactDetail.tsx @@ -1,4 +1,5 @@ import { useState } from "react"; +import { T, useGT, useMessages } from "gt-react"; import type { KnowledgeConflictHint, KnowledgeMessageRef, @@ -10,6 +11,7 @@ import type { } from "@t3tools/contracts"; import { KNOWLEDGE_SOURCE_UNAVAILABLE_LABEL, + KNOWLEDGE_FACT_STATUS_LABEL, knowledgeConflictHintLabel, knowledgeOriginLabel, memoryCurationRunLabel, @@ -32,6 +34,7 @@ const SPARK_HEIGHT = 24; // Trust lives in [0, 1]; a fixed scale keeps a flat history visibly flat instead of // stretching noise across the full height. function TrustSparkline(props: { readonly points: ReadonlyArray }) { + const gt = useGT(); const first = props.points[0] ?? 0; const last = props.points.at(-1) ?? 0; const step = SPARK_WIDTH / (props.points.length - 1); @@ -44,7 +47,10 @@ function TrustSparkline(props: { readonly points: ReadonlyArray }) { return (

      - {knowledgeConflictHintLabel(props.hint)}: {props.hint.excerpt} + {knowledgeConflictHintLabel(props.hint, m)}: {props.hint.excerpt}

      {props.onOpenFact ? ( ) : null} {props.currentContent !== null ? ( ) : null}
      {comparing && props.currentContent !== null ? (
      -
      This fact
      +
      + This fact +

      {props.currentContent}

      - Existing fact, revision {props.hint.revision} + {gt("Existing fact, revision {revision}", { revision: props.hint.revision })}

      {props.hint.excerpt}

      @@ -102,14 +114,20 @@ function SummaryRow(props: { readonly summary: ProjectFactSummary; readonly onOpenFact: OpenFact; }) { + const gt = useGT(); + const m = useMessages(); return (
      - {props.label}: {props.summary.excerpt ?? "Forgotten fact"} (revision{" "} - {props.summary.revision}, {props.summary.status}) + {gt("{label}: {excerpt} (revision {revision}, {status})", { + label: props.label, + excerpt: props.summary.excerpt ?? gt("Forgotten fact"), + revision: props.summary.revision, + status: m(KNOWLEDGE_FACT_STATUS_LABEL[props.summary.status]), + })}
      ); @@ -119,27 +137,34 @@ function HistoryRow(props: { readonly entry: ProjectFactHistoryEntry; readonly onOpenSource: (source: KnowledgeMessageRef) => void; }) { + const gt = useGT(); + const m = useMessages(); const { entry } = props; const showsContent = (entry.event === "created" || entry.event === "edited") && entry.content !== null; return (
    • - {projectFactHistoryLabel(entry)} + {projectFactHistoryLabel(entry, m)} - {knowledgeOriginLabel(entry.actor)} ·{" "} + {knowledgeOriginLabel(entry.actor, m)} ·{" "}
      {entry.event === "feedback" && entry.trustBefore !== null ? (

      - Trust {entry.trustBefore.toFixed(2)} → {entry.trustAfter.toFixed(2)} + {gt("Trust {before} → {after}", { + before: entry.trustBefore.toFixed(2), + after: entry.trustAfter.toFixed(2), + })}

      ) : null} {entry.reason ?

      {entry.reason}

      : null} {showsContent ? (
      - Revision {entry.revision} content + + {gt("Revision {revision} content", { revision: entry.revision })} +

      {entry.content}

      ) : null} @@ -154,13 +179,13 @@ function HistoryRow(props: { size="sm" onClick={() => props.onOpenSource(source)} > - Message {source.messageId} + {gt("Message {messageId}", { messageId: source.messageId })} ) : null, )} {entry.sourceUnavailable !== null ? ( - {KNOWLEDGE_SOURCE_UNAVAILABLE_LABEL[entry.sourceUnavailable]} + {m(KNOWLEDGE_SOURCE_UNAVAILABLE_LABEL[entry.sourceUnavailable])} ) : null}
    • @@ -174,16 +199,21 @@ export function ProjectFactRelations(props: { readonly detail: ProjectKnowledgeFactDetail; readonly onOpenFact: OpenFact; }) { + const gt = useGT(); const { detail } = props; if (!detail.supersedes && !detail.supersededBy && detail.hints.length === 0) return null; return (
      {detail.supersedes ? ( - + ) : null} {detail.supersededBy ? ( @@ -204,20 +234,23 @@ export function ProjectFactHistory(props: { readonly detail: ProjectKnowledgeFactDetail; readonly onOpenSource: (source: KnowledgeMessageRef) => void; }) { + const gt = useGT(); const { detail } = props; const trust = projectFactTrustPoints(detail.history); return (

      - History + History

      {trust.length >= 2 ? : null}
      {detail.historyTruncated ? ( -

      Earlier history not shown

      +

      + Earlier history not shown +

      ) : null} -
        +
          {detail.history.map((entry) => ( ))} @@ -227,18 +260,20 @@ export function ProjectFactHistory(props: { } export function KnowledgeHealthStrip(props: { readonly status: ProjectKnowledgeStatus }) { + const gt = useGT(); + const m = useMessages(); const { status } = props; const counters = [ - ["Saved", status.counts.saved], - ["Superseded", status.counts.superseded], - ["Below recall threshold", status.belowRecallThreshold], - ["Retrievals", status.retrievals], - ["Helpful", status.feedback.helpful], - ["Unhelpful", status.feedback.unhelpful], + [gt("Saved", { $context: "project fact count" }), status.counts.saved], + [gt("Superseded", { $context: "project fact count" }), status.counts.superseded], + [gt("Below recall threshold"), status.belowRecallThreshold], + [gt("Retrievals", { $context: "project fact retrieval count" }), status.retrievals], + [gt("Helpful", { $context: "project fact feedback count" }), status.feedback.helpful], + [gt("Unhelpful", { $context: "project fact feedback count" }), status.feedback.unhelpful], ] as const; return (
          -
          +
          {counters.map(([label, value]) => (
          {label}
          @@ -248,7 +283,7 @@ export function KnowledgeHealthStrip(props: { readonly status: ProjectKnowledgeS
          {status.curation ? (

          - {memoryCurationRunLabel(status.curation)} + {memoryCurationRunLabel(status.curation, m)} {status.curation.completedAt ? ( <> {" · "} diff --git a/apps/web/src/components/projectKnowledge/ProjectFactEditor.tsx b/apps/web/src/components/projectKnowledge/ProjectFactEditor.tsx index 4081757f0a9db..530e6708026b0 100644 --- a/apps/web/src/components/projectKnowledge/ProjectFactEditor.tsx +++ b/apps/web/src/components/projectKnowledge/ProjectFactEditor.tsx @@ -1,4 +1,6 @@ import { useId, useState } from "react"; +import { T, useGT, useMessages } from "gt-react"; +import { KNOWLEDGE_FACT_KIND_LABEL } from "@t3tools/client-runtime/projectKnowledge"; import { CommandId, ProjectFactId, @@ -46,6 +48,8 @@ export function ProjectFactEditor(props: { readonly onSubmit: (input: ProjectKnowledgeMutation) => void; readonly onCancel: () => void; }) { + const gt = useGT(); + const m = useMessages(); const { seed } = props; const base = seed.mode === "create" ? null : seed.base; const [superseding, setSuperseding] = useState(seed.mode === "supersede"); @@ -63,7 +67,7 @@ export function ProjectFactEditor(props: { : seed.mode === "create" && seed.sources.length ? seed.sources : [{ kind: "user" }]; - const title = base ? (superseding ? "Supersede fact" : "Edit fact") : "Save a fact"; + const title = base ? (superseding ? gt("Supersede fact") : gt("Edit fact")) : gt("Save a fact"); return (

          {title} {base && superseding ? (

          - The original stays readable but is no longer recalled once replaced. + The original stays readable but is no longer recalled once replaced.

          ) : null}