Files
plugins/packages/agent-console/daemon/src/store/settings.ts
T
qingnian108 5703c9f18a agent-console 1.3: reviewed features from #727 and timeline polish (#733)
This carries #727's reviewed part forward, without auto-approve (that comes as its own PR). Permission behaviour is the same as 1.2.

- Windows Git Bash detection, never the WSL System32 bash. It can be overridden in Settings and is passed per spawn only.
- GBK / system code page decoding of raw process output.
- Folded tool steps that don't wrap at ~600px.
- Select-to-quote, and copy/edit under the user bubble.
- Instant send with the echo replacing the bubble in place, and retry when a send fails.
- `/app` heals itself after sleep/wake. `frame-ancestors` is limited to loopback and Magpie's window.
- Grayscale timeline polish: one-line tool rows, a task-list pill, a reply footer and code blocks.
- Test fixes:
  - The `initializing` push is awaited.
  - `afterEach` waits for the thread store's writes.
  - `runtimeInfo().starting` is exposed, and the steer test waits on it.
  - "idle recycling" waits for closed.

Run on mote (macOS) at 65ab7c94:
- `npm ci`, `npm run check` and `build` are ok; `verify:build` gives 5/5 OK.
- Full `vitest run` x5: 4 green (427 passed). One red, "send while running → queued", is a race that is on main too.
  - Cause: `setStatus(idle)` runs before `queue.shift()`.
  - A 300ms pause injected there makes it red 3/3 on main and on this head.
  - Filed on #585 with the cause and the repro.
- Focused send-latency + manager runs: 12/12. `e2e:v1`: 25/25, with no pageerror or console error.
- Broken by hand:
  - With the old steer wait and the mock send held 400ms, the test is red 3/3; the new wait passes 3/3.
  - With `recycleIdle` made a no-op, "idle recycling" goes red.
- Playwright render:
  - Chromium and WebKit × zh/en × light/dark × 1280/420.
  - No gradients, no coloured left borders, no `<select>`, no page errors.
  - At 420 the page scrolls sideways (scrollWidth 480), the same as main.

Not tried: Windows (Git Bash detection, GBK decoding) and a real agent, rather than the mock.
2026-11-05 11:08:38 +08:00

155 lines
5.9 KiB
TypeScript

