`,
+ );
+ const visible = timeline.container.querySelector("p")!;
+ using measure = vi.spyOn(Range.prototype, "getBoundingClientRect");
+ await using _screen = await render(
+ {}}
+ />,
+ );
+ expect([painted().length, paintedIn(visible)]).toEqual([1, 1]);
+ expect(measure.mock.calls.length).toBeLessThan(100);
+});
+
+it("registers a row's matches only while it is near the viewport, and again after its text changes", async () => {
+ using timeline = mountTimeline(
+ `
e e e
+
+
e e
`,
+ );
+ const [near, far] = [...timeline.container.querySelectorAll("[data-thread-find-text]")];
+ const onActiveRange = vi.fn<(range: Range | null) => void>();
+ await using _screen = await render(
+ ,
+ );
+ expect([paintedIn(near!), paintedIn(far!)]).toEqual([3, 0]);
+ expect(CSS.highlights.get("t3-thread-find-active")?.size).toBe(1);
+ expect(far!.contains(onActiveRange.mock.lastCall?.[0]?.startContainer ?? null)).toBe(true);
+
+ near!.append(" e");
+ await vi.waitFor(() => expect(paintedIn(near!)).toBe(4));
+
+ timeline.container.scrollTop = timeline.container.scrollHeight;
+ await vi.waitFor(() => expect([paintedIn(near!), paintedIn(far!)]).toEqual([0, 1]));
+});
+
+it("paints a row's matches once the hidden wrapper around it is revealed", async () => {
+ using timeline = mountTimeline(
+ `
e e
`,
+ );
+ const text = timeline.container.querySelector("[data-thread-find-text]")!;
+ await using _screen = await render(
+ {}}
+ />,
+ );
+ expect(paintedIn(text)).toBe(0);
+
+ timeline.container.querySelector("#wrap")!.removeAttribute("hidden");
+ await vi.waitFor(() => expect(paintedIn(text)).toBe(2));
});
diff --git a/apps/web/src/components/chat/threadFindHighlights.ts b/apps/web/src/components/chat/threadFindHighlights.ts
index 54ee159e1b286..c8ce0b31b9c9e 100644
--- a/apps/web/src/components/chat/threadFindHighlights.ts
+++ b/apps/web/src/components/chat/threadFindHighlights.ts
@@ -2,6 +2,8 @@ import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
import { useEffect, useEffectEvent, useRef } from "react";
import { THREAD_FIND_BLOCK_TAGS } from "@t3tools/shared/threadFindText";
+import { observeResize } from "~/lib/observeResize";
+
const THREAD_FIND_HIGHLIGHT_NAME = "t3-thread-find";
const THREAD_FIND_ACTIVE_HIGHLIGHT_NAME = "t3-thread-find-active";
@@ -160,9 +162,19 @@ export function useThreadFindHighlights(input: {
}
for (const row of cache.keys()) if (!rows.has(row)) cache.delete(row);
rangesRef.current = ranges;
- paint(ranges, readSelection());
+ paint.update(cache, ranges, readSelection());
};
let frame: number | null = null;
+ let dirty = false;
+ const schedule = () => {
+ if (frame !== null) return;
+ frame = requestAnimationFrame(() => {
+ frame = null;
+ if (dirty) repaint();
+ else paint.place(cache);
+ dirty = false;
+ });
+ };
const observer = new MutationObserver((mutations) => {
// Ignore timer and status mutations outside searchable text and folds.
const relevant = mutations.filter(affectsSearchableText);
@@ -174,12 +186,12 @@ export function useThreadFindHighlights(input: {
: mutation.target.parentElement;
const row = target?.closest("[data-timeline-row-id]");
if (row) cache.delete(row);
+ // A hidden wrapper around rows changes their runs, which are cached with their matches.
+ if (mutation.attributeName === "hidden" && target)
+ for (const cached of cache.keys()) if (target.contains(cached)) cache.delete(cached);
}
- if (frame !== null) return;
- frame = requestAnimationFrame(() => {
- frame = null;
- repaint();
- });
+ dirty = true;
+ schedule();
});
observer.observe(container, {
subtree: true,
@@ -195,10 +207,14 @@ export function useThreadFindHighlights(input: {
"data-thread-find-ignore",
],
});
+ container.addEventListener("scroll", schedule, { passive: true });
+ const stopResize = observeResize(container, schedule);
// Revealing the first match can synchronously mount or recycle list rows.
repaint();
return () => {
observer.disconnect();
+ stopResize();
+ container.removeEventListener("scroll", schedule);
if (frame !== null) cancelAnimationFrame(frame);
cache.clear();
paintRef.current = null;
@@ -211,7 +227,7 @@ export function useThreadFindHighlights(input: {
// layout inputs, and repainting the active highlight for those is wasted work.
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- repaints the active CSS Highlight range when the selected match changes
useEffect(() => {
- paintRef.current?.(rangesRef.current, {
+ paintRef.current?.select({
activeRowId,
activeOccurrence,
onActiveRange: readSelection().onActiveRange,
@@ -219,47 +235,188 @@ export function useThreadFindHighlights(input: {
}, [activeOccurrence, activeRowId]);
}
+type ThreadFindSelection = Pick<
+ Parameters[0],
+ "activeRowId" | "activeOccurrence" | "onActiveRange"
+>;
+
+interface TextRun {
+ readonly start: number;
+ end: number;
+ readonly box: Element;
+ readonly item: Node | null;
+ readonly ordered: boolean;
+ readonly hidden: boolean;
+}
+
+const INLINE_DISPLAYS = new Set(["inline", "contents"]);
+const textRunsByMatches = new WeakMap();
+
+// Splits a row's matches into runs that each lie in one inline formatting context,
+// where a later match is never higher on screen. Cells, flex and grid items, and
+// inline blocks each start a run, since their text can sit beside earlier text.
+function textRuns(row: Element, matches: readonly ThreadFindRange[]): readonly TextRun[] {
+ const cached = textRunsByMatches.get(matches);
+ if (cached) return cached;
+ const displays = new Map();
+ const displayOf = (element: Element) => {
+ let display = displays.get(element);
+ if (display === undefined) {
+ display = getComputedStyle(element).display;
+ displays.set(element, display);
+ }
+ return display;
+ };
+ const columns = new Map();
+ const inColumns = (element: Element): boolean => {
+ let multicol = columns.get(element);
+ if (multicol === undefined) {
+ const style = getComputedStyle(element);
+ multicol =
+ style.columnCount !== "auto" ||
+ style.columnWidth !== "auto" ||
+ (element !== row && element.parentElement !== null && inColumns(element.parentElement));
+ columns.set(element, multicol);
+ }
+ return multicol;
+ };
+ const runs: TextRun[] = [];
+ let text: Node | null = null;
+ for (const [index, { range }] of matches.entries()) {
+ const last = runs.at(-1);
+ if (last && range.startContainer === text) {
+ last.end = index + 1;
+ continue;
+ }
+ const parent = range.startContainer.parentElement;
+ if (!parent) continue;
+ text = range.startContainer;
+ let box = parent;
+ while (box !== row && box.parentElement && INLINE_DISPLAYS.has(displayOf(box)))
+ box = box.parentElement;
+ // Text directly inside a flex or grid container is an anonymous item of its own.
+ const item = /flex|grid/.test(displayOf(box)) ? text : null;
+ const hidden = parent.closest("[hidden]") !== null;
+ if (last?.end === index && last.box === box && last.item === item && last.hidden === hidden) {
+ last.end = index + 1;
+ continue;
+ }
+ runs.push({ start: index, end: index + 1, box, item, hidden, ordered: !inColumns(box) });
+ }
+ textRunsByMatches.set(matches, runs);
+ return runs;
+}
+
+// Blink rebuilds every registered highlight Range on any DOM or style change, so
+// only matches within a screen of the viewport are painted; the active one always is.
+function matchesInZone(
+ row: Element,
+ matches: readonly ThreadFindRange[],
+ zone: { top: number; bottom: number },
+ shown: Set,
+): void {
+ const rowBox = row.getBoundingClientRect();
+ if (matches.length === 0 || rowBox.bottom < zone.top || rowBox.top > zone.bottom) return;
+ const intersects = (rect: DOMRect) => rect.bottom >= zone.top && rect.top <= zone.bottom;
+ for (const run of textRuns(row, matches)) {
+ if (run.hidden) continue;
+ const boxes = run.box.getClientRects();
+ if (boxes.length === 0 || ![...boxes].some(intersects)) continue;
+ if (!run.ordered) {
+ for (let index = run.start; index < run.end; index++)
+ if (intersects(matches[index]!.range.getBoundingClientRect()))
+ shown.add(matches[index]!.range);
+ continue;
+ }
+ const firstShown = (index: number, high: number): [number, DOMRect | null] => {
+ for (; index < high; index++) {
+ const rect = matches[index]!.range.getBoundingClientRect();
+ if (rect.height > 0) return [index, rect];
+ }
+ return [high, null];
+ };
+ const firstWhere = (isPast: (rect: DOMRect) => boolean) => {
+ let low = run.start;
+ let high = run.end;
+ while (low < high) {
+ const mid = (low + high) >>> 1;
+ const [probe, rect] = firstShown(mid, high);
+ if (!rect || isPast(rect)) high = mid;
+ else low = probe + 1;
+ }
+ return low;
+ };
+ const end = firstWhere((rect) => rect.top > zone.bottom);
+ for (let index = firstWhere((rect) => rect.bottom >= zone.top); index < end; index++)
+ shown.add(matches[index]!.range);
+ }
+}
+
function makeThreadFindHighlightPainter(container: HTMLElement) {
- let previousRanges: readonly ThreadFindRange[] | null = null;
- const rangesByRow = new Map();
const inactive = new Highlight();
const active = new Highlight();
- let previousActive: Range | null = null;
+ const zoned = new Set();
+ const windows = new Map>();
+ const rangesByRow = new Map();
+ let selected: Range | null = null;
CSS.highlights.set(THREAD_FIND_HIGHLIGHT_NAME, inactive);
CSS.highlights.set(THREAD_FIND_ACTIVE_HIGHLIGHT_NAME, active);
- return (
- ranges: readonly ThreadFindRange[],
- selection: Pick<
- Parameters[0],
- "activeRowId" | "activeOccurrence" | "onActiveRange"
- >,
- ) => {
- if (previousRanges !== ranges) {
- previousRanges = ranges;
- previousActive = null;
- rangesByRow.clear();
- inactive.clear();
- for (const match of ranges) {
- const row = rangesByRow.get(match.rowId) ?? [];
- row[match.occurrence] = match.range;
- rangesByRow.set(match.rowId, row);
- if (foldsHiding(match.range, container).length === 0) inactive.add(match.range);
- }
+ const show = (range: Range) => {
+ zoned.add(range);
+ if (range !== selected && foldsHiding(range, container).length === 0) inactive.add(range);
+ };
+ const hide = (range: Range) => {
+ zoned.delete(range);
+ inactive.delete(range);
+ };
+ const place = (rows: ReadonlyMap) => {
+ const viewport = container.getBoundingClientRect();
+ const zone = { top: viewport.top - viewport.height, bottom: viewport.bottom + viewport.height };
+ for (const [row, previous] of windows) {
+ if (rows.has(row)) continue;
+ for (const range of previous) hide(range);
+ windows.delete(row);
+ }
+ for (const [row, matches] of rows) {
+ const shown = new Set();
+ matchesInZone(row, matches, zone, shown);
+ const previous = windows.get(row);
+ if (previous) for (const range of previous) if (!shown.has(range)) hide(range);
+ for (const range of shown) if (!previous?.has(range)) show(range);
+ windows.set(row, shown);
}
- if (previousActive && foldsHiding(previousActive, container).length === 0)
- inactive.add(previousActive);
- const selected =
+ };
+ const select = (selection: ThreadFindSelection) => {
+ const next =
selection.activeRowId === null
? null
: (rangesByRow.get(selection.activeRowId)?.[selection.activeOccurrence] ?? null);
+ if (selected && selected !== next && zoned.has(selected)) {
+ if (foldsHiding(selected, container).length === 0) inactive.add(selected);
+ }
+ selected = next;
active.clear();
- if (selected) inactive.delete(selected);
- previousActive = selected;
- if (selected && revealFolded(selected, container)) {
+ if (next) inactive.delete(next);
+ if (next && revealFolded(next, container)) {
selection.onActiveRange(null);
} else {
- if (selected) active.add(selected);
- selection.onActiveRange(selected);
+ if (next) active.add(next);
+ selection.onActiveRange(next);
+ }
+ };
+ const update = (
+ rows: ReadonlyMap,
+ ranges: readonly ThreadFindRange[],
+ selection: ThreadFindSelection,
+ ) => {
+ rangesByRow.clear();
+ for (const match of ranges) {
+ const row = rangesByRow.get(match.rowId) ?? [];
+ row[match.occurrence] = match.range;
+ rangesByRow.set(match.rowId, row);
}
+ place(rows);
+ select(selection);
};
+ return { update, place, select };
}
diff --git a/scripts/scenarios/thread-find-paint-bound.e2e.ts b/scripts/scenarios/thread-find-paint-bound.e2e.ts
new file mode 100644
index 0000000000000..9c0be796fcdca
--- /dev/null
+++ b/scripts/scenarios/thread-find-paint-bound.e2e.ts
@@ -0,0 +1,75 @@
+import { expect } from "e2e";
+
+import { test, WEB } from "./t3.ts";
+
+// The thread CLI takes at most 120,000 characters per message: 3,000 lines of ten "the".
+const SEEDED_MATCHES = 30_000;
+const LONG_MESSAGE = Array.from({ length: SEEDED_MATCHES / 10 }, () =>
+ "the ".repeat(10).trim(),
+).join("\n");
+
+const findTotal = `(() => {
+ const label = document.querySelector("[data-thread-find-bar] span[aria-hidden]")?.textContent ?? "";
+ const match = /^\\d+\\/(\\d+)$/.exec(label.trim());
+ return match ? Number(match[1]) : 0;
+})()`;
+
+const paint = `(() => {
+ const inactive = CSS.highlights.get("t3-thread-find");
+ const active = CSS.highlights.get("t3-thread-find-active");
+ let onScreen = 0;
+ for (const highlight of [inactive, active])
+ for (const range of highlight ?? []) {
+ const rect = range.getBoundingClientRect();
+ if (rect.height > 0 && rect.bottom >= 0 && rect.top <= innerHeight) onScreen++;
+ }
+ return {
+ registered: (inactive?.size ?? 0) + (active?.size ?? 0),
+ active: active?.size ?? 0,
+ onScreen,
+ };
+})()`;
+
+test(
+ "Find paints only matches near the viewport of a message with 30,000 matches",
+ WEB,
+ async ({ t3, app, screen, browser }) => {
+ const project = await t3.project("find-paint");
+ const thread = await t3.thread({
+ project,
+ title: "Paint bound proof",
+ messages: [LONG_MESSAGE],
+ });
+ await t3.open(thread);
+ await expect(screen.getByText("first fixture turn complete", { exact: false })).toBeVisible({
+ timeout: 120_000,
+ });
+
+ // The CLI's message folds to one line; find unfolds it to reach the first match.
+ await browser.keyboard.press("Control+f");
+ const find = screen.getByRole("searchbox", "Find in thread");
+ await expect(find).toBeVisible();
+ await find.fill("the");
+ // The count is the server's: every match in the thread, whatever is painted.
+ await expect
+ .poll(() => browser.evaluate(findTotal), { timeout: 60_000 })
+ .toBeGreaterThanOrEqual(SEEDED_MATCHES);
+ await expect
+ .poll(async () => (await browser.evaluate<{ active: number }>(paint)).active, {
+ timeout: 30_000,
+ })
+ .toBe(1);
+
+ try {
+ const painted = await browser.evaluate<{
+ registered: number;
+ active: number;
+ onScreen: number;
+ }>(paint);
+ expect(painted.onScreen).toBeGreaterThan(0);
+ expect(painted.registered).toBeLessThan(5_000);
+ } finally {
+ await app.screenshot("find-open-paint");
+ }
+ },
+);
From 73e62fcecc5e07de840e2b03a8efd9c45cbe52cf Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Tue, 17 Nov 2026 14:23:35 -0800
Subject: [PATCH 067/122] fix(server): Copilot MCP calls and glob searches keep
their identity (#38349)
---
.../Adapters/AcpRegistryAdapterV2.test.ts | 103 ++++++++++++++++++
.../src/server/copilotAcp.ts | 53 ++++++++-
2 files changed, 153 insertions(+), 3 deletions(-)
diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
index ee82cc06de836..495f16646a61d 100644
--- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
@@ -1997,6 +1997,109 @@ describe("AcpRegistryAdapterV2", () => {
}).pipe(Effect.provide(layerTest)),
);
+ // Copilot flattens MCP titles and reports kind "read" for MCP calls and glob; its native
+ // tool.execution_start event carries the real identity.
+ it.effect("keeps Copilot's MCP and search tool identity instead of calling them file reads", () =>
+ Effect.gen(function* () {
+ const sessionId = "copilot-session";
+ const executionStart = (data: Record) => ({
+ type: "emit_inbound",
+ frame: {
+ kind: "notification",
+ method: "github.com/copilot/sessionEvent",
+ params: { sessionId, type: "tool.execution_start", data },
+ },
+ });
+ const update = (sessionUpdate: Record) =>
+ claudeFrames.update(sessionId, sessionUpdate);
+ const session = yield* openClaudeReplaySession(
+ [
+ {
+ type: "expect_outbound",
+ frame: { kind: "request", method: "initialize", params: "" },
+ },
+ {
+ type: "emit_inbound",
+ frame: {
+ kind: "response",
+ method: "initialize",
+ result: {
+ protocolVersion: 1,
+ agentInfo: { name: "Copilot", version: "1.0.112" },
+ agentCapabilities: { loadSession: true },
+ authMethods: [],
+ },
+ },
+ },
+ {
+ type: "expect_outbound",
+ frame: { kind: "request", method: "session/new", params: "" },
+ },
+ {
+ type: "emit_inbound",
+ frame: { kind: "response", method: "session/new", result: { sessionId } },
+ },
+ {
+ type: "expect_outbound",
+ frame: { kind: "request", method: "session/prompt", params: "" },
+ },
+ executionStart({
+ toolCallId: "mcp-call",
+ mcpServerName: "demo-library",
+ mcpToolName: "search_books",
+ }),
+ update({
+ sessionUpdate: "tool_call",
+ toolCallId: "mcp-call",
+ title: "demo-library-search_books",
+ kind: "read",
+ status: "completed",
+ rawInput: { arguments: { query: "paper airplanes" }, limit: 2 },
+ }),
+ executionStart({
+ toolCallId: "native-search",
+ toolName: "glob",
+ toolTitle: "Finding files",
+ arguments: { pattern: "*.ts", paths: ["/workspace"] },
+ }),
+ update({
+ sessionUpdate: "tool_call",
+ toolCallId: "native-search",
+ title: "Finding files matching *.ts",
+ kind: "read",
+ status: "completed",
+ rawInput: { pattern: "*.ts", paths: ["/workspace"] },
+ locations: [{ path: "/workspace" }],
+ }),
+ update({ sessionUpdate: "session_info_update", title: "after tools" }),
+ ],
+ undefined,
+ false,
+ "github-copilot-cli",
+ );
+ yield* session.runtime.startTurn(session.turnInput(1));
+ const events = yield* session.throughMarker("after tools");
+ const lastItem = (nativeId: string) =>
+ events
+ .flatMap((event) =>
+ event.type === "turn_item.updated" &&
+ event.turnItem.nativeItemRef?.nativeId === nativeId
+ ? [event.turnItem]
+ : [],
+ )
+ .at(-1);
+ const mcp = lastItem("mcp-call");
+ const search = lastItem("native-search");
+ assert.deepEqual(
+ {
+ mcp: mcp?.type === "dynamic_tool" ? mcp.toolName : mcp?.type,
+ search: search?.type === "dynamic_tool" ? search.toolName : search?.type,
+ },
+ { mcp: "demo-library.search_books", search: "file_search" },
+ );
+ }).pipe(Effect.provide(layerTest)),
+ );
+
it.effect.each([
{ kind: "approval", stopReason: "end_turn", status: "completed" },
{ kind: "question", stopReason: "error", status: "failed" },
diff --git a/packages/provider-acp-registry/src/server/copilotAcp.ts b/packages/provider-acp-registry/src/server/copilotAcp.ts
index 8482886892985..7b5027147c073 100644
--- a/packages/provider-acp-registry/src/server/copilotAcp.ts
+++ b/packages/provider-acp-registry/src/server/copilotAcp.ts
@@ -24,6 +24,7 @@ export const copilotClientCapabilitiesMeta = {
"session.compaction_complete",
"assistant.turn_start",
"assistant.idle",
+ "tool.execution_start",
],
},
};
@@ -63,9 +64,26 @@ function record(value: unknown): Record | undefined {
const childSessionId = (taskToolCallId: string) => `copilot-task:${taskToolCallId}`;
+// Copilot's tool_call reports MCP calls and glob/grep as kind "read" under a flattened title.
+type CopilotToolIdentity =
+ | { readonly kind: "mcp"; readonly server: string; readonly tool: string }
+ | { readonly kind: "search" };
+
+const COPILOT_SEARCH_TOOLS = new Set(["glob", "grep"]);
+
interface CopilotSessionAttribution {
delta: { readonly kind: string; readonly text: string; readonly task?: string } | undefined;
readonly taskByAgentId: Map;
+ readonly toolIdentityByCallId: Map;
+}
+
+function copilotToolIdentity(data: Record): CopilotToolIdentity | undefined {
+ const server = typeof data.mcpServerName === "string" ? data.mcpServerName.trim() : "";
+ const tool = typeof data.mcpToolName === "string" ? data.mcpToolName.trim() : "";
+ if (server.length > 0 && tool.length > 0) return { kind: "mcp", server, tool };
+ return typeof data.toolName === "string" && COPILOT_SEARCH_TOOLS.has(data.toolName)
+ ? { kind: "search" }
+ : undefined;
}
export function makeCopilotSubagentRouting() {
@@ -73,13 +91,17 @@ export function makeCopilotSubagentRouting() {
const session = (sessionId: string) => {
let current = sessions.get(sessionId);
if (current === undefined) {
- current = { delta: undefined, taskByAgentId: new Map() };
+ current = { delta: undefined, taskByAgentId: new Map(), toolIdentityByCallId: new Map() };
sessions.set(sessionId, current);
}
return current;
};
const release = (sessionId: string, current: CopilotSessionAttribution) => {
- if (current.delta === undefined && current.taskByAgentId.size === 0) {
+ if (
+ current.delta === undefined &&
+ current.taskByAgentId.size === 0 &&
+ current.toolIdentityByCallId.size === 0
+ ) {
sessions.delete(sessionId);
}
};
@@ -105,6 +127,13 @@ export function makeCopilotSubagentRouting() {
}
return Effect.void;
}
+ case "tool.execution_start": {
+ const identity = copilotToolIdentity(data);
+ if (identity !== undefined && typeof data.toolCallId === "string") {
+ session(event.sessionId).toolIdentityByCallId.set(data.toolCallId, identity);
+ }
+ return Effect.void;
+ }
case "subagent.completed":
case "subagent.failed": {
const current = sessions.get(event.sessionId);
@@ -154,6 +183,7 @@ export function makeCopilotSubagentRouting() {
const current = sessions.get(notification.sessionId);
if (current === undefined) return notification;
let task: string | undefined;
+ let normalized = notification;
if (
update.sessionUpdate === "agent_message_chunk" ||
update.sessionUpdate === "agent_thought_chunk"
@@ -178,8 +208,25 @@ export function makeCopilotSubagentRouting() {
) {
const agentId = record(record(update._meta)?.[COPILOT_META_KEY])?.agentId;
task = typeof agentId === "string" ? current.taskByAgentId.get(agentId) : undefined;
+ const identity = current.toolIdentityByCallId.get(update.toolCallId);
+ if (identity !== undefined) {
+ if (update.status === "completed" || update.status === "failed") {
+ current.toolIdentityByCallId.delete(update.toolCallId);
+ release(notification.sessionId, current);
+ }
+ normalized = {
+ ...notification,
+ update:
+ identity.kind === "search"
+ ? { ...update, kind: "search" }
+ : {
+ ...update,
+ _meta: { ...update._meta, serverId: identity.server, toolName: identity.tool },
+ },
+ };
+ }
}
- return task === undefined ? notification : { ...notification, sessionId: childSessionId(task) };
+ return task === undefined ? normalized : { ...normalized, sessionId: childSessionId(task) };
};
return { registerExtensions, normalizeSessionUpdate };
From 7b4478895daf4f71da216131dbb629ba04271dcf Mon Sep 17 00:00:00 2001
From: Simone
Date: Tue, 17 Nov 2026 23:25:09 +0100
Subject: [PATCH 068/122] fix(server): omit page-specific headers and footers
from RTF text (#38347)
Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com>
Co-authored-by: Julius Marminge
---
apps/server/src/provider/documentTextWorker.ts | 6 ++++++
apps/server/src/provider/userInputAttachments.test.ts | 11 ++++++++++-
2 files changed, 16 insertions(+), 1 deletion(-)
diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts
index ed67cba63f472..57f154204a563 100644
--- a/apps/server/src/provider/documentTextWorker.ts
+++ b/apps/server/src/provider/documentTextWorker.ts
@@ -454,7 +454,13 @@ function* rtf(source: string): Generator {
"object",
"fldinst",
"header",
+ "headerf",
+ "headerl",
+ "headerr",
"footer",
+ "footerf",
+ "footerl",
+ "footerr",
].includes(control)
)
state.skip = true;
diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts
index 79a9f0539534b..f54b748a5701e 100644
--- a/apps/server/src/provider/userInputAttachments.test.ts
+++ b/apps/server/src/provider/userInputAttachments.test.ts
@@ -277,6 +277,15 @@ describe("question answer paths", () => {
);
it.effect.each([
+ [
+ "page-specific headers and footers",
+ String.raw`{\rtf1\ansi\facingp\sectd\titlepg
+{\headerf First-page header}{\headerl Left-page header}{\headerr Right-page header}
+{\footerf First-page footer}{\footerl Left-page footer}{\footerr Right-page footer}
+\pard Approved delivery date: 24 November.\par
+}`,
+ "Approved delivery date: 24 November.",
+ ],
[
"text symbols",
String.raw`{\rtf1\ansi Pages 1\endash 5\emdash\lquote left\rquote\ldblquote right\rdblquote\bullet\b End\b0\unknown{\*\secret\bullet hidden}}`,
@@ -310,7 +319,7 @@ describe("question answer paths", () => {
["large fallback", String.raw`{\rtf1\ansi\uc20\u945????????????????????Z}`, "αZ"],
["no fallback", String.raw`{\rtf1\ansi\uc0\u945Z}`, "αZ"],
["scoped count", String.raw`{\rtf1\ansi{\uc2\u945??}\u946?Z}`, "αβZ"],
- ] as const)("extracts RTF symbols and Unicode fallbacks: %s", ([name, source, expected]) =>
+ ] as const)("extracts RTF text: %s", ([name, source, expected]) =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const path = NodePath.join(config.attachmentsDir, `${name}.rtf`);
From 856c84e4b14653facaa3ee320cd165e4e1b103c1 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Tue, 17 Nov 2026 15:37:35 -0800
Subject: [PATCH 069/122] fix(desktop): picked element keeps its screenshot
when the page re-renders before Attach (#38357)
---
apps/desktop/src/preview/PickPreload.test.ts | 45 +++++++++++++++++++-
apps/desktop/src/preview/PickPreload.ts | 19 +++++++--
2 files changed, 59 insertions(+), 5 deletions(-)
diff --git a/apps/desktop/src/preview/PickPreload.test.ts b/apps/desktop/src/preview/PickPreload.test.ts
index 61d3941ba41ab..abf9421985f21 100644
--- a/apps/desktop/src/preview/PickPreload.test.ts
+++ b/apps/desktop/src/preview/PickPreload.test.ts
@@ -1,9 +1,10 @@
import { expect, it, vi } from "vite-plus/test";
-import { START_PICK_CHANNEL } from "./GuestProtocol.ts";
+import { ELEMENT_PICKED_CHANNEL, START_PICK_CHANNEL } from "./GuestProtocol.ts";
import "./PickPreload.ts";
const ipcListeners = vi.hoisted(() => new Map void>>());
+const ipcSend = vi.hoisted(() => ({ calls: [] as unknown[][] }));
vi.mock("electron", () => ({
ipcRenderer: {
@@ -11,7 +12,9 @@ vi.mock("electron", () => ({
ipcListeners.set(channel, [...(ipcListeners.get(channel) ?? []), listener]);
},
off: () => {},
- send: () => {},
+ send: (...args: unknown[]) => {
+ ipcSend.calls.push(args);
+ },
invoke: async () => undefined,
},
}));
@@ -105,3 +108,41 @@ it("keeps the annotation when Escape dismisses an IME candidate in the comment",
expect(shadowRoot.host.isConnected).toBe(true);
expect(comment.value).toBe("draft");
});
+
+it.each([
+ { scrolled: false, rect: { x: 40, y: 60, width: 200, height: 120 } },
+ // The last rect would point at whatever now sits there, so no crop beats a wrong one.
+ { scrolled: true, rect: { x: 0, y: 0, width: 0, height: 0 } },
+])(
+ "submits a replaced element's last rect unless the page scrolled ($scrolled)",
+ async ({ scrolled, rect }) => {
+ ipcSend.calls.length = 0;
+ const card = document.body.appendChild(document.createElement("div"));
+ const pickedRect = new DOMRect(40, 60, 200, 120);
+ // Browsers report a detached element at 0x0 in the corner.
+ using _rect = vi
+ .spyOn(card, "getBoundingClientRect")
+ .mockImplementation(() => (card.isConnected ? pickedRect : new DOMRect()));
+ document.elementsFromPoint = () => [card];
+ const shadowRoot = startAnnotation();
+
+ card.dispatchEvent(
+ new PointerEvent("pointerdown", { button: 0, clientX: 100, clientY: 100, bubbles: true }),
+ );
+ // A polling page re-renders while the comment is written and replaces the picked node.
+ card.replaceWith(document.createElement("div"));
+ if (scrolled) window.dispatchEvent(new Event("scroll"));
+ const attach = Array.from(shadowRoot.querySelectorAll("button")).find(
+ (button) => button.textContent === "Attach",
+ );
+ if (!attach) throw new Error("Attach button not found");
+ attach.click();
+
+ await vi.waitFor(() =>
+ expect(ipcSend.calls.some(([channel]) => channel === ELEMENT_PICKED_CHANNEL)).toBe(true),
+ );
+ const [, annotation] =
+ ipcSend.calls.find(([channel]) => channel === ELEMENT_PICKED_CHANNEL) ?? [];
+ expect((annotation as { elements: Array<{ rect: unknown }> }).elements[0]?.rect).toEqual(rect);
+ },
+);
diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts
index 42867b9d9cb44..14ae5b16f33d6 100644
--- a/apps/desktop/src/preview/PickPreload.ts
+++ b/apps/desktop/src/preview/PickPreload.ts
@@ -151,6 +151,8 @@ interface SelectedElement {
outline: HTMLDivElement;
label: HTMLDivElement;
baselineStyles: Map;
+ // Last rect measured while connected; a detached node reports 0x0.
+ rect: PreviewAnnotationRect;
}
interface AnnotationSession {
@@ -417,6 +419,7 @@ function updateSelectedVisual(target: SelectedElement): void {
target.label.style.display = "none";
return;
}
+ target.rect = rectFromDomRect(target.element.getBoundingClientRect());
const rect = visibleElementRect(target.element);
positionBox(target.outline, rect);
if (rect.width === 0 || rect.height === 0) {
@@ -966,6 +969,7 @@ function startAnnotation(
outline: createBox(PRIMARY, PRIMARY_FILL),
label: createLabel(),
baselineStyles: new Map(),
+ rect: rectFromDomRect(element.getBoundingClientRect()),
};
selected.set(element, target);
root.append(target.outline, target.label);
@@ -1392,6 +1396,13 @@ function startAnnotation(
for (const target of selected.values()) updateSelectedVisual(target);
queueEditorLayout();
};
+ const onScroll = (): void => {
+ // A detached element's last rect no longer matches what is on screen once the page scrolls.
+ for (const target of selected.values()) {
+ if (!target.element.isConnected) target.rect = { x: 0, y: 0, width: 0, height: 0 };
+ }
+ repaint();
+ };
// A scrollbar appearing narrows the viewport without a window resize.
const rootResizeObserver = new ResizeObserver(repaint);
@@ -1626,7 +1637,7 @@ function startAnnotation(
window.removeEventListener("focus", onWindowFocus);
window.removeEventListener("keydown", onKeyDown, true);
window.removeEventListener("keyup", onVoiceKeyUp, true);
- window.removeEventListener("scroll", repaint, true);
+ window.removeEventListener("scroll", onScroll, true);
window.removeEventListener("resize", repaint);
dragHandle.removeEventListener("pointerdown", onEditorPointerDown);
dragHandle.removeEventListener("pointermove", onEditorPointerMove);
@@ -1723,7 +1734,9 @@ function startAnnotation(
return {
id: target.id,
element,
- rect: rectFromDomRect(target.element.getBoundingClientRect()),
+ rect: target.element.isConnected
+ ? rectFromDomRect(target.element.getBoundingClientRect())
+ : target.rect,
};
}),
)
@@ -1785,7 +1798,7 @@ function startAnnotation(
window.addEventListener("focus", onWindowFocus);
window.addEventListener("keydown", onKeyDown, { capture: true });
window.addEventListener("keyup", onVoiceKeyUp, { capture: true });
- window.addEventListener("scroll", repaint, { capture: true, passive: true });
+ window.addEventListener("scroll", onScroll, { capture: true, passive: true });
window.addEventListener("resize", repaint, { passive: true });
// Bubble phase, so the overlay's own handlers still see these events.
for (const type of PAGE_ISOLATED_EVENTS)
From 24467d671d182bdac5915088bed23a4d34a46dfe Mon Sep 17 00:00:00 2001
From: Martin Bergo
Date: Wed, 18 Nov 2026 01:28:02 +0100
Subject: [PATCH 070/122] fix(client): a subagent prompt that opens with
comment dividers no longer freezes the thread (#38368)
Co-authored-by: Julius Marminge
---
.../client-runtime/src/state/subagentRuntime.test.ts | 12 ++++++++++++
packages/client-runtime/src/state/subagentRuntime.ts | 4 +++-
2 files changed, 15 insertions(+), 1 deletion(-)
diff --git a/packages/client-runtime/src/state/subagentRuntime.test.ts b/packages/client-runtime/src/state/subagentRuntime.test.ts
index 7be9639bafedb..3512956af25fc 100644
--- a/packages/client-runtime/src/state/subagentRuntime.test.ts
+++ b/packages/client-runtime/src/state/subagentRuntime.test.ts
@@ -316,5 +316,17 @@ describe("resolveWorkflowOpening", () => {
false,
);
expect(isWorkflowScriptMessage({ role: "assistant", text: SCRIPT })).toBe(false);
+ expect(
+ isWorkflowScriptMessage({ role: "user", text: `// a\r// b\u2028/* c\n * d */\r\n${SCRIPT}` }),
+ ).toBe(true);
+ expect(isWorkflowScriptMessage({ role: "user", text: "// export const meta = {}" })).toBe(
+ false,
+ );
+ // Divider comments ahead of ordinary code must reject without catastrophic backtracking.
+ const dividers = `${"/".repeat(40)}\n`.repeat(40);
+ expect(isWorkflowScriptMessage({ role: "user", text: `${dividers}const x = 1;` })).toBe(false);
+ expect(
+ isWorkflowScriptMessage({ role: "user", text: `${"/**/".repeat(200)}const x = 1;` }),
+ ).toBe(false);
});
});
diff --git a/packages/client-runtime/src/state/subagentRuntime.ts b/packages/client-runtime/src/state/subagentRuntime.ts
index a971eef5efc77..ceee780057d55 100644
--- a/packages/client-runtime/src/state/subagentRuntime.ts
+++ b/packages/client-runtime/src/state/subagentRuntime.ts
@@ -325,7 +325,9 @@ export function deriveWorkflowGroups(
}
// Workflow scripts open with their `meta` export, after any leading comments.
-const WORKFLOW_SCRIPT_START = /^\s*(?:(?:\/\/[^\n]*|\/\*[\s\S]*?\*\/)\s*)*export\s+const\s+meta\b/;
+// Each comment has one way to match, so a prompt of `////` divider lines cannot backtrack.
+const WORKFLOW_SCRIPT_START =
+ /^\s*(?:(?:\/\/[^\r\n\u2028\u2029]*(?:[\r\n\u2028\u2029]|$)|\/\*(?:[^*]|\*(?!\/))*\*\/)\s*)*export\s+const\s+meta\b/;
/**
* Whether a user message is the script a provider-native workflow runs. Servers mark every
From ef5772805916a97e9522feaaefcf9e0b5c3b92ff Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Tue, 17 Nov 2026 16:28:46 -0800
Subject: [PATCH 071/122] fix(gitlab): GitLab issues open again; issue
reactions come from REST (#38383)
---
.../src/server/GitLabIssueTracker.test.ts | 14 +++++++++++--
.../src/server/GitLabIssueTracker.ts | 12 ++++++++++-
.../src/server/gitLabIssueJson.ts | 6 +++---
.../src/server/gitLabMergeRequestJson.ts | 21 +++++++++++++++++++
4 files changed, 47 insertions(+), 6 deletions(-)
diff --git a/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts b/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts
index 9b6e23b16d0e5..18c3c7709f52a 100644
--- a/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts
+++ b/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts
@@ -92,13 +92,15 @@ function answer(path: string): string {
},
]);
}
+ if (path.startsWith("projects/acme%2Fweb/issues/42/award_emoji")) {
+ return encode([{ id: 11, name: "eyes", user: { username: "theo" } }]);
+ }
if (path === "graphql") {
return encode({
data: {
currentUser: { username: "julius" },
project: {
mergeRequest: {
- awardEmoji: { nodes: [{ name: "eyes", user: { username: "theo" } }] },
notes: {
pageInfo: { hasNextPage: false },
nodes: [
@@ -144,7 +146,15 @@ describe("GitLabIssueTracker", () => {
const awardCursors: unknown[] = [];
const api = yield* tracker((args, input) => {
hosts.add(input.host);
- if (args[1] === "graphql") awardCursors.push(JSON.parse(input.stdin!).variables.cursor);
+ if (args[1] === "graphql") {
+ const request = JSON.parse(input.stdin!);
+ // gitlab.com's schema has no `Issue.awardEmoji`; glab exits 1 on such a query.
+ const issueFields = /issue\(iid: \$iid\) \{([\s\S]*?)notes\(/.exec(request.query)?.[1];
+ if (issueFields?.includes("awardEmoji")) {
+ throw new Error("Field 'awardEmoji' doesn't exist on type 'Issue'");
+ }
+ awardCursors.push(request.variables.cursor);
+ }
return answer(args[1]!);
});
const target = { cwd: "/w", host: "gitlab.example.com", scope: "acme/web", key: "42" };
diff --git a/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts b/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts
index e30dcc18b256a..8206b572ece5d 100644
--- a/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts
+++ b/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts
@@ -37,7 +37,9 @@ import {
type GitLabTemplateEntry,
} from "./gitLabIssueJson.ts";
import {
+ awardReactions,
decodeAwardEmojiJson,
+ decodeAwardListJson,
decodeOwnAwardIdJson,
decodeViewerJson,
gitLabAwardName,
@@ -523,6 +525,13 @@ export const make: Effect.Effect =
number,
operation: "getIssue",
}),
+ read({
+ cwd: input.cwd,
+ host: input.host,
+ operation: "getIssue",
+ path: paged(`${path}/award_emoji`, 1),
+ decode: decodeAwardListJson,
+ }),
],
{ concurrency: 4 },
),
@@ -537,6 +546,7 @@ export const make: Effect.Effect =
closing,
related,
awardPage,
+ issueAwards,
]) => {
const closingKeys = new Set(
closing.map((link) => `${link.repository}!${link.number}`),
@@ -546,7 +556,7 @@ export const make: Effect.Effect =
viewer: viewerLogin,
viewerPermissions: VIEWER_PERMISSIONS,
states: ISSUE_STATES,
- reactions: awardPage.reactions,
+ reactions: awardReactions(issueAwards, viewerLogin),
comments: notes.comments.map((comment) => ({
...comment,
reactions: awardPage.reactionsByNoteId.get(comment.id) ?? [],
diff --git a/packages/source-control-gitlab/src/server/gitLabIssueJson.ts b/packages/source-control-gitlab/src/server/gitLabIssueJson.ts
index 7f649eeeb9f1a..91495e43ed00f 100644
--- a/packages/source-control-gitlab/src/server/gitLabIssueJson.ts
+++ b/packages/source-control-gitlab/src/server/gitLabIssueJson.ts
@@ -409,14 +409,14 @@ export function decodeTemplateJson(
}
/**
- * Awards on the issue and on every note of it, in one read, shaped exactly like the merge request
- * query so its decoder answers for both: `mergeRequest` is an alias for the issue field.
+ * Awards on every note of the issue, shaped like the merge request query so its decoder answers
+ * for both: `mergeRequest` is an alias for the issue field. GitLab's `Issue` type has no
+ * `awardEmoji`, so the issue's own awards are read from REST `award_emoji` instead.
*/
export const ISSUE_AWARD_EMOJI_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!, $cursor: String) {
currentUser { username }
project(fullPath: $fullPath) {
mergeRequest: issue(iid: $iid) {
- awardEmoji { nodes { name user { username } } }
notes(first: ${PAGE_SIZE}, after: $cursor) {
pageInfo { hasNextPage endCursor }
nodes { id awardEmoji { nodes { name user { username } } } }
diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
index 995ae74939260..00daa58f026d9 100644
--- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
+++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
@@ -1304,6 +1304,27 @@ const RawAwardSchema = Schema.Struct({
const decodeAward = Schema.decodeUnknownExit(RawAwardSchema);
+type GitLabAward = typeof RawAwardSchema.Type;
+
+/** A page of REST `award_emoji`; a row that cannot be read is skipped. */
+export function decodeAwardListJson(
+ raw: string,
+): Result.Result, DecodeFailure> {
+ return Result.map(decodeUnknownList(raw), (rows) =>
+ rows.flatMap((entry) => {
+ const award = decodeAward(entry);
+ return Exit.isSuccess(award) ? [award.value] : [];
+ }),
+ );
+}
+
+export function awardReactions(
+ awards: ReadonlyArray,
+ viewer: string | null,
+): ReadonlyArray {
+ return toReactions({ nodes: awards }, viewer);
+}
+
export function decodeOwnAwardIdJson(
raw: string,
input: { readonly content: PullRequestReactionContent; readonly viewer: string },
From 959c4c1ecf0dac0e6a1ebc83336113ecf91a585d Mon Sep 17 00:00:00 2001
From: Simone
Date: Wed, 18 Nov 2026 01:31:17 +0100
Subject: [PATCH 072/122] fix(server): count only actual slides in PowerPoint
attachment text (#38377)
Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com>
---
.../server/src/provider/documentTextWorker.ts | 8 ++++---
.../src/provider/userInputAttachments.test.ts | 22 ++++++++++++++-----
2 files changed, 21 insertions(+), 9 deletions(-)
diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts
index 57f154204a563..fd723a7c25856 100644
--- a/apps/server/src/provider/documentTextWorker.ts
+++ b/apps/server/src/provider/documentTextWorker.ts
@@ -133,8 +133,8 @@ function xml(source: string, extension: string): XmlNode {
return root;
}
-const children = (node: XmlNode) =>
- node.children.filter((child): child is XmlNode => typeof child !== "string");
+const children = (node: XmlNode | undefined) =>
+ node?.children.filter((child): child is XmlNode => typeof child !== "string") ?? [];
function* all(node: XmlNode, name: string | readonly string[]): Generator {
for (const child of children(node)) {
if (typeof name === "string" ? child.name === name : name.includes(child.name)) yield child;
@@ -630,8 +630,10 @@ async function* document(path: string, extension: string): AsyncGenerator node.name === "sldIdLst");
let index = 0;
- for (const slide of all(read("ppt/presentation.xml"), "sldId")) {
+ for (const slide of children(slideList).filter((node) => node.name === "sldId")) {
yield `\n\n## Slide ${++index}\n`;
const target = rels.get(slide.attrs["r:id"] ?? slide.attrs.id);
if (!target) {
diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts
index f54b748a5701e..b2ea247900b98 100644
--- a/apps/server/src/provider/userInputAttachments.test.ts
+++ b/apps/server/src/provider/userInputAttachments.test.ts
@@ -685,7 +685,7 @@ describe("question answer paths", () => {
ext === "pptx"
? {
"ppt/presentation.xml":
- '',
+ '',
"ppt/_rels/presentation.xml.rels":
'',
"ppt/bad.xml": "
- Loading the rest of the file…
+
+ Loading the rest of the file…
+
) : null}
{meta.columns === 1024 ? (
- Showing the first 1,024 columns. Source and Save retain every column.
+ Showing the first 1,024 columns. Source and Save retain every column.
) : null}
{meta.count > 0 ? (
@@ -256,7 +270,7 @@ export default function LargeTextViewer(props: {
/>
) : (
- This file is empty.
+ This file is empty.
)}
diff --git a/apps/web/src/components/files/MermaidViewer.tsx b/apps/web/src/components/files/MermaidViewer.tsx
index c831c583a51c8..997717bbfe00b 100644
--- a/apps/web/src/components/files/MermaidViewer.tsx
+++ b/apps/web/src/components/files/MermaidViewer.tsx
@@ -1,9 +1,11 @@
+import { T, useGT } from "gt-react";
import { useState } from "react";
import { MermaidDiagram } from "../chat/MermaidDiagram";
import { ExpandedImageDialog } from "../chat/ExpandedImageDialog";
export default function MermaidViewer(props: { readonly text: string }) {
+ const gt = useGT();
const [expanded, setExpanded] = useState(null);
// Mermaid lays out DOM before sanitizing its SVG. Refuse resource and config
// syntax before that pass so standalone files cannot initiate requests. Node
@@ -15,8 +17,10 @@ export default function MermaidViewer(props: { readonly text: string }) {
)
return (
- This diagram contains resource URLs, markup, node metadata, or custom configuration. Show
- Mermaid source to inspect it safely.
+
+ This diagram contains resource URLs, markup, node metadata, or custom configuration. Show
+ Mermaid source to inspect it safely.
+
) : null}
{visible < props.notebook.cells.length ? (
setVisible((count) => count + 20)}>
- Show more cells ({props.notebook.cells.length - visible} remaining)
+ {gt(
+ "{count, plural, one {Show more cells ({count} remaining)} other {Show more cells ({count} remaining)}}",
+ { count: props.notebook.cells.length - visible },
+ )}
) : null}
diff --git a/apps/web/src/components/files/OfficeViewer.tsx b/apps/web/src/components/files/OfficeViewer.tsx
index 76298b545d66b..e35cd9cf63fcc 100644
--- a/apps/web/src/components/files/OfficeViewer.tsx
+++ b/apps/web/src/components/files/OfficeViewer.tsx
@@ -1,8 +1,11 @@
+import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
/* oxlint-disable react/no-array-index-key -- Spreadsheet rows and columns retain their source positions. */
import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
import type { OfficePreviewKind } from "@t3tools/shared/filePreview";
import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
+import { msg, T, useGT, useMessages } from "gt-react";
import { lazy, Suspense, useEffect, useRef, useState } from "react";
+import { m } from "~/i18n/messages";
import VirtualTablePreview from "./VirtualTablePreview";
@@ -16,6 +19,7 @@ import {
import { FileSurfaceAction, FileSurfaceLoading, FileSurfaceNotice } from "./fileSurfaceChrome";
import { OFFICE_PREVIEW_MAX_BYTES, type OfficeWorkerResult } from "./officePreviewProtocol";
+import { previewFailureText } from "./previewFailureMessages";
const DocumentPages = lazy(() => import("./DocumentPages"));
const NotebookPreview = lazy(() => import("./NotebookPreview"));
@@ -26,11 +30,12 @@ const OpenXmlOfficeViewer = lazy(() => import("./OpenXmlOfficeViewer"));
async function readOfficeFile(src: string, signal: AbortSignal) {
const response = await fetch(src, { signal });
- if (!response.ok) throw new Error("The file could not be loaded. Close it and try again.");
+ if (!response.ok)
+ throw new Error(m(msg("The file could not be loaded. Close it and try again.")));
if (Number(response.headers.get("content-length")) > OFFICE_PREVIEW_MAX_BYTES)
- throw new Error("Preview limited to files under 50 MB.");
+ throw new Error(m(msg("Preview limited to files under 50 MB.")));
const reader = response.body?.getReader();
- if (!reader) throw new Error("The file is unavailable.");
+ if (!reader) throw new Error(m(msg("The file is unavailable.")));
const chunks: Uint8Array[] = [];
let size = 0;
try {
@@ -38,7 +43,8 @@ async function readOfficeFile(src: string, signal: AbortSignal) {
const { value, done } = await reader.read();
if (done) break;
size += value.length;
- if (size > OFFICE_PREVIEW_MAX_BYTES) throw new Error("Preview limited to files under 50 MB.");
+ if (size > OFFICE_PREVIEW_MAX_BYTES)
+ throw new Error(m(msg("Preview limited to files under 50 MB.")));
chunks.push(value);
}
} finally {
@@ -68,6 +74,8 @@ function ExtendedOfficeViewer(props: {
readonly kind: OfficePreviewKind;
readonly sizeBytes?: number;
}) {
+ const gt = useGT();
+ const messages = useMessages();
const [error, setError] = useState(null);
const [sheetPages, setSheetPages] = useState(new Map());
const pendingPages = useRef(new Set());
@@ -90,7 +98,7 @@ function ExtendedOfficeViewer(props: {
const controller = new AbortController();
if ((props.sizeBytes ?? 0) > OFFICE_PREVIEW_MAX_BYTES) {
// oxlint-disable-next-line react/set-state-in-effect -- The file metadata can reject the preview before loading bytes or engines.
- setError("Preview limited to files under 50 MB.");
+ setError(m(msg("Preview limited to files under 50 MB.")));
return;
}
const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
@@ -104,16 +112,16 @@ function ExtendedOfficeViewer(props: {
if (timerRef.current) clearTimeout(timerRef.current);
};
timerRef.current = setTimeout(
- () => fail("This document took too long to preview. Open it in another app."),
+ () => fail(m(msg("This document took too long to preview. Open it in another app."))),
30_000,
);
worker.addEventListener("error", () =>
- fail("Could not load the Office viewer. Close the file and try again."),
+ fail(m(msg("Could not load the Office viewer. Close the file and try again."))),
);
worker.addEventListener("message", (event: MessageEvent) => {
if (controller.signal.aborted) return;
const result = event.data;
- if (result.type === "error") fail(result.message);
+ if (result.type === "error") fail(previewFailureText(result));
else if (result.type === "document") {
if (timerRef.current) clearTimeout(timerRef.current);
setDocument(result);
@@ -144,7 +152,7 @@ function ExtendedOfficeViewer(props: {
}
})
.catch((cause: unknown) =>
- fail(cause instanceof Error ? cause.message : "Could not read this file."),
+ fail(thrownErrorMessage(cause, m) ?? m(msg("Could not read this file."))),
);
return () => {
controller.abort();
@@ -160,9 +168,11 @@ function ExtendedOfficeViewer(props: {
role="alert"
className="flex min-h-0 flex-1 flex-col items-center justify-center gap-1 px-6 text-center"
>
-
No preview for this file
+
+ No preview for this file
+
- {error} Save it or open it in another app.
+ {gt("{error} Save it or open it in another app.", { error })}
) : null}
{documentPage ? (
<>
{props.kind !== "epub" ? (
- Text and images. Layout and embedded objects may differ from the original.
+ Text and images. Layout and embedded objects may differ from the original.
) : null}
}>
>
) : sheet ? (
<>
- Cell values only. Charts, images, and formatting are not shown.
{sheet.truncated
? props.kind === "ods"
- ? " Limited to 500 rows and 50 columns."
- : " Preview limited to 250,000 rows, 1,024 columns, and bounded cell text."
- : ""}
+ ? gt(
+ "Cell values only. Charts, images, and formatting are not shown. Limited to 500 rows and 50 columns.",
+ )
+ : gt(
+ "Cell values only. Charts, images, and formatting are not shown. Preview limited to 250,000 rows, 1,024 columns, and bounded cell text.",
+ )
+ : gt("Cell values only. Charts, images, and formatting are not shown.")}
{sheet.rowCount === 0 ? (
-
This sheet is empty.
+
+ This sheet is empty.
+
) : (
(index === 0 ? sheet.rows : sheetPages.get(`${page}:${index}`))}
diff --git a/apps/web/src/components/files/OpenXmlOfficeViewer.tsx b/apps/web/src/components/files/OpenXmlOfficeViewer.tsx
index 7e7268cdf03c2..0729888614ad3 100644
--- a/apps/web/src/components/files/OpenXmlOfficeViewer.tsx
+++ b/apps/web/src/components/files/OpenXmlOfficeViewer.tsx
@@ -1,22 +1,26 @@
import { useStableCallback } from "~/hooks/useStableCallback";
import type { OfficePreviewKind } from "@t3tools/shared/filePreview";
+import { msg, T, useGT } from "gt-react";
import { lazy, Suspense, useEffect, useState } from "react";
+import { m } from "~/i18n/messages";
import {
FileSurfaceLoading,
FileSurfaceNotice,
FILE_SURFACE_SUBHEADER_CLASS,
} from "./fileSurfaceChrome";
import { OFFICE_PREVIEW_MAX_BYTES, type OfficeWorkerResult } from "./officePreviewProtocol";
+import { previewErrorText, previewFailureText } from "./previewFailureMessages";
const WordDocument = lazy(() => import("./office/WordDocument"));
const Spreadsheet = lazy(() => import("./office/Spreadsheet"));
const Presentation = lazy(() => import("./office/Presentation"));
async function readOfficeFile(src: string, signal: AbortSignal) {
const response = await fetch(src, { signal });
- if (!response.ok) throw new Error("The file could not be loaded. Close it and try again.");
+ if (!response.ok)
+ throw new Error(m(msg("The file could not be loaded. Close it and try again.")));
if (Number(response.headers.get("content-length")) > OFFICE_PREVIEW_MAX_BYTES)
- throw new Error("Preview limited to files under 50 MB.");
+ throw new Error(m(msg("Preview limited to files under 50 MB.")));
const reader = response.body?.getReader();
- if (!reader) throw new Error("The file is unavailable.");
+ if (!reader) throw new Error(m(msg("The file is unavailable.")));
const chunks: Uint8Array[] = [];
let size = 0;
try {
@@ -24,7 +28,8 @@ async function readOfficeFile(src: string, signal: AbortSignal) {
const { value, done } = await reader.read();
if (done) break;
size += value.length;
- if (size > OFFICE_PREVIEW_MAX_BYTES) throw new Error("Preview limited to files under 50 MB.");
+ if (size > OFFICE_PREVIEW_MAX_BYTES)
+ throw new Error(m(msg("Preview limited to files under 50 MB.")));
chunks.push(value);
}
} finally {
@@ -39,18 +44,19 @@ export default function OfficeViewer(props: {
readonly kind: Extract;
readonly sizeBytes?: number;
}) {
+ const gt = useGT();
const [error, setError] = useState(null);
const [prepared, setPrepared] = useState>();
const [details, setDetails] = useState("");
const fail = useStableCallback((cause: unknown) =>
- setError(cause instanceof Error ? cause.message : "Could not render this Office document."),
+ setError(previewErrorText(cause, m(msg("Could not render this Office document.")))),
);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Own the Open XML fetch, preparation worker, and timeout for this source and release them on cleanup.
useEffect(() => {
if ((props.sizeBytes ?? 0) > OFFICE_PREVIEW_MAX_BYTES) {
// Metadata bounds are checked before fetching or starting an engine.
// oxlint-disable-next-line react/set-state-in-effect
- setError("Preview limited to files under 50 MB.");
+ setError(m(msg("Preview limited to files under 50 MB.")));
return;
}
const controller = new AbortController();
@@ -63,17 +69,22 @@ export default function OfficeViewer(props: {
worker.terminate();
};
const timer = setTimeout(
- () => failure(new Error("This document took too long to preview. Open it in another app.")),
+ () =>
+ failure(
+ new Error(m(msg("This document took too long to preview. Open it in another app."))),
+ ),
30000,
);
- worker.addEventListener("error", () => failure(new Error("Could not load the Office viewer.")));
+ worker.addEventListener("error", () =>
+ failure(new Error(m(msg("Could not load the Office viewer.")))),
+ );
worker.addEventListener("messageerror", () =>
- failure(new Error("Could not read the Office viewer response.")),
+ failure(new Error(m(msg("Could not read the Office viewer response.")))),
);
worker.addEventListener("message", (event: MessageEvent) => {
if (controller.signal.aborted) return;
clearTimeout(timer);
- if (event.data.type === "error") failure(new Error(event.data.message));
+ if (event.data.type === "error") failure(new Error(previewFailureText(event.data)));
else if ("bytes" in event.data) {
setPrepared(event.data);
worker.terminate();
@@ -97,9 +108,11 @@ export default function OfficeViewer(props: {
role="alert"
className="flex min-h-0 flex-1 flex-col items-center justify-center gap-1 px-6 text-center"
>
-
No preview for this file
+
+ No preview for this file
+
- {error} Save it or open it in another app.
+ {gt("{error} Save it or open it in another app.", { error })}
);
@@ -111,13 +124,13 @@ export default function OfficeViewer(props: {
{details}
- {props.kind !== "xlsx" ? " · Fit to width" : ""}
+ {props.kind !== "xlsx" ? ` · ${gt("Fit to width")}` : ""}
) : null}
{prepared.truncated ? (
- Preview limited. Save it or open it in another app to read the full document.
+ Preview limited. Save it or open it in another app to read the full document.
) : null}
}>
diff --git a/apps/web/src/components/files/PdfViewer.tsx b/apps/web/src/components/files/PdfViewer.tsx
index fdbb6dd7a7526..e5872d123bba3 100644
--- a/apps/web/src/components/files/PdfViewer.tsx
+++ b/apps/web/src/components/files/PdfViewer.tsx
@@ -1,3 +1,4 @@
+import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
import {
useEffect,
useEffectEvent,
@@ -7,11 +8,14 @@ import {
type CSSProperties,
} from "react";
import { TextLayer, type PDFDocumentProxy } from "pdfjs-dist";
+import { msg, useGT } from "gt-react";
+import { m } from "~/i18n/messages";
import { ChevronDownIcon, ChevronUpIcon, MinusIcon, PlusIcon, ScanIcon } from "lucide-react";
import { Input } from "~/components/ui/input";
import { observeResize } from "~/lib/observeResize";
import { FileSurfaceAction, FileSurfaceFailure, FileSurfaceLoading } from "./fileSurfaceChrome";
import { readBoundedDocument } from "./readBoundedDocument";
+import { previewErrorText } from "./previewFailureMessages";
import { openPdf } from "./pdfDocument";
import {
currentPdfPage,
@@ -52,6 +56,7 @@ function PdfPage(props: {
onSize: (index: number, ratio: number) => void;
onError: (error: string) => void;
}) {
+ const gt = useGT();
const canvas = useRef(null);
const text = useRef(null);
const { document: pdf, index, width, onSize, onError } = props;
@@ -94,7 +99,7 @@ function PdfPage(props: {
await Promise.all([paint.promise, layer.render()]);
})().catch((cause: unknown) => {
if (!cancelled)
- onError(cause instanceof Error ? cause.message : "This PDF page could not render.");
+ onError(thrownErrorMessage(cause, m) ?? m(msg("This PDF page could not render.")));
});
return () => {
cancelled = true;
@@ -123,7 +128,11 @@ function PdfPage(props: {
}, [props.query]);
return (
<>
-
+
>
);
@@ -136,6 +145,7 @@ export default function PdfViewer(props: {
initialView?: PdfViewState;
onViewChange?: (view: PdfViewState) => void;
}) {
+ const gt = useGT();
const [savedPosition] = useState(() =>
props.positionKey === undefined ? undefined : positions.get(props.positionKey),
);
@@ -165,7 +175,7 @@ export default function PdfViewer(props: {
let disposed = false;
let task: ReturnType | undefined;
const timeout = setTimeout(() => {
- setError("This PDF took too long to load. Try again.");
+ setError(m(msg("This PDF took too long to load. Try again.")));
controller.abort();
void task?.destroy();
}, 30_000);
@@ -180,7 +190,9 @@ export default function PdfViewer(props: {
task = openPdf(bytes);
const document = await task.promise;
if (document.numPages > MAX_PAGES)
- throw new Error("Preview limited to 2,000 pages. Save this PDF to read it in full.");
+ throw new Error(
+ m(msg("Preview limited to 2,000 pages. Save this PDF to read it in full.")),
+ );
const first = (await document.getPage(1)).getViewport({ scale: 1 });
const sizes = await Promise.all(
Array.from({ length: Math.min(initialPage + 1, document.numPages) }, async (_, index) => {
@@ -202,7 +214,7 @@ export default function PdfViewer(props: {
})
.catch((cause: unknown) => {
if (!disposed && !controller.signal.aborted)
- setError(cause instanceof Error ? cause.message : "Unable to open PDF.");
+ setError(previewErrorText(cause, m(msg("Unable to open PDF."))));
})
.finally(() => clearTimeout(timeout));
return () => {
@@ -321,7 +333,7 @@ export default function PdfViewer(props: {
size += text.length;
if (size > MAX_FIND_TEXT)
throw new Error(
- "This PDF has too much text to search. Save it to search in another app.",
+ m(msg("This PDF has too much text to search. Save it to search in another app.")),
);
if (!pdfFindIncludes(text, query)) continue;
found.push(index);
@@ -336,7 +348,7 @@ export default function PdfViewer(props: {
})()
.catch((cause: unknown) => {
if (!cancelled)
- setFindError(cause instanceof Error ? cause.message : "Could not search this PDF.");
+ setFindError(thrownErrorMessage(cause, m) ?? m(msg("Could not search this PDF.")));
})
.finally(() => {
if (!cancelled) setFinding(false);
@@ -351,41 +363,49 @@ export default function PdfViewer(props: {