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

-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;