// settings.json: defaults per EXEC §5.6; unknown fields are preserved on read.
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { z } from "zod";
import { writeJsonAtomic } from "../util/atomic.js";
export type Settings = {
defaultProvider: string;
defaultMode: "plan" | "default" | "acceptEdits" | "bypassPermissions" | "ask";
sendKey: "enter" | "ctrlEnter";
runningSend: "queue" | "steer";
showThinking: boolean;
theme: "auto" | "light" | "dark";
/** 1.2: width of the conversation column */
contentWidth: ContentWidth;
/** 1.2: chat text size in px (timeline, composer; code 1px smaller) */
chatFontSize: number;
idleCloseMinutes: number;
collapsedProjects: string[];
panel: { open: boolean; tab: string; width: number };
sidebarWidth: number;
/** 1.2: the sidebar column is collapsed (wide windows) */
sidebarHidden?: boolean;
lastProjectId: string | null;
lastThreadId: string | null;
recentDirs?: string[];
v1Migrated?: boolean;
/** false = turned off by the user in settings; absent means on */
providerEnabled?: Record<string, boolean>;
/** Advanced: override how a Provider is launched (executable + args array, no shell) */
providerCommand?: Record<string, { executable?: string; args?: string[] }>;
/** 1.3 (Windows): bash.exe the agents use; empty = detect Git Bash */
bashPath?: string;
[k: string]: unknown;
};
export const CONTENT_WIDTHS = ["narrow", "default", "wide", "full"] as const;
export type ContentWidth = (typeof CONTENT_WIDTHS)[number];
export const CHAT_FONT_MIN = 12;
export const CHAT_FONT_MAX = 18;
export const CHAT_FONT_DEFAULT = 13;
export const DEFAULT_SETTINGS: Settings = {
defaultProvider: "claude",
defaultMode: "default",
sendKey: "enter",
runningSend: "queue",
showThinking: true,
theme: "auto",
contentWidth: "default",
chatFontSize: CHAT_FONT_DEFAULT,
idleCloseMinutes: 30,
collapsedProjects: [],
panel: { open: false, tab: "changes", width: 440 },
sidebarWidth: 248,
lastProjectId: null,
lastThreadId: null,
recentDirs: [],
};
export const IDLE_CLOSE_MIN = 5;
export const IDLE_CLOSE_MAX = 240;
const mode = z.enum(["plan", "default", "acceptEdits", "bypassPermissions", "ask"]);
const id = z.string().min(1).max(200);
/** B18: what settings.set accepts. Every key the UI writes is listed; anything else or a wrong type is refused. */
export const settingsPatchSchema = z
.object({
defaultProvider: z.string().min(1).max(64),
defaultMode: mode,
sendKey: z.enum(["enter", "ctrlEnter"]),
runningSend: z.enum(["queue", "steer"]),
showThinking: z.boolean(),
// auto = follow the host: Magpie's light/dark inside Magpie, the OS outside it
theme: z.enum(["auto", "light", "dark"]),
contentWidth: z.enum(CONTENT_WIDTHS),
chatFontSize: z.number().int().min(CHAT_FONT_MIN).max(CHAT_FONT_MAX),
idleCloseMinutes: z.number().int().min(IDLE_CLOSE_MIN).max(IDLE_CLOSE_MAX),
collapsedProjects: z.array(id).max(1000),
panel: z.object({ open: z.boolean(), tab: z.string().max(40), width: z.number().min(0).max(5000) }).partial(),
sidebarWidth: z.number().min(0).max(5000),
sidebarHidden: z.boolean(),
lastProjectId: id.nullable(),
lastThreadId: id.nullable(),
recentDirs: z.array(z.string().max(4096)).max(50),
providerEnabled: z.record(z.string().max(64), z.boolean()),
providerCommand: z.record(
z.string().max(64),
z.object({ executable: z.string().max(4096).optional(), args: z.array(z.string().max(4096)).max(64).optional() }).strict(),
),
v1Migrated: z.boolean(),
bashPath: z.string().max(1024),
})
.partial()
.strict();
export type SettingsPatch = z.infer<typeof settingsPatchSchema>;
/** Validate a patch from the page; returns the parsed patch or a readable error. */
export function parseSettingsPatch(patch: unknown): { ok: true; patch: SettingsPatch } | { ok: false; error: string } {
const r = settingsPatchSchema.safeParse(patch);
if (r.success) return { ok: true, patch: r.data };
return {
ok: false,
error: r.error.issues.map((i) => `${i.path.join(".") || "(patch)"}: ${i.message}`).join("; "),
};
}
/** Values in settings.json that have the wrong type (hand edits, older builds) fall back to the default; unknown keys are kept. */
export function sanitizeStored(raw: Record<string, unknown>): Record<string, unknown> {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
const shape = settingsPatchSchema.shape as Record<string, z.ZodType>;
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(raw)) {
const field = shape[k];
if (field && k !== "idleCloseMinutes" && !field.safeParse(v).success) continue;
if (k === "idleCloseMinutes") {
const n = Number(v);
if (!Number.isFinite(n)) continue;
out[k] = Math.min(IDLE_CLOSE_MAX, Math.max(IDLE_CLOSE_MIN, Math.round(n)));
continue;
}
out[k] = v;
}
return out;
}
export class SettingsStore {
private file: string;
private cache: Settings | null = null;
private writing: Promise<void> = Promise.resolve();
constructor(dataDir: string) {
this.file = join(dataDir, "settings.json");
}
async get(): Promise<Settings> {
if (this.cache) return this.cache;
let raw: Record<string, unknown> = {};
try {
raw = JSON.parse(await readFile(this.file, "utf8"));
} catch {}
raw = sanitizeStored(raw);
this.cache = { ...DEFAULT_SETTINGS, ...raw, panel: { ...DEFAULT_SETTINGS.panel, ...(raw.panel as object | undefined) } };
return this.cache;
}
async set(patch: Partial<Settings>): Promise<Settings> {
const cur = await this.get();
const next = { ...cur, ...patch, panel: { ...cur.panel, ...(patch.panel as object | undefined) } };
this.cache = next;
const snap = next;
this.writing = this.writing.then(() => writeJsonAtomic(this.file, snap));
await this.writing;
return next;
}
}