refactor: remove redundant comments and docstrings (#6527)

* refactor: remove redundant comments and docstrings

* fix(signal): annotate async context manager as a generator
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-30 13:07:03 +08:00
1 parent cb3ba45317
commit a4d2430140
922 files changed
+406 -7738

No files matched your search

-1
View File
@@ -1,6 +1,5 @@
import { expect, test } from "@playwright/test";
// Opaque and transparent artwork exercise both common brand-image layouts offline.
const tile = '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#171717"/><circle cx="16" cy="16" r="10" fill="white"/></svg>';
const mark = '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><circle cx="16" cy="16" r="12" fill="#E87D0D"/></svg>';
-2
View File
@@ -6,8 +6,6 @@ import { NanobotClient } from "@/lib/nanobot-client";
import { ThreadMessageCache } from "@/lib/thread-message-cache";
import { ClientProvider } from "@/providers/ClientProvider";
// The browser spec controls HTTP and WebSocket frames; all projection and caching
// run through the real client and thread, without model calls or saved user data.
export function AnswerOrderFixture() {
const [client] = useState(() => new NanobotClient({
url: `ws://${location.host}/answer-order-socket`, reconnect: false,
-1
View File
@@ -156,7 +156,6 @@ test.describe("answer order", () => {
await expect(first).toHaveCount(1);
await expect(last).toHaveCount(1);
await expect(page.getByRole("button", { name: "Stop response" })).toHaveCount(0);
// Completed activity is folded into the answer block, not lost or still running.
const lastBlock = last.locator("xpath=ancestor::*[@data-thread-display-unit]");
await lastBlock.hover();
await lastBlock.getByRole("button", { name: "Message actions" }).click();
-1
View File
@@ -7,7 +7,6 @@ import { useLocalPreferences } from "@/hooks/useLocalPreferences";
import { ThemeProvider, useTheme } from "@/hooks/useTheme";
import { readLocalPreferences, writeLocalPreferences, type LocalPreferences } from "@/lib/local-preferences";
/** Actual appearance controls in a browser-local harness, without a gateway. */
export function AppearanceFixture() {
const { t } = useTranslation();
const { theme, preference, setTheme } = useTheme();
-1
View File
@@ -49,7 +49,6 @@ async function expectFileDetails(page: Page, card: Locator, filename: string, wi
for (const width of [1024, 360]) {
for (const theme of ["light", "dark"]) {
test(`mixed attachments stay compact, aligned and readable at ${width}px in ${theme}`, async ({ page }, testInfo) => {
// The two widths also cover both localized download names, without a second matrix.
const chinese = width === 360;
await page.route("**/fixture/retry.webm", (route) => route.fulfill({ status: 503, body: "Temporarily unavailable" }));
await openAttachments(page, width, theme, chinese ? "zh-CN" : "en");
-1
View File
@@ -17,7 +17,6 @@ const messages: UIMessage[] = [{
createdAt: 1_700_000_000_000,
}];
// Real components with controlled state. No model calls or saved user data.
export function ChatFailureFixture({ parameters }: { parameters: URLSearchParams }) {
useReadingTypography();
const [visible, setVisible] = useState(true);
-1
View File
@@ -72,7 +72,6 @@ for (const width of [1440, 390]) {
const imageBox = (await image.boundingBox())!;
expect(imageBox.y + imageBox.height).toBeLessThan(bubbleBox.y);
if (width === 390) {
// Narrow screens use a touch action row below the message, not a hover rail.
await expect(page.locator("[data-message-mobile-actions]")).toBeVisible();
expect(triggerBox.y).toBeGreaterThanOrEqual(bubbleBox.y + bubbleBox.height);
expect(triggerBox.height).toBeGreaterThanOrEqual(44);
-1
View File
@@ -48,7 +48,6 @@ for (const width of [1280, 390]) {
expect(await action.boundingBox()).toEqual(bounds);
expect(await model.boundingBox()).toEqual(modelBounds);
// Reverse mid-transition, then send before the new icon has settled.
await input.fill("");
await input.fill("A newer draft");
await action.click();
-1
View File
@@ -175,7 +175,6 @@ test("an enlarged diagram keeps its camera through resize and recoloring", async
await expect(dialog).toBeVisible();
await expect(fit).toHaveText("150%");
await expect(dialog.locator("img")).toHaveAttribute("src", before!);
// Change the trusted document palette without closing the reader.
await page.evaluate(() => document.documentElement.classList.toggle("dark"));
await expect(dialog.locator("img")).not.toHaveAttribute("src", before!);
await expect(fit).toHaveText("150%");
-1
View File
@@ -22,7 +22,6 @@ for (const width of [360, 1024]) {
const longPath = references.first();
await expect(longPath).toContainText("…");
await expect(references.nth(1)).not.toContainText("…");
// The last filename stays inside the clipping viewport, without reversing text direction.
const filename = longPath.locator(".font-semibold");
await expect(filename).toHaveCSS("color", "rgb(3, 105, 161)");
const tail = await filename.evaluate((element) => {
-7
View File
@@ -289,7 +289,6 @@ test("wheel loading hands off to a retained 48px slot; prepend and delayed layou
await expect(body.locator(".thread-history-slot")).toHaveCount(0);
await page.screenshot({ path: test.info().outputPath("history-prepend-stable.png") });
// The reclaimed boundary scrolls as ordinary message flow, with no retained spacer.
const beforeScroll = await body.evaluate((node) => node.scrollTop);
const anchorBeforeScroll = await anchorTop(body, "Question 40");
await body.hover();
@@ -953,7 +952,6 @@ test("failed Blocks animate without visible error text; pulling retries once and
await expectCoordinates(body, "Question 40", held);
expect(history.reads).toHaveLength(1);
// This is a fresh pull at the failed boundary, not a ready-button-only path.
await requestOlderWithWheel(body, history, 2);
await expect(header).toHaveAttribute("data-state", "loading");
await page.mouse.wheel(0, -120);
@@ -1127,7 +1125,6 @@ test("bounded navigation retains three pages and reclaims each completed wheel o
const header = page.locator(".thread-history-status");
const slot = body.locator(".thread-history-slot");
const approachNextHead = async (text: string) => {
// Real scrolling stops just short of the boundary, before it can request.
const scrollTop = await body.evaluate((node) => node.scrollTop);
expect(scrollTop).toBeGreaterThan(120);
await body.hover();
@@ -1145,7 +1142,6 @@ test("bounded navigation retains three pages and reclaims each completed wheel o
await stableLayout(body);
expect(history.reads).toHaveLength(0);
// An unloaded rail destination replaces latest with P0 (38..49).
await jumpViaRail(page, 38);
await expect.poll(() => history.reads.length).toBe(1);
history.complete();
@@ -1162,7 +1158,6 @@ test("bounded navigation retains three pages and reclaims each completed wheel o
expect((await historyGeometry(body, "Question 38")).slotBeforeKey).toBeNull();
await expect(body.locator('[data-thread-display-unit^="u"]')).toHaveCount(24);
// Reach each prepended page head instead of loading from the old reading slot.
const atSecondHead = await approachNextHead("Question 26");
expect(atSecondHead.firstKey).toBe("u26");
expect(atSecondHead.slotBeforeKey).toBeNull();
@@ -1177,7 +1172,6 @@ test("bounded navigation retains three pages and reclaims each completed wheel o
expect((await historyGeometry(body, "Question 26")).slotBeforeKey).toBeNull();
await expect(body.locator('[data-thread-display-unit^="u"]')).toHaveCount(36);
// Completed feedback is removed and cannot add a fourth cached page.
await expect(header).toHaveCount(0);
await stableLayout(body);
await expect(page.getByText("No earlier messages", { exact: true })).toHaveCount(0);
@@ -1209,7 +1203,6 @@ test("bounded navigation retains three pages and reclaims each completed wheel o
await expect(page.getByText("No earlier messages", { exact: true })).toHaveCount(0);
expect(history.reads).toEqual(["?limit=24&after=38", "?limit=24&before=38", "?limit=24&before=26", "?limit=24&before=14"]);
// A real Home key reaches the next boundary and rebinds without a wheel pull.
const atKeyboardHead = await approachNextHead("Question 2");
expect(atKeyboardHead.firstKey).toBe("u2");
expect(atKeyboardHead.slotBeforeKey).toBeNull();
@@ -15,7 +15,6 @@ const sessions: ChatSummary[] = ["a", "b"].map((suffix) => ({
preview: "",
}));
// Synthetic backend-boundary reproduction, not an original user recording.
export function HistoryHydrationFixture() {
const [client] = useState(() => new NanobotClient({
url: `${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}/nan311-fixture-ws`,
-3
View File
@@ -2,8 +2,6 @@ import { expect, test, type Locator, type Page, type Route, type WebSocketRoute
import type { InboundEvent, ThreadProjectionEvent, UITurnPhase, WebuiThreadPersistedPayload } from "../src/lib/types";
// Controlled synthetic backend traffic, not a replay of an original user recording.
// Every body assertion goes through the real socket/client/provider/ThreadShell path.
const A = "nan311-a";
const B = "nan311-b";
const TURN = "nan311-active-turn";
@@ -81,7 +79,6 @@ async function installBackend(page: Page) {
const url = new URL(route.request().url());
reads.push({ chatId: decodeURIComponent(url.pathname.split("/")[3]!).slice("websocket:".length),
before: url.searchParams.get("before"), after: url.searchParams.get("after"), route });
// Deliberately leave this request pending until the test releases this exact page.
});
await page.routeWebSocket((url) => url.pathname === "/nan311-fixture-ws", (wire) => {
socket = wire;
-3
View File
@@ -46,7 +46,6 @@ test("complete rail scrolls independently, jumps to unloaded history and returns
await expect.poll(() => rail.evaluate((node) => node.scrollTop)).toBeLessThan(25000);
expect(await body.evaluate((node) => node.scrollTop)).toBe(initialBodyTop);
expect(await rail.getByRole("button").count()).toBeLessThan(70);
// Keyboard navigation reaches the beginning without mounting the whole list.
await rail.getByRole("button").first().focus();
await page.keyboard.press("Home");
const first = rail.getByRole("button", { name: "Jump to message: Question 0", exact: true });
@@ -72,7 +71,6 @@ test("complete rail scrolls independently, jumps to unloaded history and returns
await expect(rail.locator('[aria-current="location"]')).toBeInViewport();
expect(await rail.evaluate((node) => getComputedStyle(node).maskImage)).toContain("linear-gradient");
await page.screenshot({ path: "test-results/prompt-rail-long.png" });
// Short lists remain centered in the same viewport-relative space.
await page.goto("/browser/fixture.html?case=rail&short=1&workbench=1");
const markers = page.getByTestId("prompt-rail-marker");
await expect(markers).toHaveCount(5);
@@ -81,7 +79,6 @@ test("complete rail scrolls independently, jumps to unloaded history and returns
const middle = await markers.nth(2).boundingBox();
expect(Math.abs(middle!.y + middle!.height / 2 - (bounds!.y + bounds!.height / 2))).toBeLessThan(2);
await page.screenshot({ path: "test-results/prompt-rail-short.png" });
// A taller composer in a shorter window must not push navigation above center.
await page.setViewportSize({ width: 1440, height: 640 });
await page.goto("/browser/fixture.html?case=rail&short=1&tall-composer=1&workbench=1");
await expect(markers).toHaveCount(5);
-1
View File
@@ -122,7 +122,6 @@ for (const width of [1440, 390]) {
const statusSlot = (await row.locator(":scope > span").first().boundingBox())!;
await page.mouse.move(1, 1);
await page.screenshot({ path: info.outputPath("one-task-ring-running.png") });
// Finish through the existing control without dismissing the reading view.
await page.getByRole("button", { name: "全部完成", exact: true }).evaluate(node => (node as HTMLButtonElement).click());
const heading = tree.getByRole("heading", { level: 2, name: "天气结果" });
await expect(heading).toBeVisible();
-2
View File
@@ -152,7 +152,6 @@ for (const width of [1440, 390]) {
expect(middle.paint[index], `${selector} must not snap to the target palette`).not.toBe(after[index]);
expect(middle.paint[index], `${selector} must leave the old palette`).not.toBe(before[index]);
}
// These in-flow wrappers now reveal their painted parent instead of adding a second canvas.
expect(middle.footer).toBe("rgba(0, 0, 0, 0)");
expect(middle.sidebarFooter).toBe("rgba(0, 0, 0, 0)");
expect(middle.gradient).toBe(middle.paint[0]);
@@ -216,7 +215,6 @@ for (const width of [1440, 390]) {
await expect(toggle).toBeFocused();
expect(await input.boundingBox()).toEqual(box);
await page.screenshot({ path: test.info().outputPath(`crossfade-${width}-${initial}-mid.png`), animations: "allow" });
// Keyboard input still reaches the live DOM while the native snapshots are paused.
await page.keyboard.press("Space");
for (let step = 0; step < 20 && !await input.evaluate(node => node === document.activeElement); step++) {
await page.keyboard.press("Tab");
-9
View File
@@ -140,7 +140,6 @@ async function cacheFirstPublicIcon(request) {
await cache.put(request, response.clone());
await trimIconCache(cache);
} catch {
// Cache storage is optional; a successful network response still wins.
}
return response;
}
@@ -152,7 +151,6 @@ self.addEventListener("install", (event) => {
self.skipWaiting();
});
// Collect same-origin paths referenced by the given HTML document.
function referencedAssetPaths(html) {
const refs = new Set();
const re = /(?:src|href)="(\/[^"]*)"/g;
@@ -200,12 +198,6 @@ async function refreshAssetManifest(cache) {
return true;
}
// Drop cached entries that the current index.html no longer references.
// CACHE_NAME is stable across deployments, so without this, hashed assets from
// previous builds would pile up in the same cache forever. The cached
// index.html is the latest one this client saw (navigation is network-first
// and overwrites it on every successful visit), so pruning against it keeps
// the offline shell consistent with the last loaded build.
async function pruneStaleEntries() {
const cache = await caches.open(CACHE_NAME);
const cachedIndex = await cache.match("/");
@@ -290,7 +282,6 @@ self.addEventListener("fetch", (event) => {
const isNavigation = request.mode === "navigate";
if (!isNavigation && !NETWORK_FIRST_STATIC_PATHS.has(path)) return;
// App shell and public files: network-first with an offline fallback.
const networkResponse = fetch(request);
event.waitUntil(
networkResponse
-1
View File
@@ -2889,7 +2889,6 @@ function Shell({
"relative flex h-full w-full overflow-hidden",
)}
>
{/* Host sidebar: in normal flow, so the thread area width stays honest. */}
{showMainSidebar ? (
<aside
data-testid="host-sidebar-flow"
-2
View File
@@ -29,12 +29,10 @@
padding-inline: calc(var(--math-tag-width) + 1em);
}
/* Math-heavy prose uses a tighter reading rhythm than ordinary chat. */
.markdown-content:has(.math-fit) {
--cjk-line-height: 1.65;
}
/* Keep list formulas close to their explanations. */
.markdown-content li .math-fit {
margin-block: 0.3em 0.35em;
}
-1
View File
@@ -23,7 +23,6 @@ export function useFilePreviewLoader() {
const itemClassName = `${floatingItemClassName} ${floatingItemFocusClassName} cursor-default data-[disabled]:pointer-events-none data-[disabled]:opacity-50`;
/** Copy-only context menu, shared by file references and preview tabs. */
export function FileActions({
path, children, metadata, className,
}: {
@@ -333,7 +333,6 @@ export function fileIconForPath(path: string): LucideIcon {
return FILE_ICONS[fileKindForPath(path)];
}
/** The same file silhouette and stroke in replies, tabs, and attachment tiles. */
export function FileReferenceIcon({ kind, className }: { kind: FileReferenceKind; className?: string }) {
const Icon = FILE_ICONS[kind];
return <Icon aria-hidden strokeWidth={1.75} className={cn("h-[1em] w-[1em] shrink-0", className)} />;
-2
View File
@@ -69,7 +69,6 @@ export function ImageLightbox({
return () => window.removeEventListener("keydown", onKey);
}, [go, onIndexChange, open, total]);
// Neighbours we want the browser to decode eagerly.
const preload = useMemo(() => {
if (index === null || total <= 1) return [] as UIImage[];
const prev = images[(index - 1 + total) % total];
@@ -151,7 +150,6 @@ export function ImageLightbox({
<X className="h-4 w-4" aria-hidden />
</DialogPrimitive.Close>
{/* Invisible preload — browser decodes adjacent images so prev/next swap is instant. */}
<div aria-hidden className="hidden">
{preload.map((img, i) => (
<img key={`${img.url}-${i}`} src={img.url} alt="" />
-1
View File
@@ -77,7 +77,6 @@ export function preloadMarkdownText(): Promise<void> {
return loadMarkdownRenderer().then(() => undefined);
}
/** Lazy boundary for the heavier GFM, math, and code renderer. */
export function MarkdownText({
children,
className,
@@ -521,10 +521,6 @@ function codeFenceFromPreChild(value: ReactNode): { code: string; language?: str
};
}
/**
* Heavy markdown stack (GFM, math, KaTeX, syntax highlighting) kept in a
* separate chunk so the app shell can paint sooner on refresh.
*/
export default function MarkdownTextRenderer({
children,
className,
@@ -562,7 +558,6 @@ export default function MarkdownTextRenderer({
/>
);
}
/** Plain fenced ``` blocks (no language) & wide one-liners: block monospace, not inline pill. */
const widePlainBlock = raw.includes("\n") || raw.length > 120;
if (widePlainBlock) {
return (
-11
View File
@@ -46,13 +46,11 @@ import type {
interface MessageBubbleProps {
message: UIMessage;
/** Give temporary-chat user turns the dashed private-mode treatment. */
temporary?: boolean;
cliApps?: CliAppInfo[];
mcpPresets?: McpPresetInfo[];
slashCommands?: SlashCommand[];
onOpenFilePreview?: (path: string) => void;
/** Context-menu trigger positioned against this message's visual block. */
contextMenu?: ReactNode;
}
@@ -116,7 +114,6 @@ function messageCopyContent(message: UIMessage, t: (key: string) => string) {
: message.content;
}
/** The same copy behavior in the desktop menu and the mobile reply footer. */
export function MessageCopyButton({ message, className }: { message: UIMessage; className?: string }) {
const { t } = useTranslation();
const content = messageCopyContent(message, t);
@@ -151,7 +148,6 @@ interface MessageBlockMenuActionsProps {
sheet?: boolean;
}
/** Actions and metadata shown after opening a visual message block's context panel. */
export function MessageBlockMenuActions({
message,
isTurnStreaming = false,
@@ -405,7 +401,6 @@ function IncomingSessionMessage({
);
}
/** Render user turns as compact bubbles and assistant turns as document-like prose. */
export function MessageBubble({
message,
temporary = false,
@@ -706,7 +701,6 @@ function MessageMedia({
);
}
/** Quiet pre-token state that occupies a stable line in the answer column. */
function ThinkingState() {
const { t } = useTranslation();
return (
@@ -748,11 +742,6 @@ interface TraceGroupProps {
message: UIMessage;
}
/**
* Collapsible group of tool-call / progress breadcrumbs. Defaults to
* collapsed because tool traces are supporting evidence, not the answer.
* A single click expands the exact calls when the user wants details.
*/
function TraceGroup({ message }: TraceGroupProps) {
const { t } = useTranslation();
const lines = message.traces ?? [message.content];
+1 -1
View File
@@ -50,7 +50,7 @@ export function StarPrompt({ ready }: { ready: boolean }) {
previousFocus.current = document.activeElement instanceof HTMLElement
? document.activeElement : null;
setOpen(true);
}).catch(() => { /* Optional invitations stay hidden when storage is unavailable. */ });
}).catch(() => {});
});
return () => { cancelled = true; unsubscribe(); };
}, [client, ready]);
-1
View File
@@ -3,7 +3,6 @@ import createElement from "react-syntax-highlighter/dist/esm/create-element";
type RowsProps = Parameters<NonNullable<SyntaxHighlighterProps["renderer"]>>[0];
/** Keep inline tokens in one wrapping flow beside the line-number gutter. */
export function WrappedCodeRows({ rows, ...props }: RowsProps) {
return rows.map((row, index) => {
const [lineNumber, ...content] = row.children!;
@@ -8,7 +8,6 @@ import { HostSwitcherView } from "./HostSwitcherView";
export { HostNavigationContext, type HostPicker } from "./host-navigation";
export { RemoteHostMenu } from "./HostSwitcherView";
/** Connect the sidebar's presentation to the active host and client. */
export function HostSwitcher({ collapsed = false, portalContainer }: { collapsed?: boolean; portalContainer?: HTMLElement | null }) {
const picker = useContext(HostNavigationContext);
const { client } = useClient();
@@ -5,7 +5,6 @@ import { remoteAction } from "@/lib/remote-instances";
import { useRemoteConnections } from "./remote-context";
import { PairRouteSettingsView } from "./PairRouteSettingsView";
/** An explicit escape hatch for a VPN/bound-interface route, not a new SSH form. */
export function PairRouteSettings({ id, onSaved, showHint = true }: { id: string; onSaved?: () => void; showHint?: boolean }) {
const { t } = useTranslation();
const { client } = useClient();
@@ -34,7 +34,6 @@ export function QuickPairSetup({ returned, active = true, onSSH, onClose }: { re
useEffect(() => {
if (!pending) { setBusyVisible(false); return; }
// Fast local preparation should not flash a loading label or move the dialog.
const timer = window.setTimeout(() => setBusyVisible(true), 200);
return () => window.clearTimeout(timer);
}, [pending]);
@@ -167,7 +167,6 @@ export function QuickPairSetupView({
</div>;
}
/** Decorative overview, not a live connection-status indicator. */
function RemoteConnectionIllustration() {
return <svg viewBox="0 0 208 88" width="184" height="78" aria-hidden="true" focusable="false" className="mx-auto mb-4 shrink-0 text-foreground/70" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
<path d="M78 51 C111 65 114 28 146 36" className="text-muted-foreground/50" strokeWidth="2.5" />
@@ -26,7 +26,6 @@ const emptyProfile = (): Omit<RemoteProfile, "id" | "connected"> => ({
config_path: "~/.nanobot/config.json", runtime_user: "",
});
/** The page is a server directory. Add/edit/first-use verification share one dialog. */
export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChromeInset = false, onBackToChat }: {
mainNavigationExpanded?: boolean;
hostChromeInset?: boolean;
@@ -9,7 +9,6 @@ type SSHHostPickerProps = Pick<SSHHostPickerViewProps,
configFile: string;
};
/** One address field for both manual entry and existing SSH aliases. */
export function SSHHostPicker({ configFile, suggestions = true, ...props }: SSHHostPickerProps) {
const { t } = useTranslation();
const { client } = useClient();
@@ -47,7 +46,6 @@ export function SSHHostPicker({ configFile, suggestions = true, ...props }: SSHH
const unsubscribe = client.onStatus((status) => {
if (status === "open" && !started) {
started = true;
// Custom paths update quietly after typing; no separate "read config" flow.
timer = setTimeout(() => { void load(file); }, file ? 300 : 0);
}
});
@@ -1,4 +1,3 @@
/* Remote dialogs share typography and action sizing without changing app-wide controls. */
.remote-dialog {
min-inline-size: 0;
max-block-size: min(85dvh, calc(100dvh - 2rem));
@@ -46,7 +45,6 @@
grid-template-columns: auto minmax(0, 1fr);
}
/* Keep secondary actions readable when translations need a second line. */
.remote-pair-alternatives {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
@@ -74,7 +74,6 @@ export function ReadingSettings({ preferences, onChange }: {
/>
<TooltipProvider>
<Tooltip open={hintOpen} onOpenChange={(open) => {
// Keep guidance visible while typing, including pointer/touch focus.
if (open || document.activeElement !== inputRef.current) setHintOpen(open);
}}>
<TooltipTrigger asChild>
@@ -8,7 +8,6 @@
.appearance-theme-check { opacity: 0; }
.appearance-theme-option input:checked + .appearance-theme-card .appearance-theme-check { opacity: 1; }
.appearance-theme-label { display: flex; align-items: center; justify-content: space-between; gap: 4px; padding: 8px 4px 2px; min-height: 36px; }
/* Nested surfaces follow the outer curve minus their actual inset, including the border. */
.appearance-theme-miniature { --mini-paper: #fff; --mini-sidebar: #f1f0ec; --mini-line: #dad9d5; display: flex; height: 84px; overflow: hidden; border-radius: calc(var(--radius-panel) - var(--appearance-theme-inset) - 1px); background: var(--mini-paper); box-shadow: inset 0 0 0 1px rgb(0 0 0 / 0.04); }
.appearance-theme-miniature[data-mode="dark"] { --mini-paper: #303030; --mini-sidebar: #383838; --mini-line: #656565; }
.appearance-theme-miniature[data-mode="system"] { --mini-paper: linear-gradient(110deg, #fff calc(50% - 0.5px), #303030 calc(50% + 0.5px)); --mini-sidebar: #f1f0ec; --mini-line: #969590; }
@@ -285,7 +285,6 @@ function FoldedAgentActivity({
const [now, setNow] = useState(() => Date.now());
const wasTurnStreamingRef = useRef(isTurnStreaming);
const wasTurnStreaming = wasTurnStreamingRef.current;
/** Auto follows execution; expanded keeps details open unless manually collapsed. */
const outerExpanded = expanded ?? (
userToggledOuter
? outerOpenLocal
@@ -82,8 +82,6 @@ function resolveCopy(
case "model_request_failed":
return resolveModelRequestFailureCopy(error, t);
default: {
// Exhaustiveness guard: if a new StreamError kind is added, TS will
// complain here until we add a corresponding i18n branch.
const _exhaustive: never = error;
return { title: String(_exhaustive), body: "" };
}
@@ -5,7 +5,6 @@ import { cn } from "@/lib/utils";
export function ControlChevron({ className }: { className?: string }) {
return (
<ChevronDown
// Keep the horizontal viewBox around the artwork, including its stroke.
viewBox="5 0 14 24"
width={14}
height={24}
@@ -1,6 +1,5 @@
import { useLayoutEffect, useRef, useState } from "react";
/** Animate a line-limited preview without swapping or duplicating its text. */
export function ExpandableText({
children, expanded, lines, className, id,
}: {
@@ -2,7 +2,6 @@ import type { ReactNode } from "react";
import { cn } from "@/lib/utils";
/** L→R sheen on the glyphs themselves; inactive labels stay solid muted text. */
export function StreamingLabelSheen({
children,
active,
@@ -728,12 +728,8 @@ export function PaneWorkbench({
>
{renderPane(pane, {
active,
// A single conversation owns its header, alongside its preview tabs.
// Multiple conversation panes still share the workbench toolbar.
headerPortalTarget: chrome && displayedPanes.length > 1 ? headerPortalTarget : undefined,
composerPortalTarget: chrome ? composerPortalTarget : undefined,
// A single chat includes the shared composer in its visual frame.
// Split chats keep navigation centered within their own pane.
navigationFrame: displayedPanes.length === 1 ? navigationFrame : undefined,
headerActions,
})}
-1
View File
@@ -8,7 +8,6 @@ const bundles = import.meta.glob<{ default: Record<string, unknown> }>(
{ eager: true },
);
// Gallery copy is a development-only namespace; the application keeps its own bundles.
export async function initializeGalleryI18n(): Promise<void> {
await initializeI18n();
for (const { code } of supportedLocales) {
-1
View File
@@ -99,7 +99,6 @@ function FilesPreview() {
<p role="status" className="mt-4 text-xs text-muted-foreground">{opened ? t("controls.files.selected", { path: opened }) : t("controls.files.hint")}</p></>;
}
// Inline SVG fixtures stay local to the developer gallery and need no network fetch.
const mediaImages = ["#2563eb", "#0d9488", "#9333ea", "#ea580c", "#be123c", "#4f46e5"].map((color, index) => ({
number: index + 1,
url: `data:image/svg+xml,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="960" height="640" viewBox="0 0 960 640"><rect width="960" height="640" fill="${color}"/><path d="M0 480L240 160L480 480L720 160L960 480" fill="none" stroke="white" stroke-opacity=".35" stroke-width="32"/><circle cx="480" cy="320" r="120" fill="white" fill-opacity=".2"/><text x="480" y="355" text-anchor="middle" font-family="sans-serif" font-size="100" fill="white">${index + 1}</text></svg>`)}`,
-22
View File
@@ -2,7 +2,6 @@
@tailwind components;
@tailwind utilities;
/* Notices and the input share one width, including the compact screen inset. */
.thread-composer-stack {
--composer-content-width: 49.5rem;
}
@@ -109,7 +108,6 @@
--temporary-control-active: #ef8e30;
--temporary-foreground: 17 88% 32%;
--radius: 0.4375rem;
/* Shared shape scale: marks, compact content, controls, and progressively larger surfaces. */
--radius-mark: 0.25rem;
--radius-compact: 0.5rem;
--radius-control: 0.75rem;
@@ -182,7 +180,6 @@
--muted-foreground: 0 0% 72%;
--accent: 0 0% 25%;
--accent-foreground: 0 0% 98%;
/* Destructive text needs contrast on dark surfaces; filled controls use a dark label. */
--destructive: 0 93.5% 81.8%;
--destructive-foreground: 0 0% 9%;
--border: 0 0% 28%;
@@ -476,7 +473,6 @@
height: 0;
}
/* Keep the outer document rhythm clean at message boundaries. */
.markdown-content > :first-child {
@apply mt-0;
}
@@ -542,7 +538,6 @@
--cjk-line-height: 1.8;
}
/* Balance short headings; preserve explicit line breaks in chat prose. */
.markdown-content :is(h1, h2, h3, h4, h5, h6),
.settings-section-title {
text-wrap: balance;
@@ -553,8 +548,6 @@
--activity-animation: 2.8s ease-in-out infinite;
}
/* L→R sheen clipped to live activity labels. The highlight lives inside
the glyphs, not in the row background, so dark mode stays quiet. */
@keyframes streaming-text-sheen-ltr {
0% {
background-position: 140% 50%;
@@ -794,7 +787,6 @@
opacity: 1;
transform: translateY(0);
}
/* Shared in-flow disclosure: animate intrinsic height without measuring it. */
.inline-disclosure {
--inline-disclosure-duration: 220ms;
@@ -882,7 +874,6 @@
visibility: hidden;
}
}
/* Split content leaves no margin for floating conversation controls. */
.thread-preview-layout[data-preview-open] > .thread-conversation {
--thread-header-position: relative;
}
@@ -897,7 +888,6 @@
transform-origin: top left;
}
/* Subtle scrollbar that doesn't fight the dark background. */
.scrollbar-thin {
scrollbar-width: thin;
scrollbar-color: hsl(var(--muted-foreground) / 0.4) transparent;
@@ -928,8 +918,6 @@
* overflow-x: auto), so clipping the thread column horizontally is safe.
*/
/* Prose container: allow it to shrink within its column and break long words
so long URLs / paths never stretch the conversation wider than 100vw. */
.markdown-content {
min-width: 0;
max-width: 100%;
@@ -937,14 +925,12 @@
word-wrap: break-word;
}
/* Long links and inline code break rather than stretch the column. */
.markdown-content a,
.markdown-content code {
overflow-wrap: anywhere;
word-wrap: break-word;
}
/* Fenced / pre blocks scroll inside their own box, never the page. */
.markdown-content pre,
.not-prose pre {
max-width: 100%;
@@ -960,8 +946,6 @@
renderer's overflow-x:auto wrapper remains a fallback for content that
cannot shrink. */
/* Clip any residual horizontal bleed at the thread column edge. Vertical
scrolling and internal code-block scroll are unaffected. */
.thread-viewport-scrollbar {
overflow-x: hidden;
}
@@ -1172,7 +1156,6 @@
}
}
/* On phones, actions follow the message instead of taking a separate gutter. */
@media (max-width: 767px) {
.thread-message-row {
padding-inline: 1rem;
@@ -1196,7 +1179,6 @@
}
}
/* Composer controls adapt to their actual container, not just the viewport. */
.thread-composer-surface {
--composer-shadow-color: 240 10% 16%;
--tw-shadow: inset 0 0 0 1px hsl(var(--border) / 0.75), 0 4px 18px -8px hsl(var(--composer-shadow-color) / 0.12);
@@ -1355,7 +1337,6 @@
}
}
/* Match the directory glyph's start to the attachment glyph, not its hit area. */
.thread-composer-meta {
padding-inline-start: calc(var(--composer-footer-inset) + var(--composer-action-margin) + (var(--composer-action-size) - 0.875rem) / 2 - 0.5rem);
}
@@ -1448,8 +1429,6 @@
}
}
/* Settings grid: 4px baseline; 720px frame; 12 columns / 24px gutter on
desktop, 4 columns / 16px gutter on mobile. Rows share the same tracks. */
@layer components {
.settings-grid {
--settings-columns: 4;
@@ -1468,7 +1447,6 @@
.settings-grid.settings-feature-page.settings-automations-grid {
max-inline-size: calc(60rem + 2 * var(--settings-margin));
}
/* Stack a task's status below its title when the content column is narrow. */
.automations-page {
--settings-inset: 1rem;
container: automations / inline-size;
-1
View File
@@ -2,7 +2,6 @@ import { useLayoutEffect } from "react";
import { useMediaQuery } from "@/hooks/useMediaQuery";
import { isNativeRuntime } from "@/lib/runtime";
/** One viewport owner for navigation, workbench composers and ordinary threads. */
export function useAppViewport() {
const touch = useMediaQuery("(any-pointer: coarse)");
useLayoutEffect(() => {
+12 -30
View File
@@ -4,12 +4,6 @@ import type { LocalAttachment } from "../../../packages/client-events/attachment
import { encodeImage, type EncodeFailure } from "@/lib/imageEncode";
import type { WebUIIngressLimits } from "@/lib/types";
/** Lifecycle stages of one attachment:
*
* - ``encoding`` — posted to the Worker / read from disk; chip shows a spinner
* - ``ready`` — ``dataUrl`` available; safe to submit
* - ``error`` — validation / decode failure; chip shows inline error
*/
type AttachmentStatus = "encoding" | "ready" | "error";
export type AttachmentKind = "image" | "video" | "file";
@@ -18,17 +12,16 @@ interface AttachedAttachment {
kind: AttachmentKind;
file: Pick<File, "name" | "size" | "type">;
local?: LocalAttachment;
/** Optimistic ``blob:`` preview URL; revoked on ``remove`` / ``clear`` /
* unmount. */
/** Preview URL; owned ``blob:`` URLs are revoked on removal, clearing or unmount. */
previewUrl?: string;
status: AttachmentStatus;
/** Populated when ``status === "ready"``. */
/** Encoded payload; ready local attachments use ``local`` instead. */
dataUrl?: string;
/** Size of the final encoded payload (base64 bytes decoded). */
encodedBytes?: number;
/** Whether the Worker re-encoded the image to hit the size budget. */
/** Whether image bytes were re-encoded to meet the size budget. */
normalized?: boolean;
/** Human-readable validation / encoding error when ``status === "error"``. */
/** Machine-readable error code for callers to localize when ``status === "error"``. */
error?: AttachmentError;
}
@@ -47,12 +40,12 @@ export type RestoredReadyImage = RestoredReadyAttachment;
*
* Callers localize these via the ``composer.imageRejected.*`` i18n table. */
export type AttachmentError =
| "unsupported_type" // server whitelist excludes this MIME
| "empty_file" // attachments must contain bytes
| "unsupported_type"
| "empty_file"
| "too_many_attachments" // non-video per-message cap reached before enqueue
| "too_many_videos" // video slot is already occupied
| "total_too_large" // decoded attachments exceed the business-policy total
| "magic_mismatch" // extension lies about the real content
| "magic_mismatch" // bytes lack a supported image signature
| "decode_failed" // Worker couldn't decode / re-encode
| "too_large" // even after normalization we exceed the budget
| "io"; // file read failed at the browser layer
@@ -231,17 +224,15 @@ export interface UseAttachedImagesApi {
};
addLocal: (attachment: LocalAttachment, options?: { restoringDraft: boolean }) => AttachmentCountError | null;
remove: (id: string) => { nextFocusId: string | null };
/** Revoke every staged blob URL and drop all attachments. Called after a
* successful submit — the optimistic bubble holds onto an independent
* ``data:`` URL so tearing down blob previews here is safe. */
/** Revoke owned blob previews and clear staged entries; submitted attachments
* retain independent data URLs or local references. */
clear: () => void;
/** Restore already-encoded attachments, e.g. a queued composer draft moving
* back into the input. These entries are immediately sendable and use image
* ``data:`` URLs as stable previews. */
/** Restore ready encoded payloads or local references, preserving draft overflow
* for the user to resolve before sending. */
restoreReadyImages: (images: RestoredReadyAttachment[]) => void;
/** ``true`` when at least one attachment is still encoding — Send should wait. */
encoding: boolean;
/** ``true`` when we've hit ``MAX_ATTACHMENTS_PER_MESSAGE``. */
/** ``true`` when both the non-video and video attachment quotas are full. */
full: boolean;
}
@@ -249,14 +240,6 @@ interface UseAttachedImagesOptions {
ingressLimits?: WebUIIngressLimits | null;
}
/** Manage the lifecycle of attachments in the Composer.
*
* Responsibilities in one place:
* - validation (MIME whitelist, count cap)
* - blob URL creation + revocation
* - Worker orchestration
* - focus bookkeeping so keyboard delete doesn't strand the user
*/
export function useAttachedImages({
ingressLimits = null,
}: UseAttachedImagesOptions = {}): UseAttachedImagesApi {
@@ -410,7 +393,6 @@ export function useAttachedImages({
}
const next = [...prev.slice(0, idx), ...prev.slice(idx + 1)];
imagesRef.current = next;
// Prefer moving focus to the chip at the same index, else previous.
const candidate = next[idx] ?? next[idx - 1];
nextFocusId = candidate?.id ?? null;
return next;
-2
View File
@@ -26,7 +26,6 @@ function extractImageFilesFromPaste(
return files;
}
/** Extract dropped attachment files, mirroring ``extractImageFilesFromPaste``. */
function extractImageFilesFromDrop(
event: DragEvent | React.DragEvent,
): File[] {
@@ -41,7 +40,6 @@ function extractImageFilesFromDrop(
}
export interface UseClipboardAndDropApi {
/** Whether a drag is currently hovering the drop zone (toggle dragover UI). */
isDragging: boolean;
onPaste: (
event: React.ClipboardEvent,
-6
View File
@@ -49,7 +49,6 @@ const VISIBLE_STREAM_FLUSH_INTERVAL_MS = 50;
const EMPTY_INITIAL_MESSAGES: UIMessage[] = [];
const EMPTY_COMPLETED_TURN_IDS: readonly string[] = [];
/** Own the received transcript, accepting fetched pages and live events together. */
/** Payload passed to ``send`` when the user attaches one or more files.
*
* ``media`` is handed to the wire client verbatim; ``preview`` powers the
@@ -153,7 +152,6 @@ export function useNanobotStream(
isStreaming: boolean;
/** Unix epoch seconds when the current user turn started (WebSocket ``goal_status``). */
runStartedAt: number | null;
/** Transient model retry state for the active turn. */
retryStatus: RetryStatus | null;
/** Latest sustained goal for this ``chatId`` (``goal_state`` WS events). */
goalState: GoalStateWsPayload | undefined;
@@ -174,8 +172,6 @@ export function useNanobotStream(
/** Latest transport-level fault raised since the last ``dismissStreamError``.
* ``null`` when there is nothing to show. */
streamError: StreamError | null;
/** Clear the current ``streamError`` (e.g. after the user dismisses the
* notification or starts a fresh action). */
dismissStreamError: () => void;
} {
const { client, getToken } = useClient();
@@ -210,7 +206,6 @@ export function useNanobotStream(
setHistoryState(transcriptRef.current.paging);
}, []);
const [messageScope, setMessageScope] = useState({ chatId, historyKey, client });
/** If history ends in unfinished agent activity, keep the loading spinner alive. */
const initialStreaming = useMemo(() => {
if (completedTurnIds.length === 0) return hasPendingAgentActivity(initialMessages);
const completedInitialTurns = new Set(completedTurnIds);
@@ -502,7 +497,6 @@ export function useNanobotStream(
setGoalState(chatId ? client.getGoalState(chatId) : undefined);
setRecoveryState(null);
clearPendingStreamWork();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [chatId, client, historyKey, clearActivitySegment, clearPendingStreamWork, setMessages]);
useEffect(() => {
-1
View File
@@ -4,7 +4,6 @@ function pageIsVisible(): boolean {
return typeof document === "undefined" || document.visibilityState !== "hidden";
}
/** Keep background tabs quiet while resuming work immediately on return. */
export function usePageVisibility(): boolean {
const [visible, setVisible] = useState(pageIsVisible);
-2
View File
@@ -19,7 +19,6 @@ import type {
const CHAT_CREATE_TIMEOUT_MS = 60_000;
/** Sidebar state: fetches the full session list and exposes create / delete actions. */
export function useSessions(): {
sessions: ChatSummary[];
loading: boolean;
@@ -206,7 +205,6 @@ export function useSessions(): {
};
}
/** Read-only history view backed by the conversation owner. */
export function useSessionHistory(key: string | null) {
const { messages, history, refreshHistory, loadOlder } = useNanobotStream(
null, undefined, false, undefined, undefined, undefined, { key },
-7
View File
@@ -416,16 +416,12 @@ async function convertBlobToWav(blob: Blob): Promise<string> {
}
}
/**
* Encode an AudioBuffer as a 16-bit PCM WAV Blob.
*/
function audioBufferToWav(buffer: AudioBuffer): Blob {
const numChannels = buffer.numberOfChannels;
const sampleRate = buffer.sampleRate;
const format = 1; // PCM
const bitsPerSample = 16;
// Interleave channels
const channels: Float32Array[] = [];
for (let ch = 0; ch < numChannels; ch++) {
channels.push(buffer.getChannelData(ch));
@@ -450,12 +446,10 @@ function audioBufferToWav(buffer: AudioBuffer): Blob {
const buffer2 = new ArrayBuffer(totalSize);
const view = new DataView(buffer2);
// RIFF header
writeString(view, 0, "RIFF");
view.setUint32(4, totalSize - 8, true);
writeString(view, 8, "WAVE");
// fmt sub-chunk
writeString(view, 12, "fmt ");
view.setUint32(16, 16, true); // sub-chunk size
view.setUint16(20, format, true);
@@ -465,7 +459,6 @@ function audioBufferToWav(buffer: AudioBuffer): Blob {
view.setUint16(32, blockAlign, true);
view.setUint16(34, bitsPerSample, true);
// data sub-chunk
writeString(view, 36, "data");
view.setUint32(40, dataSize, true);
-3
View File
@@ -11,7 +11,6 @@ export class BootstrapAuthRequiredError extends Error {
}
}
/** Read a previously saved bootstrap secret from localStorage. */
export function loadSavedSecret(): string {
if (typeof window === "undefined") return "";
try {
@@ -21,7 +20,6 @@ export function loadSavedSecret(): string {
}
}
/** Persist the bootstrap secret so page reloads don't re-prompt. */
export function saveSecret(secret: string): void {
try {
window.localStorage.setItem(SECRET_STORAGE_KEY, secret);
@@ -30,7 +28,6 @@ export function saveSecret(secret: string): void {
}
}
/** Clear the saved bootstrap secret (sign out). */
export function clearSavedSecret(): void {
try {
window.localStorage.removeItem(SECRET_STORAGE_KEY);
-1
View File
@@ -81,7 +81,6 @@ export interface RunState {
const COMPLETED_TURN_FENCE_MAX = 256;
/** Owns transport-observed delivery and run facts for one client. */
export class ClientRunLedger {
private chats = new Map<string, ChatRecord>();
-2
View File
@@ -1,4 +1,3 @@
/** Compact token counts for dense runtime metadata (for example, 74.9K). */
export function formatCompactTokenCount(value: number): string {
if (value < 1_000) return Math.round(value).toLocaleString();
if (value < 1_000_000) {
@@ -52,7 +51,6 @@ function isLowInformationTitlePreview(text: string): boolean {
);
}
/** Truncate the first user message into a chat title. */
export function deriveTitle(preview: string | undefined, fallback: string): string {
if (!preview) return fallback;
const oneLine = visibleSessionPreview(preview).replace(/\s+/g, " ").trim();
+2 -6
View File
@@ -38,7 +38,6 @@ function bootWorker(): Worker | null {
entry.resolve(ev.data);
});
worker.addEventListener("error", (ev) => {
// Cancel every in-flight request on a Worker crash.
for (const [, entry] of pending) {
entry.reject(new Error(`image encoder worker error: ${ev.message}`));
}
@@ -54,21 +53,18 @@ function bootWorker(): Worker | null {
}
function newId(): string {
// ``crypto.randomUUID`` is widely available; fall back to Math.random if not.
if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
return (crypto as Crypto).randomUUID();
}
return `img-${Date.now()}-${Math.random().toString(36).slice(2)}`;
}
/** Encode ``file`` off the main thread when possible. Always resolves — errors
* are returned as ``{ok: false, reason}`` — so callers can render inline
* validation without wrapping in try/catch. */
/** Encode off the main thread when possible. Validation and encoding failures
* return ``{ok: false, reason}``; Worker and message-transport failures reject. */
export async function encodeImage(file: File): Promise<EncodeResponse> {
const id = newId();
const w = bootWorker();
if (!w) {
// Inline fallback: same logic, just on the main thread.
return encodeImageInWorker({ id, file });
}
return new Promise<EncodeResponse>((resolve, reject) => {
-11
View File
@@ -57,7 +57,6 @@ function wsInboundDebugEnabled(): boolean {
}
}
/** Shorten streaming text fields so logging stays usable for huge deltas. */
function summarizeInboundWsPayload(ev: InboundEvent): unknown {
const kind = (ev as { event?: string }).event;
if (kind === "ready") return { ...ev, upload: "[redacted]" };
@@ -168,9 +167,7 @@ export interface NanobotClientOptions {
maxFrameBytes?: number;
/** Called when a connection drops so the app can refresh its token. */
onReauth?: () => Promise<string | null>;
/** Inject a custom WebSocket factory (used by unit tests). */
socketFactory?: (url: string) => WebSocket;
/** Delay-cap for reconnect backoff (ms). */
maxBackoffMs?: number;
}
@@ -246,20 +243,17 @@ export class NanobotClient {
/** Inbound frames received while the transcript owner is absent, regardless of observers. */
private pendingInboundByChat = new Map<string, InboundEvent[]>();
private static readonly PENDING_INBOUND_MAX = 2000;
// chat_ids we've attached to since connect; re-attached after reconnects
private knownChats = new Set<string>();
/** Temporary chats are connection-owned and intentionally not reattached. */
private temporaryChatIds = new Set<string>();
private readonly runs = new ClientRunLedger();
/** Last tracked application frame written, for conservative transport-error attribution. */
private lastSocketMessageSend: { chatId: string; turnId: string } | null = null;
/** Latest ``goal_state`` snapshot per ``chat_id`` (multi-session isolation). */
private goalStateByChatId = new Map<string, GoalStateWsPayload>();
private pendingNewChat: PendingChatRequest | null = null;
private pendingTranscriptions = new Map<string, PendingRequest<string>>();
private pendingSystemCommands = new Map<string, PendingRequest<void>>();
private pendingWebUIRequests = new Map<string, PendingWebUIRequest>();
// Frames queued while the socket is not yet OPEN
private sendQueue: Outbound[] = [];
private reconnectAttempts = 0;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
@@ -353,7 +347,6 @@ export class NanobotClient {
return () => { this.taskNoticeHandlers.delete(handler); };
}
/** Subscribe to transport-level faults (see :type:`StreamError`). */
onError(handler: ErrorHandler): Unsubscribe {
this.errorHandlers.add(handler);
return () => {
@@ -872,7 +865,6 @@ export class NanobotClient {
return this.requestMutation<SidebarStatePayload>("sidebar.update", { state });
}
// -- internals ---------------------------------------------------------
private setStatus(status: ConnectionStatus): void {
if (this.status_ === status) return;
@@ -883,14 +875,12 @@ export class NanobotClient {
private handleOpen(): void {
this.setStatus("open");
this.reconnectAttempts = 0;
// Re-attach every known chat_id so deliveries continue routing after a drop.
for (const chatId of this.knownChats) {
this.rawSend({ type: "attach", chat_id: chatId });
}
for (const pending of this.pendingWebUIRequests.values()) {
this.rawSendSerialized(pending.serializedFrame);
}
// Flush anything queued during reconnect.
const queued = this.sendQueue.splice(0);
for (const frame of queued) this.rawSend(frame);
}
@@ -1257,7 +1247,6 @@ export class NanobotClient {
private scheduleReconnect(): void {
this.setStatus("reconnecting");
const attempt = this.reconnectAttempts++;
// Exponential backoff: 0.5s, 1s, 2s, 4s, capped.
const delay = Math.min(500 * 2 ** attempt, this.maxBackoffMs);
this.reconnectTimer = setTimeout(async () => {
this.reconnectTimer = null;
+1 -1
View File
@@ -25,7 +25,7 @@ export function parseSSHAddress(input: string): SSHAddress {
if (!match) throw invalid();
words.push(match[1] ?? match[2] ?? match[3]);
}
words.shift(); // ssh
words.shift();
const result: SSHAddress = { host: "" };
const seen = new Set<string>();
let user = "";
@@ -44,7 +44,6 @@ export function scrubSubagentAnnounceBody(
return header || body || stripped;
}
/** Apply scrub to assistant rows that look like subagent inject announcements. */
export function scrubSubagentUiMessages(messages: UIMessage[]): UIMessage[] {
return messages.map((m) => {
if (m.role !== "assistant" || m.renderAs === "text" || typeof m.content !== "string") {
-1
View File
@@ -42,7 +42,6 @@ export function isSubagentTask(value: unknown): value is SubagentTaskSnapshot {
&& (value.usage === null || (isRecord(value.usage) && Object.values(value.usage).every((entry) => entry === null || typeof entry === "string" || (typeof entry === "number" && Number.isFinite(entry)))));
}
/** Merge observations from initial reads, live events and control replies. */
export function mergeSubagentTasks(
current: ObservedSubagentTask[], incoming: SubagentTaskSnapshot[],
): ObservedSubagentTask[] {
-5
View File
@@ -104,10 +104,6 @@ function findStreamingAssistantIndex(
return null;
}
/**
* Find the most recent assistant placeholder that an incoming answer
* delta should adopt instead of spawning a parallel row.
*/
function findActiveAssistantPlaceholderIndex(
prev: UIMessage[],
turn: UIMessageTurnFields = {},
@@ -848,7 +844,6 @@ function projectFileEdits(
options.effects?.bodyWrites.add(id);
}
/** Canonical UI-message reducer shared by WebSocket delivery and transcript replay. */
export function projectThreadEvent(
previous: ThreadProjectionState,
event: ThreadProjectionEvent,
-7
View File
@@ -128,7 +128,6 @@ export interface UIMessage {
toolEvents?: ToolProgressEvent[];
/** Oversized persisted trace content that can be fetched when activity is expanded. */
traceDetail?: UITraceDetail;
/** Activity rows: explicit file edits emitted by edit tools. */
fileEdits?: UIFileEdit[];
/** Activity rows created during the same agent phase share one collapsible block. */
activitySegmentId?: string;
@@ -141,7 +140,6 @@ export interface UIMessage {
compactReply?: "empty" | "failed";
/** User turn: optimistic blob URLs for preview. Replay: placeholder chips. */
images?: UIImage[];
/** Signed or local UI-renderable media attachments. */
media?: UIMediaAttachment[];
/** App-specific CLI adapters explicitly attached to this user turn. */
cliApps?: UICliAppAttachment[];
@@ -153,8 +151,6 @@ export interface UIMessage {
* incrementally from ``reasoning_delta`` frames; finalized when
* ``reasoning_end`` arrives. */
reasoning?: string;
/** True while ``reasoning_delta`` frames are still arriving for this turn.
* Drives the shimmer header on ``ReasoningBubble``. */
reasoningStreaming?: boolean;
/** End-to-end wall time for this assistant turn (persisted ``latency_ms`` / ``turn_end``). */
latencyMs?: number;
@@ -181,7 +177,6 @@ export interface UIMessage {
reasoningStreamId?: string;
/** Ephemeral delivery lifecycle for optimistic user messages. */
deliveryStatus?: MessageDeliveryStatus;
/** Structured rejection reason shown with a failed optimistic message. */
deliveryErrorKind?: MessageDeliveryErrorKind;
}
@@ -394,7 +389,6 @@ interface AgentUIBlob {
data?: unknown;
}
/** WebSocket snapshot for sustained goals (`goal_state` events; keyed by ``chat_id``). */
export interface GoalStateWsPayload {
active: boolean;
status?: "active" | "blocked";
@@ -1706,7 +1700,6 @@ export interface OutboundMcpPresetMention {
brand_color?: string | null;
}
/** Response shape for ``GET .../webui-thread`` (server-built transcript replay). */
interface WebuiThreadPagePayload {
before_cursor?: string | null;
has_more_before?: boolean;
-1
View File
@@ -1134,7 +1134,6 @@ describe("App layout", () => {
window.history.replaceState(null, "", "/#/chat/websocket%3Aexisting-chat");
render(<App />);
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
// Wait for the existing chat's lazy composer before opening its sidebar menu.
await screen.findByRole("button", { name: "Workspace access mode: Full Access" });
const projectSection = screen.getByRole("region", { name: "selected-project" });
fireEvent.contextMenu(within(projectSection).getByRole("button", { name: "selected-project" }));
-2
View File
@@ -1563,8 +1563,6 @@ describe("ChatList", () => {
const allRegions = screen.getAllByRole("region");
const regionNames = allRegions.map((r) => r.getAttribute("aria-label") ?? r.textContent);
// The most recently updated conversation ("Recent chat" at 12:00) must be
// in the first group — Topics should come before both projects.
const chatsIdx = regionNames.findIndex((n) => n?.includes("Topics"));
const projAIdx = regionNames.findIndex((n) => n?.includes("project-a"));
const projBIdx = regionNames.findIndex((n) => n?.includes("project-b"));
@@ -122,8 +122,8 @@ describe("Mobile context usage sheet", () => {
});
it.each([
[100, 500], // Deliberate pull.
[32, 40], // Short, quick downward flick.
[100, 500],
[32, 40],
])("dismisses after dragging %dpx in %dms and opens at the original position", async (distance, duration) => {
const { user, handle, sheet, trigger } = await openSheet();
pointer(handle, "pointerDown", { y: 400 });
@@ -155,7 +155,6 @@ describe("Mobile context usage sheet", () => {
expect(sheet.style.transition).toBe("");
fireEvent.click(handle, { detail: 1 });
expect(screen.getByRole("dialog")).toBeVisible();
// A real subsequent tap must still close the sheet.
await user.click(handle);
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(document.body).not.toHaveStyle({ pointerEvents: "none" });
@@ -83,7 +83,6 @@ describe("host compatibility facts", () => {
]);
const values = within(dialog).getAllByRole("definition");
expect(values.map((value) => value.textContent)).toEqual([version, version]);
// Read-only facts must not inherit the settings controls' 60px row floor.
expect(dialog.querySelector(".settings-list-row")).toBeNull();
expect(dialog.querySelector(".break-all, .truncate")).toBeNull();
expect(within(dialog).getByRole("status")).toHaveTextContent(i18n.t("remote.compatibility.compatibleHint"));
+1 -1
View File
@@ -195,7 +195,7 @@ describe("host session lifecycle", () => {
act(() => result.current.loaded(ids[0]));
expect(result.current.selected).toBeNull();
expect(result.current.frames).toHaveLength(0);
expect(vi.getTimerCount()).toBe(1); // health interval only
expect(vi.getTimerCount()).toBe(1);
});
it("a timed-out cold page leaves the old host intact and can be retried", async () => {
@@ -10,7 +10,6 @@ vi.mock("@/lib/bootstrap", async (original) => ({
fetchBootstrap: vi.fn(async () => ({ token: "test", api_token: "test", ws_path: "/" })),
deriveWsUrl: () => "ws://test",
}));
// Keep this suite focused on App's remote boundary rather than the chat implementation.
vi.mock("@/components/thread/ThreadShell", () => ({
ThreadShell: () => <textarea aria-label="Local draft" />,
}));
@@ -6,7 +6,6 @@ import { linearWorkspaceStore } from "../../../nanobot/channels/linear/webui/wor
const installation = { organization_id: "org-1", organization_name: "nanobot" };
const logo = "https://public.linear.app/org-1/logo";
function fixture() {
// Keep the real generic transport type; this client is never connected.
const client = new NanobotClient({ url: "ws://preview.invalid", reconnect: false });
const requestMutation = vi.spyOn(client, "requestMutation").mockImplementation(async (_action, params) =>
params?.operation === "inspect"
-15
View File
@@ -3,11 +3,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { NanobotClient } from "@/lib/nanobot-client";
import type { SidebarStatePayload } from "@/lib/types";
/**
* Minimal fake WebSocket implementing the subset NanobotClient touches.
* Every instance is retrievable via ``FakeSocket.instances`` so tests can
* drive open/close/message lifecycles deterministically.
*/
class FakeSocket {
static instances: FakeSocket[] = [];
static readonly CONNECTING = 0;
@@ -37,8 +32,6 @@ class FakeSocket {
this.onclose?.();
}
/** Simulate a server-initiated drop with a specific wire-level close code
* (e.g. ``1009`` for Message Too Big). */
fakeCloseWithCode(code: number) {
this.readyState = FakeSocket.CLOSED;
this.onclose?.({ code });
@@ -2433,9 +2426,7 @@ describe("NanobotClient", () => {
expect(lastSocket().sent).toContain(
JSON.stringify({ type: "attach", chat_id: "chat-z" }),
);
// Drop the socket.
lastSocket().close();
// Advance the backoff timer.
await vi.advanceTimersByTimeAsync(20);
const reconnected = lastSocket();
expect(reconnected).not.toBe(FakeSocket.instances[0]);
@@ -2471,10 +2462,8 @@ describe("NanobotClient", () => {
client.connect();
lastSocket().fakeOpen();
client.close();
// Advance past any possible backoff window to prove no reconnect was scheduled.
await vi.advanceTimersByTimeAsync(200);
expect(FakeSocket.instances).toHaveLength(1);
// "reconnecting" must never appear after an intentional close.
expect(seen).not.toContain("reconnecting");
expect(seen.at(-1)).toBe("closed");
});
@@ -2529,7 +2518,6 @@ describe("NanobotClient", () => {
client.onError((e) => errors.push(e));
client.connect();
lastSocket().fakeOpen();
// Server rejected an outbound frame as too large.
lastSocket().fakeCloseWithCode(1009);
expect(errors).toEqual([{ kind: "message_too_big" }]);
});
@@ -2587,7 +2575,6 @@ describe("NanobotClient", () => {
maxBackoffMs: 5,
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
});
// First handler explodes; subsequent reconnect state must be untouched.
client.onError(() => {
throw new Error("subscriber blew up");
});
@@ -2596,7 +2583,6 @@ describe("NanobotClient", () => {
client.connect();
lastSocket().fakeOpen();
lastSocket().fakeCloseWithCode(1009);
// Despite the throwing handler, the client must still schedule a reconnect.
expect(seenStatuses).toContain("reconnecting");
await vi.advanceTimersByTimeAsync(20);
expect(FakeSocket.instances.length).toBeGreaterThan(1);
@@ -2627,7 +2613,6 @@ describe("NanobotClient", () => {
client.onStatus((s) => seen.push(s));
client.connect();
lastSocket().fakeOpen();
// Simulate the remote side hanging up (no client.close() call).
lastSocket().close();
await vi.advanceTimersByTimeAsync(50);
expect(seen).toContain("reconnecting");
@@ -205,7 +205,6 @@ describe("settings edit completion", () => {
});
});
// Exercise the real controller and portaled editor, not only the completion primitive.
describe("model editor completion boundaries", () => {
installSettingsViewTestHooks();
@@ -118,7 +118,6 @@ describe("useSkills", () => {
fireEvent.keyDown(input, { key: "Tab" });
expect(input).toHaveValue("$simple-pr-review ");
// A later open must also refresh removals without remounting the page.
vi.mocked(fetchSkills).mockResolvedValue({ skills: [] });
fireEvent.change(input, { target: { value: "$", selectionStart: 1 } });
await act(async () => {});
-1
View File
@@ -1,7 +1,6 @@
import { NanobotClient } from "@/lib/nanobot-client";
import type { InboundEvent } from "@/lib/types";
/** Real lifecycle and dispatch with an in-memory transport. */
export function createStreamClient() {
const socket = {
readyState: 1,
-6
View File
@@ -11,7 +11,6 @@ const CACHE_NAME = "nanobot-static-v2";
const ICON_CACHE_NAME = "nanobot-icons-v1";
const ICON_CACHE_LIMIT = 128;
/** Minimal Cache-compatible in-memory store with SW-style URL normalization. */
class FakeCacheStore {
entries = new Map<string, Response>();
@@ -287,7 +286,6 @@ describe("service worker", () => {
it("removes stale cache names and prunes unreferenced static entries on activate", async () => {
const sw = loadSw();
await sw.fire("install");
// Simulate the latest loaded build: index.html references only v2 assets.
await sw.store.put(`${ORIGIN}/`, indexHtml(["/assets/index-v2.js", "/assets/index-v2.css"]));
await sw.store.put(`${ORIGIN}/assets/index-v2.js`, new Response("v2"));
await sw.store.put(`${ORIGIN}/assets/index-v2.css`, new Response("v2 css"));
@@ -508,11 +506,9 @@ describe("service worker", () => {
it("serves navigation network-first, prunes on shell refresh, and falls back when offline", async () => {
const sw = loadSw();
await sw.store.put(`${ORIGIN}/`, indexHtml(["/assets/index-v2.js"]));
// Assets from an older build, still referenced by the cached v2 shell.
await sw.store.put(`${ORIGIN}/assets/index-v2.js`, new Response("v2"));
await sw.store.put(`${ORIGIN}/assets/index-v1.js`, new Response("v1"));
// Offline: network rejects, cached shell is returned.
sw.fetchMock.mockRejectedValue(new TypeError("Failed to fetch"));
const offlineEvent = {
request: new Request(`${ORIGIN}/`),
@@ -522,8 +518,6 @@ describe("service worker", () => {
const offlineResponse = (await offlineEvent.respondWith.mock.calls[0][0]) as Response;
expect(await offlineResponse.text()).toContain("assets/index-v2.js");
// Online: network response wins, refreshes the cached shell, and prunes
// entries the new index.html no longer references.
const freshShell = indexHtml(["/assets/index-v3.js"]);
sw.fetchMock.mockImplementation((input: Request | string) => {
const url = new URL(typeof input === "string" ? input : input.url, ORIGIN);
@@ -21,7 +21,6 @@ vi.mock("@/lib/bootstrap", async (importOriginal) => ({
deriveWsUrl: () => "ws://test",
}));
// Only the network is fake: App, the workbench, stream hook and multiplexed client are real.
class TestSocket {
static current: TestSocket;
readyState = 0;
-3
View File
@@ -2833,7 +2833,6 @@ describe("ThreadComposer", () => {
expect(screen.queryByText("MCP servers")).not.toBeInTheDocument();
const gimp = screen.getByRole("option", { name: /@gimp GIMP .* CLI/i });
const browserbase = screen.getByRole("option", { name: /@browserbase Browserbase .* MCP/i });
// Reuse the app's 44px coarse-pointer targets without changing desktop density.
expect(gimp).toHaveClass("touch-target");
expect(browserbase).toHaveClass("touch-target");
expect(within(gimp).getByText("CLI")).toBeInTheDocument();
@@ -3214,7 +3213,6 @@ describe("ThreadComposer", () => {
expect(palette).toHaveStyle({ maxHeight: "84px" });
expect(input.closest("form")).toHaveAttribute("data-palette-beside", "true");
// Rotation restores the ordinary floating menu, without changing the draft.
landscape = false;
document.getElementById("root")!.classList.remove("short-visual-viewport");
Object.assign(window.visualViewport!, { height: 396, offsetTop: 350 });
@@ -3620,7 +3618,6 @@ describe("ThreadComposer", () => {
const keyEvent = createEvent.keyDown(input, { key: "Enter" });
fireEvent(input, keyEvent);
// Enter inserts a newline on touch; the send button is the interject path.
expect(keyEvent.defaultPrevented).toBe(false);
expect(onSend).not.toHaveBeenCalled();
expect(screen.getByRole("button", { name: "Send message" })).toBeInTheDocument();
-2
View File
@@ -1555,7 +1555,6 @@ describe("ThreadShell", () => {
expect(client.sendSystemCommand).not.toHaveBeenCalled();
emit("notice-a", true);
expect(notice()).not.toBeInTheDocument();
// A new turn can notify again; it does not inherit the previous dismissal.
emit("notice-a", false);
emit("notice-a", true);
expect(notice()).toBeVisible();
@@ -5157,7 +5156,6 @@ describe("ThreadShell", () => {
),
);
// No banner yet: only appears once the client emits a matching error.
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
await act(async () => {});
@@ -554,7 +554,6 @@ describe("Workspace project picker", () => {
await waitFor(() => expect(input).toHaveValue("/srv/alpha/"));
expect(screen.getAllByRole("listbox")).toHaveLength(1);
await screen.findByRole("option", { name: "/srv/alpha/docs" });
// Once the address is complete, Tab leaves the input instead of entering docs.
await user.tab();
expect(input).not.toHaveFocus();
expect(input).toHaveValue("/srv/alpha/");
+5 -22
View File
@@ -1,22 +1,11 @@
/**
* Off-main-thread image encoder.
*
* Accepts a ``File``, validates it via magic bytes (ignoring the extension to
* defeat rename-based spoofs), and either passes through or *normalizes* the
* bytes so the resulting base64 data URL stays ≤ ``TARGET_MAX_BYTES``. The
* normalization path uses ``createImageBitmap`` + ``OffscreenCanvas`` so the
* full decode/resize/re-encode cycle never blocks the UI thread.
*
* Output contract:
* ``{ok: true, dataUrl, bytes, normalized}`` on success, or
* ``{ok: false, reason}`` for every recoverable failure — magic-bytes
* mismatch, unsupported MIME, decode error, or a post-normalization payload
* that *still* exceeds the budget (extreme aspect ratios).
* Validate image bytes independently of filenames and normalize to TARGET_MAX_BYTES
* before base64 encoding. Used by the Worker and the main-thread fallback.
* Returns {ok: true, dataUrl, bytes, normalized} or {ok: false, reason}.
*/
/// <reference lib="webworker" />
// --- Types -------------------------------------------------------------------
export type EncodeInput = {
id: string;
@@ -45,11 +34,8 @@ export type EncodeFailure = {
export type EncodeResponse = EncodeSuccess | EncodeFailure;
// --- Budgets -----------------------------------------------------------------
/** Upper bound for the final base64-decoded payload. Matches the server-side
* safeguard (8 MB) minus safety margin; anything this function yields should
* safely pass ``_MAX_IMAGE_BYTES`` on the server. */
/** Encoded image byte budget before base64; the server's supplied ingress limits still apply. */
export const TARGET_MAX_BYTES = 6 * 1024 * 1024;
/** Long-edge pixel cap when we resize a large image. 2048 keeps retina UIs
@@ -72,7 +58,6 @@ const SUPPORTED_MIMES = new Set([
"image/gif",
]);
// --- Magic bytes -------------------------------------------------------------
/** Sniff the first 12 bytes; returns the canonical MIME or ``null``.
*
@@ -116,10 +101,9 @@ export function sniffImageMime(bytes: Uint8Array): string | null {
return null;
}
// --- Encoder -----------------------------------------------------------------
function bufferToBase64(buf: ArrayBuffer): string {
// ``btoa`` can't take large strings — chunk through 32 KB windows.
// Bound fromCharCode's argument list to avoid engine argument-count limits.
const bytes = new Uint8Array(buf);
let binary = "";
const CHUNK = 0x8000;
@@ -150,7 +134,6 @@ async function normalize(
file: File,
sourceMime: string,
): Promise<{ dataUrl: string; bytes: number } | { error: EncodeFailure["reason"] }> {
// Re-encode paths: JPEG/WebP → WebP q=0.85; PNG/GIF → PNG (keep crisp).
const targetMime = NORMALIZE_LOSSY_MIMES.has(sourceMime)
? "image/webp"
: "image/png";