Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
fix(web): stop idle work in chats and charts
Leocd68fc66d3c3
diff --git a/apps/web/src/components/dither-kit/bar-canvas.tsx b/apps/web/src/components/dither-kit/bar-canvas.tsxindex c714f26eb..ce6537cb0 100644--- a/apps/web/src/components/dither-kit/bar-canvas.tsx+++ b/apps/web/src/components/dither-kit/bar-canvas.tsx@@ -58,10 +58,31 @@ export function BarCanvas() {// mid-render tears under Strict Mode / concurrent rendering.const state = useRef(ctx);const targetsRef = useRef(targets);+ const invalidateRef = useRef<(() => void) | null>(null);useEffect(() => {state.current = ctx;targetsRef.current = targets;- });+ }, [ctx, targets]);++ useEffect(() => {+ invalidateRef.current?.();+ }, [+ targets,+ ctx.ready,+ ctx.revision,+ ctx.stackType,+ ctx.seriesSpecs,+ ctx.seedOf,+ ctx.barSlot,+ ctx.dataLength,+ ctx.selectedDataKey,+ ctx.focusDataKey,+ ctx.hoverIndex,+ ctx.isMouseInChart,+ ctx.hovered,+ ctx.bloom,+ ctx.bloomOnHover,+ ]);useEffect(() => {const canvas = canvasRef.current;@@ -138,16 +159,9 @@ export function BarCanvas() {let lastHover: number | null | undefined = Symbol() as never;const draw = (now: number) => {- raf = requestAnimationFrame(draw);+ raf = animate ? requestAnimationFrame(draw) : 0;const s = state.current;if (!s.ready) return;- if (bloomCtx) {- const on = s.bloom !== "off" && (!s.bloomOnHover || s.isMouseInChart || s.hovered);- if (on) {- bloomCtx.clearRect(0, 0, cols, rows);- bloomCtx.drawImage(canvas, 0, 0);- }- }if (s.revision !== lastRevision) {lastRevision = s.revision;animStart = 0; // re-play the wave on data change / replay@@ -171,7 +185,7 @@ export function BarCanvas() {}const itTarget = s.isMouseInChart || s.hovered ? 1 : 0;if (Math.abs(intensity - itTarget) > 0.001) {- intensity += (itTarget - intensity) * (reduce ? 1 : 0.16);+ intensity += (itTarget - intensity) * (animate ? 0.16 : 1);needsFill = true;} else intensity = itTarget;@@ -187,11 +201,22 @@ export function BarCanvas() {if (!needsFill) return;paint(prog);needsFill = false;+ if (bloomCtx && s.bloom !== "off" && (!s.bloomOnHover || s.isMouseInChart || s.hovered)) {+ bloomCtx.clearRect(0, 0, cols, rows);+ bloomCtx.drawImage(canvas, 0, 0);+ }};- raf = requestAnimationFrame(draw);- return () => cancelAnimationFrame(raf);- }, [cols, rows, width]);+ invalidateRef.current = () => {+ needsFill = true;+ if (!raf) raf = requestAnimationFrame(draw);+ };+ invalidateRef.current();+ return () => {+ cancelAnimationFrame(raf);+ invalidateRef.current = null;+ };+ }, [cols, rows, width, ctx.animate, ctx.animationDuration]);const bloomActive = ctx.bloomOnHover ? ctx.isMouseInChart || ctx.hovered : true;const bloom = bloomLayerStyle(ctx.bloom, bloomActive);diff --git a/apps/web/src/components/dither-kit/canvas.test.tsx b/apps/web/src/components/dither-kit/canvas.test.tsxnew file mode 100644index 000000000..efe3fcd4b--- /dev/null+++ b/apps/web/src/components/dither-kit/canvas.test.tsx@@ -0,0 +1,242 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";+import { reactHookHarness } from "../../test/reactHookHarness";+import { seedOfColor } from "./palette";++const hooks = vi.hoisted(() => ({+ refs: [] as { current: unknown }[],+ effects: [] as { run: () => void | (() => void); deps: readonly unknown[] | undefined }[],+}));++vi.mock("react", async (importOriginal) => {+ const actual = await importOriginal<typeof import("react")>();+ const { reactHookHarness } = await import("../../test/reactHookHarness");+ return {+ ...actual,+ useMemo: <T,>(factory: () => T, deps: readonly unknown[]) => {+ const ref = reactHookHarness.useRef<{ value: T; deps: readonly unknown[] } | null>(null);+ if (+ !ref.current ||+ deps.some((value, index) => !Object.is(value, ref.current!.deps[index]))+ ) {+ ref.current = { value: factory(), deps };+ }+ return ref.current.value;+ },+ useRef: <T,>(value: T) => {+ const ref = reactHookHarness.useRef(value);+ hooks.refs.push(ref);+ return ref;+ },+ useEffect: (run: () => void | (() => void), deps: readonly unknown[] | undefined) => {+ hooks.effects.push({ run, deps });+ },+ };+});+vi.mock("react/compiler-runtime", async () => {+ const { reactHookHarness } = await import("../../test/reactHookHarness");+ return { c: reactHookHarness.useMemoCache };+});+vi.mock("./chart-context", () => ({ useChart: () => chart }));++import { BarCanvas } from "./bar-canvas";+import { CartesianCanvas } from "./cartesian-canvas";++function chartFixture() {+ return {+ plot: { width: 100, height: 60 },+ margins: { top: 0, right: 0, bottom: 0, left: 0 },+ ready: true,+ configKeys: ["tokens"],+ bands: {+ tokens: [+ [0, 10],+ [0, 20],+ ],+ },+ y: (value: number) => 60 - value,+ chartType: "line",+ dataLength: 2,+ seriesSpecs: {},+ seedOf: () => seedOfColor("green"),+ animate: false,+ animationDuration: 100,+ revision: 0,+ stackType: "overlap",+ selectedDataKey: null as string | null,+ focusDataKey: null as string | null,+ hoverIndex: null as number | null,+ cursorX: 0,+ markerIndex: null as number | null,+ isMouseInChart: false,+ hovered: false,+ bloom: "off",+ bloomOnHover: false,+ barSlot: (index: number) => ({ x: index * 50, width: 40 }),+ markEntranceDone: vi.fn(),+ };+}++let chart = chartFixture();+let frames = new Map<number, FrameRequestCallback>();+let nextFrame = 0;+let effects: { deps: readonly unknown[] | undefined; cleanup?: void | (() => void) }[] = [];+const paintContext = () => ({+ clearRect: vi.fn(),+ drawImage: vi.fn(),+ fillRect: vi.fn(),+ fillStyle: "",+});+const paint = paintContext();+const fillPaint = paintContext();+const bloomPaint = paintContext();+const canvas = { width: 0, height: 0, getContext: () => paint };+const fillCanvas = { width: 0, height: 0, getContext: () => fillPaint };+const bloomCanvas = { width: 0, height: 0, getContext: () => bloomPaint };++function render(Component: typeof BarCanvas) {+ reactHookHarness.beginRender();+ hooks.refs = [];+ hooks.effects = [];+ Component();+ hooks.refs[0]!.current = canvas;+ hooks.refs[1]!.current = bloomCanvas;+ hooks.effects.forEach((effect, index) => {+ const previous = effects[index];+ if (+ previous?.deps &&+ effect.deps &&+ previous.deps.length === effect.deps.length &&+ previous.deps.every((value, i) => Object.is(value, effect.deps![i]))+ )+ return;+ previous?.cleanup?.();+ effects[index] = { deps: effect.deps, cleanup: effect.run() };+ });+}++function flushFrame(now = 1000) {+ const pending = [...frames.values()];+ frames.clear();+ pending.forEach((callback) => callback(now));+}++beforeEach(() => {+ chart = chartFixture();+ frames = new Map();+ nextFrame = 0;+ effects = [];+ reactHookHarness.reset();+ vi.clearAllMocks();+ vi.stubGlobal("window", { matchMedia: () => ({ matches: false }) });+ vi.stubGlobal("document", { createElement: () => fillCanvas });+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {+ frames.set(++nextFrame, callback);+ return nextFrame;+ });+ vi.stubGlobal("cancelAnimationFrame", (id: number) => frames.delete(id));+});++afterEach(() => {+ effects.forEach((effect) => effect.cleanup?.());+ vi.unstubAllGlobals();+});++for (const [name, Component] of [+ ["bar", BarCanvas],+ ["line", CartesianCanvas],+] as const) {+ describe(`${name} canvas`, () => {+ const seriesPaint = name === "line" ? fillPaint : paint;+ it("paints static data once and schedules no idle frames", () => {+ render(Component);+ expect(frames.size).toBe(1);+ flushFrame();+ expect(seriesPaint.fillRect).toHaveBeenCalled();+ expect(frames.size).toBe(0);+ });++ it("repaints hover, selection, data and marker removal without retaining a loop", () => {+ render(Component);+ flushFrame();+ for (const update of [+ { hoverIndex: 1, isMouseInChart: true },+ { selectedDataKey: "tokens" },+ {+ bands: {+ tokens: [+ [0, 20],+ [0, 30],+ ],+ },+ revision: 1,+ },+ { hoverIndex: null, isMouseInChart: false, selectedDataKey: null },+ ]) {+ paint.clearRect.mockClear();+ chart = { ...chart, ...update };+ render(Component);+ expect(frames.size).toBe(1);+ flushFrame();+ expect(paint.clearRect).toHaveBeenCalled();+ expect(frames.size).toBe(0);+ }+ });++ it("waits for ready data and coalesces invalidations", () => {+ chart.ready = false;+ render(Component);+ flushFrame();+ expect(frames.size).toBe(0);+ expect(seriesPaint.fillRect).not.toHaveBeenCalled();+ chart = { ...chart, ready: true };+ render(Component);+ chart = { ...chart, hovered: true };+ render(Component);+ expect(frames.size).toBe(1);+ flushFrame();+ expect(seriesPaint.fillRect).toHaveBeenCalled();+ expect(frames.size).toBe(0);+ });++ it("keeps animated charts running and cancels pending frames on unmount", () => {+ chart.animate = true;+ render(Component);+ flushFrame();+ expect(frames.size).toBe(1);+ effects.forEach((effect) => effect.cleanup?.());+ expect(frames.size).toBe(0);+ });++ it.each([false, true])("reuses the fill for cursor-only updates with animate=%s", (animate) => {+ chart = { ...chart, animate, hoverIndex: 1, isMouseInChart: true };+ render(Component);+ for (let frame = 0; frame < 100; frame++) flushFrame(1000 + frame * 16);+ seriesPaint.fillRect.mockClear();+ chart = { ...chart, cursorX: 20 };+ render(Component);+ flushFrame(2600);+ expect(seriesPaint.fillRect).not.toHaveBeenCalled();+ expect(frames.size).toBe(animate ? 1 : 0);+ });++ it("copies the newly painted canvas into the bloom layer", () => {+ chart.bloom = "low";+ render(Component);+ flushFrame();+ expect(bloomPaint.drawImage).toHaveBeenCalledWith(canvas, 0, 0);+ expect(seriesPaint.fillRect.mock.invocationCallOrder.at(-1)).toBeLessThan(+ bloomPaint.drawImage.mock.invocationCallOrder[0]!,+ );+ expect(frames.size).toBe(0);+ });++ it("honors reduced motion for animated charts", () => {+ chart.animate = true;+ vi.stubGlobal("window", { matchMedia: () => ({ matches: true }) });+ render(Component);+ flushFrame();+ expect(seriesPaint.fillRect).toHaveBeenCalled();+ expect(frames.size).toBe(0);+ });+ });+}diff --git a/apps/web/src/components/dither-kit/cartesian-canvas.tsx b/apps/web/src/components/dither-kit/cartesian-canvas.tsxindex b7b0f6687..7b666c319 100644--- a/apps/web/src/components/dither-kit/cartesian-canvas.tsx+++ b/apps/web/src/components/dither-kit/cartesian-canvas.tsx@@ -24,6 +24,7 @@ type LoopArgs = {state: RefObject<ChartContextValue>;targets: RefObject<Record<string, Surface>>;stars: RefObject<Star[]>;+ invalidate: RefObject<(() => void) | null>;};/**@@ -41,6 +42,7 @@ function startCartesianLoop({state,targets,stars,+ invalidate,}: LoopArgs): (() => void) | undefined {const c = canvas.getContext("2d");if (!c || cols <= 0 || rows <= 0) return undefined;@@ -61,8 +63,8 @@ function startCartesianLoop({}const reduce = prefersReducedMotion();- const EASE = reduce ? 1 : 0.18;const animate = state.current.animate && !reduce;+ const EASE = animate ? 0.18 : 1;const duration = state.current.animationDuration;const current: Record<string, Surface> = {};@@ -115,17 +117,9 @@ function startCartesianLoop({let lastSelected: string | null | undefined = Symbol() as never;const draw = (now: number) => {- raf = requestAnimationFrame(draw);+ raf = animate ? requestAnimationFrame(draw) : 0;const s = state.current;if (!s.ready) return;- // Keep the bloom layer in sync with the crisp canvas while it's active.- if (bloomCtx) {- const on = s.bloom !== "off" && (!s.bloomOnHover || s.isMouseInChart || s.hovered);- if (on) {- bloomCtx.clearRect(0, 0, cols, rows);- bloomCtx.drawImage(canvas, 0, 0);- }- }const tgt = targets.current;if (s.revision !== lastRevision) {lastRevision = s.revision;@@ -181,7 +175,7 @@ function startCartesianLoop({const itTarget = s.isMouseInChart || s.hovered ? 1 : 0;let settling = false;if (Math.abs(intensity - itTarget) > 0.001) {- intensity += (itTarget - intensity) * 0.16;+ intensity += (itTarget - intensity) * (animate ? 0.16 : 1);settling = true;needsFill = true;} else intensity = itTarget;@@ -189,7 +183,7 @@ function startCartesianLoop({// Live hover wins; the controlled markerIndex (e.g. a committed point)// is the fallback shown when nothing is hovered.const marker = s.hoverIndex != null ? s.hoverIndex : s.markerIndex;- const winkDue = !reduce && now - last >= 100;+ const winkDue = animate && now - last >= 100;// Repaint when a tweak-driven paint input changes (variant, stacking) so// the panel updates the fill live — without resetting the entrance reveal.const paintSig = `${s.stackType}|${s.configKeys@@ -200,7 +194,10 @@ function startCartesianLoop({lastPaintSig = paintSig;needsFill = true;}- if (!(moving || settling || winkDue || marker != null || progChanged || sigChanged)) return;+ if (+ !(needsFill || moving || settling || winkDue || marker != null || progChanged || sigChanged)+ )+ return;if (progChanged) {lastProg = prog;needsFill = true;@@ -249,7 +246,7 @@ function startCartesianLoop({const top = cur.top[sx] ?? 0;const floor = cur.floor[sx] ?? rows - 1;const sy = Math.round(top + star.depth * (floor - top));- const tw = reduce ? 0.85 : (Math.sin((tick + star.phase) * 0.35) + 1) / 2;+ const tw = animate ? (Math.sin((tick + star.phase) * 0.35) + 1) / 2 : 0.85;const lift = tw * (0.7 + 0.3 * intensity);if (lift < 0.55 || sy < 0 || sy >= rows) continue;// Sparkles glint in the series colour via opacity (the `lift` wink)@@ -267,10 +264,21 @@ function startCartesianLoop({c.fillRect(sx, sy + 1, 1, 1);}}+ if (bloomCtx && s.bloom !== "off" && (!s.bloomOnHover || s.isMouseInChart || s.hovered)) {+ bloomCtx.clearRect(0, 0, cols, rows);+ bloomCtx.drawImage(canvas, 0, 0);+ }};- raf = requestAnimationFrame(draw);- return () => cancelAnimationFrame(raf);+ invalidate.current = () => {+ needsFill = true;+ if (!raf) raf = requestAnimationFrame(draw);+ };+ invalidate.current();+ return () => {+ cancelAnimationFrame(raf);+ invalidate.current = null;+ };}/**@@ -338,11 +346,32 @@ export function CartesianCanvas() {const stateRef = useRef(ctx);const targetsRef = useRef(targets);const starsRef = useRef(stars);+ const invalidateRef = useRef<(() => void) | null>(null);useEffect(() => {stateRef.current = ctx;targetsRef.current = targets;starsRef.current = stars;- });+ }, [ctx, targets, stars]);++ useEffect(() => {+ invalidateRef.current?.();+ }, [+ targets,+ stars,+ ctx.ready,+ ctx.revision,+ ctx.stackType,+ ctx.seriesSpecs,+ ctx.seedOf,+ ctx.selectedDataKey,+ ctx.focusDataKey,+ ctx.hoverIndex,+ ctx.markerIndex,+ ctx.isMouseInChart,+ ctx.hovered,+ ctx.bloom,+ ctx.bloomOnHover,+ ]);useEffect(() => {const canvas = canvasRef.current;@@ -355,8 +384,9 @@ export function CartesianCanvas() {state: stateRef,targets: targetsRef,stars: starsRef,+ invalidate: invalidateRef,});- }, [cols, rows]);+ }, [cols, rows, ctx.animate, ctx.animationDuration]);const bloomActive = ctx.bloomOnHover ? ctx.isMouseInChart || ctx.hovered : true;const bloom = bloomLayerStyle(ctx.bloom, bloomActive);diff --git a/apps/web/src/components/roster/botThreadRuntime.logic.test.ts b/apps/web/src/components/roster/botThreadRuntime.logic.test.tsindex a0b07f6b5..0c70bbe30 100644--- a/apps/web/src/components/roster/botThreadRuntime.logic.test.ts+++ b/apps/web/src/components/roster/botThreadRuntime.logic.test.ts@@ -1,5 +1,5 @@import { BotId, GroupId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";-import { describe, expect, it } from "vite-plus/test";+import { describe, expect, it, vi } from "vite-plus/test";import {buildBotTurnStartInput,@@ -11,6 +11,101 @@ import {joinOrStartThreadCreate,} from "./botThreadRuntime.logic";+describe.each([+ { name: "bot", findLatest: findLatestBotThreadTarget, ownerKey: "botId" as const },+ { name: "group", findLatest: findLatestGroupThreadTarget, ownerKey: "groupId" as const },+])("latest $name thread selection", ({ findLatest, ownerKey }) => {+ const thread = (id: string, updatedAt = "2026-08-27T00:00:00.000Z") => ({+ environmentId: "env-a",+ id,+ botId: "owner",+ groupId: "owner",+ updatedAt,+ archivedAt: null as string | null,+ deletedAt: null as string | null | undefined,+ });++ it("returns null for empty and non-matching inputs", () => {+ expect(findLatest("owner", "env-a", [])).toBeNull();+ expect(+ findLatest("owner", "env-a", [+ { ...thread("wrong-environment"), environmentId: "env-b" },+ { ...thread("wrong-owner"), [ownerKey]: "other" },+ { ...thread("archived"), archivedAt: "2026-08-28T00:00:00.000Z" },+ { ...thread("deleted"), deletedAt: "2026-08-28T00:00:00.000Z" },+ ]),+ ).toBeNull();+ });++ it("preserves descending timestamp and ID order without mutating the input", () => {+ const candidates = [+ thread("z-older", "2026-08-26T00:00:00.000Z"),+ thread("b-newer"),+ thread("a-newer"),+ { ...thread("z-deleted", "2026-08-29T00:00:00.000Z"), deletedAt: "deleted" },+ { ...thread("z-archived", "2026-08-29T00:00:00.000Z"), archivedAt: "archived" },+ { ...thread("z-remote", "2026-08-29T00:00:00.000Z"), environmentId: "env-b" },+ { ...thread("z-other", "2026-08-29T00:00:00.000Z"), [ownerKey]: "other" },+ ];+ for (const input of [candidates, candidates.toReversed()]) {+ const original = [...input];+ expect(findLatest("owner", "env-a", Object.freeze(input))).toEqual({+ environmentId: "env-a",+ threadId: "b-newer",+ });+ expect(input).toEqual(original);+ }+ expect(+ findLatest("owner", "env-a", [{ ...thread("no-deletion-field"), deletedAt: undefined }]),+ ).toEqual({ environmentId: "env-a", threadId: "no-deletion-field" });+ });++ it("keeps the first candidate when timestamp and ID collate equally", () => {+ const composed = thread("é");+ const decomposed = thread("e\u0301");+ expect(composed.id.localeCompare(decomposed.id)).toBe(0);+ for (const candidates of [+ [composed, decomposed],+ [decomposed, composed],+ ]) {+ expect(findLatest("owner", "env-a", candidates)?.threadId).toBe(candidates[0]?.id);+ }+ });++ it("matches filter-sort selection with only 2,046 locale comparisons for 1,024 ties", () => {+ const candidates = Array.from({ length: 1_024 }, (_, index) =>+ thread(`thread-${String((index * 317) % 1_024).padStart(4, "0")}`),+ );+ const compare = vi.spyOn(String.prototype, "localeCompare");+ let oldComparisons = 0;+ let newComparisons = 0;+ try {+ const oldLatest = candidates+ .filter(+ (entry) =>+ entry.environmentId === "env-a" &&+ entry[ownerKey] === "owner" &&+ entry.archivedAt === null &&+ entry.deletedAt == null,+ )+ .toSorted(+ (left, right) =>+ right.updatedAt.localeCompare(left.updatedAt) || right.id.localeCompare(left.id),+ )[0];+ oldComparisons = compare.mock.calls.length;+ compare.mockClear();+ const latest = findLatest("owner", "env-a", candidates);+ newComparisons = compare.mock.calls.length;+ expect(latest).toEqual({ environmentId: oldLatest?.environmentId, threadId: oldLatest?.id });+ expect(newComparisons).toBe(2 * (candidates.length - 1));+ expect(oldComparisons).toBeGreaterThan(newComparisons);+ } finally {+ compare.mockRestore();+ }+ console.info(`Latest ${ownerKey}: locale comparisons ${oldComparisons} -> ${newComparisons}`);+ });+});+describe("bot thread runtime", () => {it("finds each secure MCP authorization once and rejects unsafe URLs", () => {const activities = [diff --git a/apps/web/src/components/roster/botThreadRuntime.logic.ts b/apps/web/src/components/roster/botThreadRuntime.logic.tsindex 374c777f1..330a8d826 100644--- a/apps/web/src/components/roster/botThreadRuntime.logic.ts+++ b/apps/web/src/components/roster/botThreadRuntime.logic.ts@@ -134,18 +134,23 @@ export function findLatestBotThreadTarget(deletedAt?: string | null | undefined;}[],): { environmentId: string; threadId: string } | null {- const latest = threads- .filter(- (thread) =>- thread.environmentId === environmentId &&- thread.botId === botId &&- thread.archivedAt === null &&- thread.deletedAt == null,- )- .toSorted(- (left, right) =>- right.updatedAt.localeCompare(left.updatedAt) || right.id.localeCompare(left.id),- )[0];+ let latest: (typeof threads)[number] | undefined;+ for (const thread of threads) {+ if (+ thread.environmentId !== environmentId ||+ thread.botId !== botId ||+ thread.archivedAt !== null ||+ thread.deletedAt != null+ ) {+ continue;+ }+ if (+ latest === undefined ||+ (thread.updatedAt.localeCompare(latest.updatedAt) || thread.id.localeCompare(latest.id)) > 0+ ) {+ latest = thread;+ }+ }return latest ? { environmentId: latest.environmentId, threadId: latest.id } : null;}@@ -175,18 +180,23 @@ export function findLatestGroupThreadTarget(deletedAt?: string | null | undefined;}[],): { environmentId: string; threadId: string } | null {- const latest = threads- .filter(- (thread) =>- thread.environmentId === environmentId &&- thread.groupId === groupId &&- thread.archivedAt === null &&- thread.deletedAt == null,- )- .toSorted(- (left, right) =>- right.updatedAt.localeCompare(left.updatedAt) || right.id.localeCompare(left.id),- )[0];+ let latest: (typeof threads)[number] | undefined;+ for (const thread of threads) {+ if (+ thread.environmentId !== environmentId ||+ thread.groupId !== groupId ||+ thread.archivedAt !== null ||+ thread.deletedAt != null+ ) {+ continue;+ }+ if (+ latest === undefined ||+ (thread.updatedAt.localeCompare(latest.updatedAt) || thread.id.localeCompare(latest.id)) > 0+ ) {+ latest = thread;+ }+ }return latest ? { environmentId: latest.environmentId, threadId: latest.id } : null;}diff --git a/apps/web/src/components/roster/useBotThreadRuntime.test.ts b/apps/web/src/components/roster/useBotThreadRuntime.test.tsnew file mode 100644index 000000000..50eeaa92b--- /dev/null+++ b/apps/web/src/components/roster/useBotThreadRuntime.test.ts@@ -0,0 +1,104 @@+import { ApprovalRequestId, EnvironmentId, ThreadId } from "@t3tools/contracts";+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";++import { reactHookHarness as hooks } from "../../test/reactHookHarness";+import { useBotThreadRuntime } from "./useBotThreadRuntime";+import { useRosterPendingApproval } from "./useRosterPendingApproval";++const mocks = vi.hoisted(() => ({+ derivePendingApprovals: vi.fn(),+ useAtomCommand: vi.fn(),+ command: vi.fn(),+ approvalCommand: Symbol("respondToApproval"),+}));++vi.mock("react", async (importOriginal) => {+ const actual = await importOriginal<typeof import("react")>();+ const { reactHookHarness } = await import("../../test/reactHookHarness");+ return {+ ...actual,+ useCallback: reactHookHarness.useCallback,+ useEffect: () => undefined,+ useMemo: reactHookHarness.useMemo,+ useRef: reactHookHarness.useRef,+ useState: reactHookHarness.useState,+ };+});+vi.mock("react/compiler-runtime", async () => {+ const { reactHookHarness } = await import("../../test/reactHookHarness");+ return { c: reactHookHarness.useMemoCache };+});+vi.mock("@effect/atom-react", () => ({ useAtomValue: () => [] }));+vi.mock("../../hooks/useSettings", () => ({ usePrimarySettings: () => ({}) }));+vi.mock("../../modelSelection", () => ({ resolveAppModelSelectionState: () => null }));+vi.mock("../../state/entities", () => ({+ useProjects: () => [],+ useThreadShells: () => [],+ useAllEnvironmentShellsBootstrapped: () => true,+ useThreadShell: () => null,+ useThreadMessages: () => [],+ useThreadActivities: () => [],+ readEnvironmentSupportsFileAttachments: () => true,+}));+vi.mock("../../state/bots", () => ({ environmentBotsAtom: () => null }));+vi.mock("../../state/environments", () => ({ usePrimaryEnvironmentId: () => null }));+vi.mock("../../state/server", () => ({ primaryServerProvidersAtom: null }));+vi.mock("../../state/threads", () => ({+ threadEnvironment: { respondToApproval: mocks.approvalCommand },+}));+vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: mocks.useAtomCommand }));+vi.mock("../../session-logic", () => ({+ derivePendingApprovals: mocks.derivePendingApprovals,+ derivePendingUserInputs: () => [],+}));+vi.mock("../Sidebar.logic", () => ({ sortScopedProjectsForSidebar: () => [] }));+vi.mock("./rosterStore", () => ({+ useRosterStore: (selector: (state: { bots: []; chatPathByBotId: {} }) => unknown) =>+ selector({ bots: [], chatPathByBotId: {} }),+}));++beforeEach(() => {+ hooks.reset();+ vi.clearAllMocks();+ mocks.derivePendingApprovals.mockReturnValue([]);+ mocks.useAtomCommand.mockReturnValue(mocks.command);+ mocks.command.mockResolvedValue({ _tag: "Success", value: undefined });+});++describe("bot runtime approval ownership", () => {+ it("does not derive approvals or acquire an unused approval command", () => {+ hooks.beginRender();+ const runtime = useBotThreadRuntime("bot-1", null);+ expect(mocks.derivePendingApprovals).not.toHaveBeenCalled();+ expect(+ mocks.useAtomCommand.mock.calls.filter(([command]) => command === mocks.approvalCommand),+ ).toHaveLength(0);+ expect(runtime).not.toHaveProperty("pendingApprovals");+ expect(runtime).not.toHaveProperty("respondToApproval");+ expect(runtime).not.toHaveProperty("respondingToApproval");+ });++ it("derives approvals once and keeps the roster response path active", async () => {+ const requestId = ApprovalRequestId.make("request-1");+ const threadRef = {+ environmentId: EnvironmentId.make("env-a"),+ threadId: ThreadId.make("thread-1"),+ };+ mocks.derivePendingApprovals.mockReturnValue([+ { requestId, requestKind: "command", createdAt: "2026-08-27T00:00:00.000Z" },+ ]);+ hooks.beginRender();+ useBotThreadRuntime("bot-1", null);+ const approval = useRosterPendingApproval(threadRef);+ expect(mocks.derivePendingApprovals).toHaveBeenCalledTimes(1);+ expect(+ mocks.useAtomCommand.mock.calls.filter(([command]) => command === mocks.approvalCommand),+ ).toHaveLength(1);+ expect(approval.pendingApproval?.requestId).toBe(requestId);+ expect(await approval.respond(requestId, "accept")).toBe(true);+ expect(mocks.command).toHaveBeenCalledWith({+ environmentId: threadRef.environmentId,+ input: { threadId: threadRef.threadId, requestId, decision: "accept" },+ });+ });+});diff --git a/apps/web/src/components/roster/useBotThreadRuntime.ts b/apps/web/src/components/roster/useBotThreadRuntime.tsindex acd7f170d..bc7673a54 100644--- a/apps/web/src/components/roster/useBotThreadRuntime.ts+++ b/apps/web/src/components/roster/useBotThreadRuntime.ts@@ -7,7 +7,6 @@ import {EnvironmentId,ThreadId,type ModelSelection,- type ProviderApprovalDecision,type ScopedThreadRef,} from "@t3tools/contracts";import { useCallback, useEffect, useMemo, useRef, useState } from "react";@@ -30,7 +29,7 @@ import { usePrimaryEnvironmentId } from "../../state/environments";import { primaryServerProvidersAtom } from "../../state/server";import { threadEnvironment } from "../../state/threads";import { useAtomCommand } from "../../state/use-atom-command";-import { derivePendingApprovals, derivePendingUserInputs } from "../../session-logic";+import { derivePendingUserInputs } from "../../session-logic";import {applyPendingUserInputSingleSelect,buildPendingUserInputAnswers,@@ -131,7 +130,6 @@ export function useBotThreadRuntime(botId: string, effectiveModelSelection: ModeopenedAuthorizationActivitiesRef.current.add(authorization.activityId);void ensureLocalApi().shell.openExternal(authorization.url);}, [activities]);- const pendingApprovals = useMemo(() => derivePendingApprovals(activities), [activities]);const pendingUserInputs = useMemo(() => derivePendingUserInputs(activities), [activities]);const defaultProject = useMemo(() =>@@ -158,9 +156,6 @@ export function useBotThreadRuntime(botId: string, effectiveModelSelection: ModereportFailure: false,});const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });- const respondToApprovalCommand = useAtomCommand(threadEnvironment.respondToApproval, {- reportFailure: false,- });const respondToUserInputCommand = useAtomCommand(threadEnvironment.respondToUserInput, {reportFailure: false,});@@ -173,7 +168,6 @@ export function useBotThreadRuntime(botId: string, effectiveModelSelection: Modeconst sendQueueRef = useRef(createBotTurnSubmissionQueue());const queuedSendCountRef = useRef(0);const [sending, setSending] = useState(false);- const [respondingToApproval, setRespondingToApproval] = useState(false);const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);const respondingRequestIdsRef = useRef(new Set<ApprovalRequestId>());const singleSelectInFlightRef = useRef<string | null>(null);@@ -433,23 +427,6 @@ export function useBotThreadRuntime(botId: string, effectiveModelSelection: Mode[appendVoiceTranscript, botId, ensureTranscriptThread],);- const respondToApproval = useCallback(- async (- requestId: (typeof pendingApprovals)[number]["requestId"],- decision: ProviderApprovalDecision,- ) => {- if (!linkedThreadRef || respondingToApproval) return;- setRespondingToApproval(true);- const result = await respondToApprovalCommand({- environmentId: linkedThreadRef.environmentId,- input: { threadId: linkedThreadRef.threadId, requestId, decision },- });- setRespondingToApproval(false);- if (result._tag === "Failure") setError(errorMessage(result));- },- [linkedThreadRef, pendingApprovals, respondToApprovalCommand, respondingToApproval],- );-useEffect(() => {setPendingUserInputAnswers({});setPendingUserInputQuestionIndex(0);@@ -533,15 +510,12 @@ export function useBotThreadRuntime(botId: string, effectiveModelSelection: ModelinkedThreadRef,latestTurn: rememberedThread?.latestTurn ?? null,messages,- pendingApprovals,pendingUserInputs,pendingUserInputAnswers,pendingUserInputQuestionIndex,respondingRequestIds,selectPendingUserInputOption,advancePendingUserInput,- respondToApproval,- respondingToApproval,send,sending,};diff --git a/docs/user/usage.md b/docs/user/usage.mdindex cb7675f42..ef85d2536 100644--- a/docs/user/usage.md+++ b/docs/user/usage.md@@ -21,6 +21,8 @@ Akeru reads transcripts from each environment. It deduplicates shared transcriptsame usage is not counted twice. A notice identifies environments that are still loading, stale, orunavailable.+Web and desktop charts stay still when idle. Hover over a chart to inspect a value.+## Refresh usageAkeru refreshes usage every five minutes by default. Select **Refresh usage** to reload it now.diff --git a/packages/client-runtime/src/state/threadReducer.test.ts b/packages/client-runtime/src/state/threadReducer.test.tsindex bc28029a9..1fa481dd1 100644--- a/packages/client-runtime/src/state/threadReducer.test.ts+++ b/packages/client-runtime/src/state/threadReducer.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it } from "vite-plus/test";+import { assert, describe, expect, it } from "vite-plus/test";import {AuthSessionId,@@ -354,6 +354,108 @@ describe("applyThreadDetailEvent", () => {});describe("thread.message-sent", () => {+ const boundMessageId = MessageId.make("msg-bound");+ const boundTurnId = TurnId.make("turn-bound");+ const boundCheckpoint = {+ turnId: boundTurnId,+ checkpointTurnCount: 1,+ checkpointRef: CheckpointRef.make("ref-bound"),+ status: "ready",+ files: [],+ assistantMessageId: boundMessageId,+ completedAt: "2026-04-01T06:00:00.000Z",+ } satisfies OrchestrationThread["checkpoints"][number];+ const streamingEvent = {+ ...baseEventFields,+ sequence: 7,+ occurredAt: "2026-04-01T06:01:00.000Z",+ aggregateKind: "thread",+ aggregateId: baseThread.id,+ type: "thread.message-sent",+ payload: {+ threadId: baseThread.id,+ messageId: boundMessageId,+ role: "assistant",+ text: "delta",+ turnId: boundTurnId,+ streaming: true,+ createdAt: "2026-04-01T06:00:00.000Z",+ updatedAt: "2026-04-01T06:01:00.000Z",+ },+ } as const;++ it.each([+ { name: "empty checkpoints", checkpoints: [] },+ { name: "already-bound checkpoint", checkpoints: [boundCheckpoint] },+ {+ name: "unrelated checkpoint",+ checkpoints: [{ ...boundCheckpoint, turnId: TurnId.make("other-turn") }],+ },+ ])("preserves collection identity for $name", ({ checkpoints }) => {+ const result = applyThreadDetailEvent({ ...baseThread, checkpoints }, streamingEvent);+ assert(result.kind === "updated");+ expect(result.thread.checkpoints).toBe(checkpoints);+ });++ it("copies only checkpoints whose assistant binding changes", () => {+ const unrelated = { ...boundCheckpoint, turnId: TurnId.make("other-turn") };+ const unbound = { ...boundCheckpoint, assistantMessageId: null };+ const previouslyBound = { ...boundCheckpoint, assistantMessageId: MessageId.make("old") };+ const checkpoints = [unrelated, unbound, boundCheckpoint, previouslyBound];+ const result = applyThreadDetailEvent({ ...baseThread, checkpoints }, streamingEvent);+ assert(result.kind === "updated");+ expect(result.thread.checkpoints).not.toBe(checkpoints);+ expect(result.thread.checkpoints[0]).toBe(unrelated);+ expect(result.thread.checkpoints[2]).toBe(boundCheckpoint);+ expect(result.thread.checkpoints[1]).toEqual(boundCheckpoint);+ expect(result.thread.checkpoints[1]).not.toBe(unbound);+ expect(result.thread.checkpoints[3]).toEqual(boundCheckpoint);+ expect(result.thread.checkpoints[3]).not.toBe(previouslyBound);+ expect(unbound.assistantMessageId).toBeNull();+ expect(previouslyBound.assistantMessageId).toBe("old");+ });++ it("removes 100 no-op collection and entry replacements across 500 checkpoints", () => {+ const checkpoints = Array.from({ length: 500 }, (_, index) => ({+ ...boundCheckpoint,+ turnId: index === 0 ? boundTurnId : TurnId.make(`turn-${index}`),+ }));+ let thread: OrchestrationThread = { ...baseThread, checkpoints };+ let previousCheckpoints: OrchestrationThread["checkpoints"] = checkpoints;+ let oldCollectionReplacements = 0;+ let oldEntryReplacements = 0;+ let newCollectionReplacements = 0;+ let newEntryReplacements = 0;+ for (let index = 0; index < 100; index += 1) {+ const oldNext = previousCheckpoints.map((entry) =>+ entry.turnId === boundTurnId ? { ...entry, assistantMessageId: boundMessageId } : entry,+ );+ oldCollectionReplacements += Number(oldNext !== previousCheckpoints);+ oldEntryReplacements += oldNext.filter(+ (entry, i) => entry !== previousCheckpoints[i],+ ).length;+ previousCheckpoints = oldNext;++ const result = applyThreadDetailEvent(thread, { ...streamingEvent, sequence: index + 1 });+ assert(result.kind === "updated");+ newCollectionReplacements += Number(result.thread.checkpoints !== thread.checkpoints);+ newEntryReplacements += result.thread.checkpoints.filter(+ (entry, i) => entry !== thread.checkpoints[i],+ ).length;+ thread = result.thread;+ }+ expect({ oldCollectionReplacements, oldEntryReplacements }).toEqual({+ oldCollectionReplacements: 100,+ oldEntryReplacements: 100,+ });+ expect({ newCollectionReplacements, newEntryReplacements }).toEqual({+ newCollectionReplacements: 0,+ newEntryReplacements: 0,+ });+ expect(thread.checkpoints).toBe(checkpoints);+ expect(thread.messages[0]?.text).toBe("delta".repeat(100));+ });+it("appends a new message", () => {const result = applyThreadDetailEvent(baseThread, {...baseEventFields,diff --git a/packages/client-runtime/src/state/threadReducer.ts b/packages/client-runtime/src/state/threadReducer.tsindex 59fd4bcd7..4c5545831 100644--- a/packages/client-runtime/src/state/threadReducer.ts+++ b/packages/client-runtime/src/state/threadReducer.ts@@ -698,10 +698,15 @@ function rebindCheckpointAssistantMessage(checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,turnId: TurnId,messageId: MessageId,-): OrchestrationCheckpointSummary[] {- return Arr.map(checkpoints, (entry) =>- entry.turnId === turnId ? { ...entry, assistantMessageId: messageId } : entry,- );+): ReadonlyArray<OrchestrationCheckpointSummary> {+ let next: OrchestrationCheckpointSummary[] | undefined;+ for (let index = 0; index < checkpoints.length; index += 1) {+ const entry = checkpoints[index]!;+ if (entry.turnId !== turnId || entry.assistantMessageId === messageId) continue;+ next ??= checkpoints.slice();+ next[index] = { ...entry, assistantMessageId: messageId };+ }+ return next ?? checkpoints;}function retainMessagesAfterRevert(