Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(settings): account icon picker, nightly auto-update, stable channel (#139)
Abdurrahman Fakhrulf1f69608ac0a
diff --git a/.env.example b/.env.exampleindex 6900e216..a041be68 100644--- a/.env.example+++ b/.env.example@@ -55,6 +55,14 @@ OS_SESSION_SECRET=# moving; it is here because the updater runs as a transient systemd unit and the# path is passed to it explicitly rather than inherited.# MSO_UPDATE_LOG=~/.mso/self-update.log+# Where the unattended updater records its last attempt and failure streak. Written by+# the nightly timer, read by Settings → Update MSO; never set by a client. Delete it to+# clear a pause after two failed builds (or run `mso update`, which does that for you).+# MSO_AUTO_UPDATE_STATE=~/.mso/auto-update-state.json+# Directory the nightly update timer units are written to. Defaults to+# $XDG_CONFIG_HOME/systemd/user (or ~/.config/systemd/user). Override only in tests or+# on a host whose user manager reads units from a non-standard path.+# MSO_SYSTEMD_USER_DIR=~/.config/systemd/user# Optional advanced SSH transport override for custom/private Git origins. Canonical# MSO origins are normalized to public HTTPS, so ordinary installs should leave this# unset. When unset, MSO update paths use `ssh -oBatchMode=yes` for non-interactivediff --git a/app/api/auth/account/icon/route.test.ts b/app/api/auth/account/icon/route.test.tsnew file mode 100644index 00000000..a6c1067c--- /dev/null+++ b/app/api/auth/account/icon/route.test.ts@@ -0,0 +1,106 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";++const state = { role: "owner" as "viewer" | "operator" | "owner" | null };+const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0]);++const mocks = vi.hoisted(() => ({+ read: vi.fn(async () => ({ name: "Owner", icon: { type: "preset", id: "user" } })),+ write: vi.fn(async () => ({ name: "Owner", icon: { type: "image", src: "data:image/webp;base64,AAAA" } })),+ audit: vi.fn(async () => {}),+ convert: vi.fn(async () => ({ webp: Buffer.from("WEBPBYTES"), png192: Buffer.alloc(0), png512: Buffer.alloc(0), apple180: Buffer.alloc(0), ico: Buffer.alloc(0) })),+ iconPng: vi.fn(async () => Buffer.from([0x89, 0x50, 0x4e, 0x47])),+}));++vi.mock("@/lib/auth/require-session", () => ({+ getSessionContext: vi.fn(async () => state.role ? ({+ session: { device_id: "b".repeat(32), issued_at: 1, expires_at: 2, cookie_scope: "host", cookie_epoch: "epoch-0000000000000000" },+ device: { label: "current", approvedAt: 1, role: state.role },+ role: state.role,+ }) : null),+}));+vi.mock("@/lib/auth/account-profile", () => ({+ readAccountProfile: mocks.read,+ writeAccountProfile: mocks.write,+ AccountProfileError: class AccountProfileError extends Error {+ code: string;+ constructor(code: string) { super(code); this.code = code; }+ },+}));+vi.mock("@/lib/auth/account-icon-image", async (importOriginal) => {+ const original = await importOriginal() as typeof import("@/lib/auth/account-icon-image");+ return {+ ...original,+ convertAccountIcon: mocks.convert,+ accountIconPng: mocks.iconPng,+ };+});+vi.mock("@/lib/host/audit-api", () => ({ audit: mocks.audit }));++const post = (body: Buffer | string, type = "image/png") => new NextRequest("https://mso.example/api/auth/account/icon", {+ method: "POST",+ headers: { "content-type": type },+ body: typeof body === "string" ? body : new Uint8Array(body),+});++beforeEach(() => {+ state.role = "owner";+ for (const fn of Object.values(mocks)) fn.mockClear();+});++describe("account icon route", () => {+ it("lets only an owner upload, and stores the converted WebP, not the upload", async () => {+ const { POST } = await import("./route");+ state.role = "viewer";+ expect((await POST(post(png))).status).toBe(403);+ state.role = null;+ expect((await POST(post(png))).status).toBe(403);+ expect(mocks.write).not.toHaveBeenCalled();++ state.role = "owner";+ const response = await POST(post(png));+ expect(response.status).toBe(200);+ expect(mocks.convert).toHaveBeenCalledWith(png, "image/png");+ expect(mocks.write).toHaveBeenCalledWith({ icon: { type: "image", src: `data:image/webp;base64,${Buffer.from("WEBPBYTES").toString("base64")}` } });+ expect(mocks.audit).toHaveBeenCalledWith(expect.objectContaining({ action: "auth.account", detail: "icon:upload" }));+ // The audit trail must never carry the image bytes.+ expect(JSON.stringify(mocks.audit.mock.calls)).not.toContain(Buffer.from("WEBPBYTES").toString("base64"));+ });++ it("rejects a body over the 8 MiB cap by counting bytes, not by trusting content-length", async () => {+ const { POST } = await import("./route");+ const { MAX_INPUT_BYTES } = await import("@/lib/auth/account-icon-image");+ const oversized = Buffer.alloc(MAX_INPUT_BYTES + 16);+ // No content-length header is set by NextRequest for this stream, so only the+ // reader loop can catch it.+ const response = await POST(post(oversized));+ expect(response.status).toBe(413);+ expect(await response.json()).toEqual({ error: "too_large" });+ expect(mocks.convert).not.toHaveBeenCalled();+ expect(mocks.write).not.toHaveBeenCalled();+ });++ it("maps conversion failures to a status the client can explain", async () => {+ const { POST } = await import("./route");+ const { AccountIconError } = await import("@/lib/auth/account-icon-image");+ mocks.convert.mockRejectedValueOnce(new AccountIconError("unsupported_type"));+ expect((await POST(post(png, "text/plain"))).status).toBe(415);+ mocks.convert.mockRejectedValueOnce(new AccountIconError("too_many_pixels"));+ expect((await POST(post(png))).status).toBe(422);+ mocks.convert.mockRejectedValueOnce(new Error("unexpected"));+ expect((await POST(post(png))).status).toBe(400);+ });++ it("serves the stored icon publicly, without a session, and 404s for the demo", async () => {+ const { GET } = await import("./route");+ state.role = null;+ const response = await GET(new NextRequest("https://mso.example/api/auth/account/icon?size=192"));+ expect(response.status).toBe(200);+ expect(response.headers.get("content-type")).toBe("image/png");+ expect(response.headers.get("cache-control")).toContain("max-age=60");+ expect(mocks.read).toHaveBeenCalled();++ mocks.read.mockRejectedValueOnce(new Error("corrupt"));+ expect((await GET(new NextRequest("https://mso.example/api/auth/account/icon"))).status).toBe(404);+ });+});diff --git a/app/api/auth/account/icon/route.ts b/app/api/auth/account/icon/route.tsnew file mode 100644index 00000000..d5578a65--- /dev/null+++ b/app/api/auth/account/icon/route.ts@@ -0,0 +1,121 @@+import { NextRequest, NextResponse } from "next/server";+import { AccountProfileError, readAccountProfile, writeAccountProfile } from "@/lib/auth/account-profile";+import {+ AccountIconError,+ accountIconPng,+ buildIco,+ convertAccountIcon,+ MAX_INPUT_BYTES,+} from "@/lib/auth/account-icon-image";+import { getSessionContext } from "@/lib/auth/require-session";+import { managedAppIdForHost, isUnclaimedAppNamespaceHost } from "@/lib/managed-apps/origin";+import { audit } from "@/lib/host/audit-api";+import { IS_DEMO } from "@/lib/demo";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";++const noStore = { "Cache-Control": "no-store" };+const PUBLIC_CACHE = "public, max-age=60, stale-while-revalidate=300";+const ICO_SIZES = [16, 32, 48] as const;+const SIZES = { "32": 32, "180": 180, "192": 192, "512": 512 } as const;++/** Public by nature: this is the owner's avatar, and the browser tab fetches it+ * for a favicon before any session exists. It returns stored icon bytes only —+ * never the profile name or any other field. `?size=ico` is the multi-entry+ * favicon; the default is the 192 PNG used by the manifest. */+export async function GET(req: NextRequest) {+ const raw = req.nextUrl.searchParams.get("size") ?? "192";+ try {+ const { icon } = await readAccountProfile();+ if (raw === "ico") {+ const pngs = await Promise.all(ICO_SIZES.map((size) => accountIconPng(icon, size)));+ const ico = buildIco(ICO_SIZES.map((size, index) => ({ size, png: pngs[index]! })));+ return new NextResponse(new Uint8Array(ico), {+ headers: { "Content-Type": "image/x-icon", "Cache-Control": PUBLIC_CACHE, "X-Content-Type-Options": "nosniff" },+ });+ }+ const size = SIZES[(raw in SIZES ? raw : "192") as keyof typeof SIZES];+ const png = await accountIconPng(icon, size);+ if (!png.length) return new NextResponse(null, { status: 404, headers: noStore });+ return new NextResponse(new Uint8Array(png), {+ headers: {+ "Content-Type": "image/png",+ "Content-Length": String(png.length),+ "Cache-Control": PUBLIC_CACHE,+ "X-Content-Type-Options": "nosniff",+ },+ });+ } catch {+ return new NextResponse(null, { status: 404, headers: noStore });+ }+}++/** Read the body ourselves so the cap applies to actual bytes. A missing or+ * lying `content-length` must not let a huge stream through. */+async function readCapped(req: NextRequest): Promise<Buffer | "too_large"> {+ const declared = Number(req.headers.get("content-length") ?? "");+ if (Number.isFinite(declared) && declared > MAX_INPUT_BYTES) return "too_large";+ if (!req.body) return Buffer.alloc(0);+ const reader = req.body.getReader();+ const chunks: Uint8Array[] = [];+ let total = 0;+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ if (!value) continue;+ total += value.byteLength;+ if (total > MAX_INPUT_BYTES) {+ await reader.cancel().catch(() => undefined);+ return "too_large";+ }+ chunks.push(value);+ }+ return Buffer.concat(chunks);+}++export async function POST(req: NextRequest) {+ if (IS_DEMO) return NextResponse.json({ error: "demo" }, { status: 403, headers: noStore });+ // This path bypasses the proxy body-clone middleware so the owner can send an+ // 8 MiB image without being buffered twice. That means the two guards the proxy+ // would have applied on this path are repeated here, exactly as /fs/upload does.+ const host = req.headers.get("host") ?? new URL(req.url).host;+ if (managedAppIdForHost(host) || isUnclaimedAppNamespaceHost(host))+ return new NextResponse("Not Found", { status: 404 });+ const site = req.headers.get("sec-fetch-site");+ if (site && site !== "same-origin" && site !== "none")+ return NextResponse.json({ error: "cross_origin_blocked" }, { status: 403, headers: noStore });+ const origin = req.headers.get("origin");+ if (origin) {+ try {+ if (new URL(origin).host !== host)+ return NextResponse.json({ error: "cross_origin_blocked" }, { status: 403, headers: noStore });+ } catch {+ return NextResponse.json({ error: "cross_origin_blocked" }, { status: 403, headers: noStore });+ }+ }+ const context = await getSessionContext();+ if (!context || context.role !== "owner") {+ return NextResponse.json({ error: "owner_required" }, { status: 403, headers: noStore });+ }+ const body = await readCapped(req);+ if (body === "too_large") {+ return NextResponse.json({ error: "too_large" }, { status: 413, headers: noStore });+ }+ try {+ const converted = await convertAccountIcon(body, req.headers.get("content-type") ?? "");+ const src = `data:image/webp;base64,${converted.webp.toString("base64")}`;+ const profile = await writeAccountProfile({ icon: { type: "image", src } });+ await audit({ action: "auth.account", actor: context.session.device_id, ok: true, detail: "icon:upload" });+ return NextResponse.json(profile, { headers: noStore });+ } catch (error) {+ if (error instanceof AccountIconError) {+ const status = error.code === "too_large" ? 413 : error.code === "unsupported_type" ? 415 : 422;+ return NextResponse.json({ error: error.code }, { status, headers: noStore });+ }+ if (error instanceof AccountProfileError) {+ return NextResponse.json({ error: error.code }, { status: error.code === "corrupt" ? 500 : 400, headers: noStore });+ }+ return NextResponse.json({ error: "invalid" }, { status: 400, headers: noStore });+ }+}diff --git a/app/api/prefs/route.test.ts b/app/api/prefs/route.test.tsindex 9476bd90..2dd197f5 100644--- a/app/api/prefs/route.test.ts+++ b/app/api/prefs/route.test.ts@@ -5,14 +5,17 @@ const mocks = vi.hoisted(() => ({requireSession: vi.fn(async () => true),readPrefs: vi.fn(async () => ({ quicklinks: [] })),writePrefs: vi.fn(async () => ({ quicklinks: [], updatedAt: 1 })),+ applyAutomation: vi.fn(async () => ({ prefs: { auto: true, channel: "stable" } })),}));vi.mock("@/lib/auth/require-session", () => ({ requireSession: mocks.requireSession }));vi.mock("@/lib/prefs/store", () => ({ readPrefs: mocks.readPrefs, writePrefs: mocks.writePrefs }));+vi.mock("@/lib/host/update-automation", () => ({ applyAutomation: mocks.applyAutomation }));beforeEach(() => {mocks.requireSession.mockReset().mockResolvedValue(true);mocks.readPrefs.mockClear();mocks.writePrefs.mockClear();+ mocks.applyAutomation.mockClear();});describe("shared preferences role boundary", () => {@@ -43,5 +46,30 @@ describe("shared preferences role boundary", () => {});expect((await POST(request)).status).toBe(401);expect(mocks.writePrefs).not.toHaveBeenCalled();+ expect(mocks.applyAutomation).not.toHaveBeenCalled();+ });++ it("routes the updates section through the automation authority, not a bare file write", async () => {+ const { POST } = await import("./route");+ const request = new NextRequest("https://mso.example/api/prefs", {+ method: "POST", headers: { "content-type": "application/json" },+ body: JSON.stringify({ updates: { auto: true, channel: "main" } }),+ });+ expect((await POST(request)).status).toBe(200);+ expect(mocks.applyAutomation).toHaveBeenCalledWith({ auto: true, channel: "main" }, expect.objectContaining({ root: expect.any(String) }));+ // Enabling must not be persisted as raw prefs behind the authority's back.+ expect(mocks.writePrefs).not.toHaveBeenCalled();+ });++ it("rejects an updates patch that could mean anything else", async () => {+ const { POST } = await import("./route");+ for (const updates of [{ auto: true, ref: "origin/main" }, { channel: "nightly" }, { auto: "yes" }]) {+ const request = new NextRequest("https://mso.example/api/prefs", {+ method: "POST", headers: { "content-type": "application/json" },+ body: JSON.stringify({ updates }),+ });+ expect((await POST(request)).status).toBe(400);+ }+ expect(mocks.applyAutomation).not.toHaveBeenCalled();});});diff --git a/app/api/prefs/route.ts b/app/api/prefs/route.tsindex 82633bcd..2974fe15 100644--- a/app/api/prefs/route.ts+++ b/app/api/prefs/route.ts@@ -1,12 +1,15 @@import { NextRequest, NextResponse } from "next/server";import { requireSession } from "@/lib/auth/require-session";import { readPrefs, writePrefs, type OsPrefs } from "@/lib/prefs/store";+import { sanitizeUpdatesPatch } from "@/lib/prefs/updates";+import { applyAutomation } from "@/lib/host/update-automation";export const runtime = "nodejs";export const dynamic = "force-dynamic";-// Cross-device prefs sync (appearance tweaks + quicklinks). GET → stored prefs;-// POST → partial section merge. Session-gated; mirrors /api/config exactly.+// Cross-device prefs sync (appearance tweaks + quicklinks + update automation).+// GET → stored prefs; POST → partial section merge. Session-gated; mirrors+// /api/config exactly.export async function GET() {if (!(await requireSession())) {@@ -21,7 +24,7 @@ export async function POST(req: NextRequest) {if (!(await requireSession("owner"))) {return NextResponse.json({ error: "Unauthorized" }, { status: 401 });}- let body: { tweaks?: Record<string, unknown>; quicklinks?: unknown };+ let body: { tweaks?: Record<string, unknown>; quicklinks?: unknown; updates?: unknown };try {body = await req.json();} catch {@@ -36,9 +39,28 @@ export async function POST(req: NextRequest) {if (Array.isArray(body.quicklinks)) {patch.quicklinks = body.quicklinks as OsPrefs["quicklinks"];}- if (!patch.tweaks && !patch.quicklinks) {+ // `updates` is the one section that is not just a file write: enabling it must+ // install the timer. It goes through the same authority as the CLI and the+ // Settings toggle, so a POST here can never leave `auto:true` with no unit.+ let updates: ReturnType<typeof sanitizeUpdatesPatch> | null = null;+ if (body.updates !== undefined) {+ updates = sanitizeUpdatesPatch(body.updates);+ if (!updates.ok) return NextResponse.json({ error: updates.error }, { status: 400 });+ }+ if (!patch.tweaks && !patch.quicklinks && !updates) {return NextResponse.json({ error: "Nothing to update" }, { status: 400 });}- await writePrefs(patch);+ // Automation FIRST: enabling it can be refused by the host, and a refusal must not+ // leave the appearance section half-applied. It writes its own section through the+ // same serialized store, so the two writes cannot clobber each other.+ if (updates?.ok) {+ try {+ await applyAutomation(updates.patch, { root: process.cwd() });+ } catch (cause) {+ const message = cause instanceof Error ? cause.message : "could not apply update automation";+ return NextResponse.json({ error: message }, { status: 400 });+ }+ }+ if (patch.tweaks || patch.quicklinks) await writePrefs(patch);return NextResponse.json({ ok: true });}diff --git a/app/api/v1/sys/update/automation/route.test.ts b/app/api/v1/sys/update/automation/route.test.tsnew file mode 100644index 00000000..6e431f88--- /dev/null+++ b/app/api/v1/sys/update/automation/route.test.ts@@ -0,0 +1,76 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const authed = { current: true };+vi.mock("@/lib/agent/server", () => ({ verifyAuth: vi.fn(async () => authed.current) }));++const state = {+ prefs: { auto: true, channel: "stable" as const },+ timer: { installed: true, enabled: true, active: true, nextRun: null },+ active: true,+ last: { lastAttemptAt: null, lastResult: null, consecutiveFailures: 0, detail: null, channel: null },+ drift: null,+};+const readAutomationState = vi.fn(async () => state);+const applyAutomation = vi.fn(async (_patch: unknown, _ctx: unknown) => state);+vi.mock("@/lib/host/update-automation", () => ({+ readAutomationState: () => readAutomationState(),+ applyAutomation: (patch: unknown, ctx: unknown) => applyAutomation(patch, ctx),+}));+const reason = vi.hoisted(() => ({ value: null as string | null }));+vi.mock("@/lib/host/update-host-support", () => ({ automaticUpdateReason: async () => reason.value, execRunner: async () => ({ code: 0, stdout: "", stderr: "" }) }));+const auditMock = vi.fn();+vi.mock("@/lib/host/audit-api", () => ({ audit: (...args: unknown[]) => auditMock(...args) }));++const { GET, POST } = await import("./route");+const { HostError } = await import("@/lib/host/host-error");++const post = (body: unknown) =>+ new Request("http://localhost/api/v1/sys/update/automation", {+ method: "POST", body: JSON.stringify(body), headers: { "content-type": "application/json" },+ });++beforeEach(() => {+ authed.current = true;+ reason.value = null;+ readAutomationState.mockClear();+ applyAutomation.mockClear();+ auditMock.mockReset();+});++describe("/api/v1/sys/update/automation", () => {+ it("tells a signed-out caller nothing and touches no host state", async () => {+ authed.current = false;+ expect((await GET(new Request("http://localhost/api/v1/sys/update/automation"))).status).toBe(401);+ expect((await POST(post({ updates: { auto: true } }))).status).toBe(401);+ expect(readAutomationState).not.toHaveBeenCalled();+ expect(applyAutomation).not.toHaveBeenCalled();+ });++ it("reports the pref together with whether the host can host a timer", async () => {+ reason.value = "software updates require the checkout to be on main (current: feat/x)";+ const body = await (await GET(new Request("http://localhost/api/v1/sys/update/automation"))).json();+ expect(body).toMatchObject({ supported: false, active: true });+ expect(body.reason).toContain("on main");+ });++ it("refuses an unknown key or a non-enum channel instead of dropping it", async () => {+ for (const updates of [{ ref: "origin/main" }, { channel: "nightly" }, { auto: "on" }, {}]) {+ expect((await POST(post({ updates }))).status, JSON.stringify(updates)).toBe(400);+ }+ expect(applyAutomation).not.toHaveBeenCalled();+ });++ it("passes only the validated patch to the shared automation authority", async () => {+ expect((await POST(post({ updates: { auto: true, channel: "main" } }))).status).toBe(200);+ expect(applyAutomation).toHaveBeenCalledWith({ auto: true, channel: "main" }, expect.objectContaining({ root: expect.any(String) }));+ expect(auditMock).toHaveBeenCalledWith(expect.objectContaining({ action: "sys.update", target: "automation", ok: true }));+ });++ it("surfaces a host refusal as its sentence and audits it", async () => {+ applyAutomation.mockRejectedValueOnce(new HostError("automatic updates are unavailable: no systemd user manager"));+ const res = await POST(post({ updates: { auto: true } }));+ expect(res.status).toBe(400);+ expect((await res.json()).error).toContain("no systemd user manager");+ expect(auditMock).toHaveBeenCalledWith(expect.objectContaining({ target: "automation", ok: false }));+ });+});diff --git a/app/api/v1/sys/update/automation/route.ts b/app/api/v1/sys/update/automation/route.tsnew file mode 100644index 00000000..7a1a09ca--- /dev/null+++ b/app/api/v1/sys/update/automation/route.ts@@ -0,0 +1,55 @@+/**+ * Owner-only automation surface for the Updates card.+ *+ * GET → the pref, the REAL timer state, and the last unattended result.+ * POST → {auto?: boolean, channel?: "stable"|"main"} through the same module the+ * CLI uses, so the browser cannot install a timer the CLI does not see.+ *+ * The route prefix `/api/v1/sys/update` is owner-only in lib/agent/server.ts, so a+ * viewer cannot schedule a host restart.+ */+import { NextResponse } from "next/server";+import { verifyAuth } from "@/lib/agent/server";+import { apiError, readJson } from "@/lib/host/request-api";+import { audit } from "@/lib/host/audit-api";+import { applyAutomation, readAutomationState } from "@/lib/host/update-automation";+import { automaticUpdateReason, execRunner } from "@/lib/host/update-host-support";+import { sanitizeUpdatesPatch } from "@/lib/prefs/updates";++export const dynamic = "force-dynamic";+export const runtime = "nodejs";++const repoRoot = (): string => process.cwd();++export async function GET(req: Request) {+ if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ try {+ const [state, reason] = await Promise.all([readAutomationState(), automaticUpdateReason(execRunner)]);+ return NextResponse.json({ ...state, supported: reason === null, reason });+ } catch (e) {+ return apiError("sys/update/automation", e);+ }+}++export async function POST(req: Request) {+ if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ try {+ const body = (await readJson(req).catch(() => ({}))) as { updates?: unknown };+ // Strict: unknown keys and wrong types are a 400, never a silently ignored+ // "enabled" that the operator believes took effect.+ const parsed = sanitizeUpdatesPatch(body.updates);+ if (!parsed.ok) return NextResponse.json({ error: parsed.error }, { status: 400 });+ const state = await applyAutomation(parsed.patch, { root: repoRoot() });+ audit({+ action: "sys.update",+ target: "automation",+ ok: true,+ detail: `auto=${String(state.prefs.auto)} channel=${state.prefs.channel} timer=${state.active ? "on" : "off"}`,+ });+ return NextResponse.json(state);+ } catch (e) {+ audit({ action: "sys.update", target: "automation", ok: false, detail: String(e).slice(0, 200) });+ // A refusal ("automatic updates are unavailable: …") is a HostError → 400.+ return apiError("sys/update/automation", e);+ }+}diff --git a/app/api/v1/sys/update/route.test.ts b/app/api/v1/sys/update/route.test.tsindex c9dce881..d31f22fc 100644--- a/app/api/v1/sys/update/route.test.ts+++ b/app/api/v1/sys/update/route.test.ts@@ -102,12 +102,24 @@ describe("/api/v1/sys/update", () => {it("passes rebuildOnly through only when it is exactly true", async () => {await POST(post({ rebuildOnly: true }));- expect(startUpdate).toHaveBeenLastCalledWith(true);+ expect(startUpdate).toHaveBeenLastCalledWith(true, undefined);// A truthy string from a hand-rolled client must not silently mean "rebuild".await POST(post({ rebuildOnly: "yes" }));- expect(startUpdate).toHaveBeenLastCalledWith(false);+ expect(startUpdate).toHaveBeenLastCalledWith(false, undefined);await POST(post({}));- expect(startUpdate).toHaveBeenLastCalledWith(false);+ expect(startUpdate).toHaveBeenLastCalledWith(false, undefined);+ });++ it("accepts only the channel enum and ignores anything ref-shaped", async () => {+ await POST(post({ channel: "main" }));+ expect(startUpdate).toHaveBeenLastCalledWith(false, "main");+ await POST(post({ channel: "stable" }));+ expect(startUpdate).toHaveBeenLastCalledWith(false, "stable");+ // A ref, a tag or a command is not a channel: fall back to the stored pref.+ for (const channel of ["origin/main", "v1.2.3", "main --force", "--rebuild-only", 3, null]) {+ await POST(post({ channel }));+ expect(startUpdate).toHaveBeenLastCalledWith(false, undefined);+ }});it("surfaces a refusal as its sentence, not as a 500", async () => {diff --git a/app/api/v1/sys/update/route.ts b/app/api/v1/sys/update/route.tsindex 4c8c86ea..815a90a2 100644--- a/app/api/v1/sys/update/route.ts+++ b/app/api/v1/sys/update/route.ts@@ -4,6 +4,8 @@ import { apiError, readJson } from "@/lib/host/request-api";import { audit } from "@/lib/host/audit-api";import { rateLimited } from "@/lib/host/limits-api";import { getUpdateStatus, startUpdate } from "@/lib/host/self-update";+import { clearAutoUpdatePause } from "@/lib/prefs/auto-update-state";+import { parseUpdateChannel } from "@/lib/prefs/updates";export const dynamic = "force-dynamic";// Status reads and explicit update actions require the host runtime.@@ -20,14 +22,14 @@ export async function GET(req: Request) {}}-// POST /sys/update {rebuildOnly?} → pull, verify, build, restart. Audited: this-// replaces the code the whole cockpit runs, which is the most consequential thing-// any session can ask for. Body carries no ref and no command — the only knob is a-// boolean, and `origin/main` is hard-coded in the updater.+// POST /sys/update {rebuildOnly?, channel?} → pull, verify, build, restart. Audited:+// this replaces the code the whole cockpit runs, which is the most consequential+// thing any session can ask for. Body carries no ref and no command — the knobs are+// a boolean and the two-word channel enum; the ref is resolved server-side.export async function POST(req: Request) {if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });try {- const body = (await readJson(req).catch(() => ({}))) as { rebuildOnly?: unknown; action?: unknown };+ const body = (await readJson(req).catch(() => ({}))) as { rebuildOnly?: unknown; action?: unknown; channel?: unknown };if (body.action === "check") {const origin = new URL(process.env.OS_PUBLIC_ORIGIN || req.url).origin;if (req.headers.get("origin") !== origin) return NextResponse.json({ error: "same_origin_required" }, { status: 403 });@@ -37,12 +39,19 @@ export async function POST(req: Request) {return NextResponse.json(status);}const rebuildOnly = body.rebuildOnly === true;- const status = await startUpdate(rebuildOnly);+ // The client may name a CHANNEL, never a ref: an unknown value is ignored and the+ // stored preference decides. The ref itself is resolved server-side.+ const channel = parseUpdateChannel(body.channel) ?? undefined;+ const status = await startUpdate(rebuildOnly, channel);+ // A manual update is the operator's answer to the unattended pause. Clear the+ // failure streak when this one was accepted; otherwise the gate keeps refusing+ // forever and its own advice ("run mso update from a terminal") would be false.+ await clearAutoUpdatePause();audit({action: "sys.update",- target: rebuildOnly ? "rebuild" : `origin/main (+${status.behind})`,+ target: rebuildOnly ? "rebuild" : `${status.target ?? "origin/main"} (+${status.behind})`,ok: true,- detail: `from ${status.current}`,+ detail: `from ${status.current} on the ${status.channel ?? "stored"} channel`,});return NextResponse.json(status);} catch (e) {diff --git a/app/apple-icon.tsx b/app/apple-icon.tsxindex 9e33cb90..e6787b75 100644--- a/app/apple-icon.tsx+++ b/app/apple-icon.tsx@@ -1,22 +1,31 @@-import { ImageResponse } from "next/og";+import { NextResponse } from "next/server";+import { readAccountProfile } from "@/lib/auth/account-profile";+import { accountIconPng } from "@/lib/auth/account-icon-image";-// Apple touch icon (iOS home screen). iOS masks its own corners, so this is the-// full-bleed MASKABLE art (gradient square + folder-terminal glyph in the safe-// zone), rasterized from the same verified SVG via <img> (resvg) so there's no-// glyph drift vs the favicon. Text-free → no font embedding needed.+// Apple touch icon (iOS home screen). iOS masks its own corners, so the owner's+// square art works as-is; the brand fallback keeps the current full-bleed mark.+// Dynamic for the same reason as app/icon.tsx: the upload must reach it.++export const dynamic = "force-dynamic";export const size = { width: 180, height: 180 };export const contentType = "image/png";-const SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><defs><linearGradient id="b" x1="48" y1="40" x2="466" y2="474" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#4a7cf8"/><stop offset="1" stop-color="#6a54f8"/></linearGradient></defs><rect width="512" height="512" fill="url(#b)"/><g transform="translate(256 256) scale(0.8) translate(-256 -256)"><g fill="none" stroke="#ffffff" stroke-width="20" stroke-linecap="round" stroke-linejoin="round"><path d="M138 150 L238 150 L292 179 L374 179 Q402 179 402 207 L402 370 Q402 398 374 398 L138 398 Q110 398 110 370 L110 178 Q110 150 138 150 Z"/><path d="M166 272 L204 302 L166 332"/><path d="M226 348 L286 348"/><path d="M320 272 L358 302 L320 332"/></g><g fill="#ffffff"><circle cx="150" cy="188" r="11"/><circle cx="186" cy="188" r="11"/><circle cx="222" cy="188" r="11"/></g></g></svg>`;+const CACHE = "public, max-age=60, stale-while-revalidate=300";-export default function AppleIcon() {- const uri = `data:image/svg+xml;base64,${Buffer.from(SVG).toString("base64")}`;- return new ImageResponse(- (- <div style={{ display: "flex", width: "100%", height: "100%" }}>- <img src={uri} width={180} height={180} alt="" />- </div>- ),- size,- );+export default async function AppleIcon() {+ let png: Buffer;+ try {+ png = await accountIconPng((await readAccountProfile()).icon, size.width);+ } catch {+ png = Buffer.alloc(0);+ }+ if (!png.length) return new NextResponse(null, { status: 404 });+ return new NextResponse(new Uint8Array(png), {+ headers: {+ "Content-Type": contentType,+ "Content-Length": String(png.length),+ "Cache-Control": CACHE,+ "X-Content-Type-Options": "nosniff",+ },+ });}diff --git a/app/icon.svg b/app/icon.svgdeleted file mode 100644index a07d813d..00000000--- a/app/icon.svg+++ /dev/null@@ -1,20 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512" role="img" aria-label="MSO — Manef Shell OS">- <defs>- <linearGradient id="mso-bg" x1="48" y1="40" x2="466" y2="474" gradientUnits="userSpaceOnUse">- <stop offset="0" stop-color="#4a7cf8"/>- <stop offset="1" stop-color="#6a54f8"/>- </linearGradient>- </defs>- <rect x="16" y="16" width="480" height="480" rx="116" fill="url(#mso-bg)"/>- <g fill="none" stroke="#ffffff" stroke-width="20" stroke-linecap="round" stroke-linejoin="round">- <path d="M138 150 L238 150 L292 179 L374 179 Q402 179 402 207 L402 370 Q402 398 374 398 L138 398 Q110 398 110 370 L110 178 Q110 150 138 150 Z"/>- <path d="M166 272 L204 302 L166 332"/>- <path d="M226 348 L286 348"/>- <path d="M320 272 L358 302 L320 332"/>- </g>- <g fill="#ffffff">- <circle cx="150" cy="188" r="11"/>- <circle cx="186" cy="188" r="11"/>- <circle cx="222" cy="188" r="11"/>- </g>-</svg>diff --git a/app/icon.tsx b/app/icon.tsxnew file mode 100644index 00000000..d09670de--- /dev/null+++ b/app/icon.tsx@@ -0,0 +1,46 @@+import { NextResponse } from "next/server";+import { readAccountProfile } from "@/lib/auth/account-profile";+import { accountIconPng } from "@/lib/auth/account-icon-image";++// Dynamic favicon + PWA icons. This replaces the static app/icon.svg so the+// owner's uploaded art reaches the browser tab.+//+// Public on purpose: a favicon is fetched by an unauthenticated tab, long before+// any session exists. It reads only the stored icon bytes (never the name).+//+// `force-dynamic` is required — without it Next bakes the build-time profile into+// the route and a later upload would never show. A short max-age keeps the+// per-page-load cost down instead; stale-while-revalidate hides the re-render.++export const dynamic = "force-dynamic";++const SIZES = [32, 192, 512] as const;+const CACHE = "public, max-age=60, stale-while-revalidate=300";++export function generateImageMetadata() {+ return SIZES.map((size) => ({+ id: String(size),+ size: { width: size, height: size },+ contentType: "image/png",+ }));+}++export default async function Icon({ id }: { id: Promise<string | number> }) {+ const requested = Number.parseInt(String(await id), 10);+ const size = (SIZES as readonly number[]).includes(requested) ? requested : 32;+ let png: Buffer;+ try {+ png = await accountIconPng((await readAccountProfile()).icon, size);+ } catch {+ png = Buffer.alloc(0);+ }+ if (!png.length) return new NextResponse(null, { status: 404 });+ return new NextResponse(new Uint8Array(png), {+ headers: {+ "Content-Type": "image/png",+ "Content-Length": String(png.length),+ "Cache-Control": CACHE,+ "X-Content-Type-Options": "nosniff",+ },+ });+}diff --git a/app/manifest.ts b/app/manifest.tsindex 28052b89..424fd900 100644--- a/app/manifest.ts+++ b/app/manifest.ts@@ -3,6 +3,12 @@ import type { MetadataRoute } from "next";// PWA manifest (served at /manifest.webmanifest). Installable standalone app.// `shortcuts` give the installed icon a long-press / right-click jump menu// straight into an app (deep-linked via the catch-all route's slugs).+//+// Icons point at the dynamic metadata routes (`app/icon.tsx` with+// generateImageMetadata → /icon/<size>), so an owner upload reaches the installed+// PWA as well as the tab. Sizes are explicit because a manifest entry without a+// usable size is skipped by installers; the PNG variant is used because WebP is+// still not universally accepted for install icons.export default function manifest(): MetadataRoute.Manifest {return {id: "/",@@ -20,8 +26,9 @@ export default function manifest(): MetadataRoute.Manifest {background_color: "#0a0a0a",theme_color: "#0a0a0a",icons: [- { src: "/icon.svg", sizes: "any", type: "image/svg+xml", purpose: "any" },- { src: "/icon-maskable.svg", sizes: "any", type: "image/svg+xml", purpose: "maskable" },+ { src: "/icon/192", sizes: "192x192", type: "image/png", purpose: "any" },+ { src: "/icon/512", sizes: "512x512", type: "image/png", purpose: "any" },+ { src: "/icon/512", sizes: "512x512", type: "image/png", purpose: "maskable" },],shortcuts: [{ name: "Terminal", short_name: "Terminal", url: "/terminal" },diff --git a/bin/mso b/bin/msoindex e740c079..4c8e1774 100755--- a/bin/mso+++ b/bin/mso@@ -107,7 +107,10 @@# service * status | start | stop | restart | logs# build Compile HEAD out-of-tree (safe against the live checkout)# deploy Rebuild active service with runtime quiesce/restore-# update [--rebuild] Update from origin/main safely; works even when the web runtime is down+# update [--rebuild] Update safely from the configured channel; works even when the web runtime is down+# update --auto on|off Enable/disable the nightly unattended update timer+# update --channel stable|main Follow release tags (stable) or rolling main+# update status Show the channel, timer state and last unattended attempt# update reconcile Preserve a local-only/diverged HEAD, then sync main to origin/main## reset [--scope config|all] Preview local factory reset; explicit token required to applydiff --git a/bin/mso-update-offline.test.ts b/bin/mso-update-offline.test.tsindex 14ce365f..f4ea3426 100644--- a/bin/mso-update-offline.test.ts+++ b/bin/mso-update-offline.test.ts@@ -102,7 +102,13 @@ describe("mso offline update dispatch", () => {it("keeps `mso update run` as a local compatibility alias", () => {const cli = fs.readFileSync(path.join(ROOT, "scripts/cli/commands-admin.sh"), "utf8");const updater = fs.readFileSync(path.join(ROOT, "scripts/mso-update"), "utf8");- expect(cli).toMatch(/update\).*scripts\/mso-update/);+ const updateCase = /update\)([\s\S]*?)\n esac ;;/.exec(cli)?.[1] ?? "";+ expect(updateCase).not.toBe("");+ // `mso update` still hands off to scripts/mso-update; the settings subcommands+ // intentionally do NOT, because they share the module the Settings toggle uses.+ expect(updateCase).toMatch(/scripts\/mso-update/);+ expect(updateCase).toMatch(/--auto/);+ expect(updateCase).toMatch(/--channel/);expect(updater).toMatch(/case "\$\{1:-run\}" in/);expect(updater).toMatch(/run\) case/);});diff --git a/bin/mso.test.ts b/bin/mso.test.tsindex c5e71f4c..7611ee58 100644--- a/bin/mso.test.ts+++ b/bin/mso.test.ts@@ -140,6 +140,14 @@ describe("bin/mso", () => {// Passwords stay in OS_LOGIN_PASSWORD and must not be placed on a shell argv."/api/auth/account","/api/auth/password",+ // The upload endpoint is the browser's half of Settings → Account: it converts an+ // image to WebP/ICO and stores it. The CLI has no image pipeline and no verb that+ // would justify one; `mso` never needs to upload an avatar over argv.+ "/api/auth/account/icon",+ // The update-automation route exists for the Settings card. `mso update --auto`+ // and `--channel` call the SAME lib/host/update-automation module directly, so a+ // CLI verb over HTTP would be a second, drifting implementation of "enabled".+ "/api/v1/sys/update/automation",// Internal transport between scripts/mso-agent.mjs and the authenticated// server-side MCP catalog. It is not a user-facing CLI verb by design."/api/v1/agent-tools",diff --git a/bun.lock b/bun.lockindex 223ebe44..f9601940 100644--- a/bun.lock+++ b/bun.lock@@ -7,6 +7,7 @@"dependencies": {"@anthropic-ai/sdk": "^0.133.0","@imgly/background-removal": "^1.7.0",+ "@phosphor-icons/react": "^2.1.10","@radix-ui/react-alert-dialog": "^1.2.0","@radix-ui/react-dialog": "^1.3.0","@radix-ui/react-dropdown-menu": "^2.2.0",@@ -32,6 +33,7 @@"react-dom": "^19.3.0","react-konva": "^19.3.0","react-resizable-panels": "^4.14.4",+ "sharp": "^0.35.5","tailwind-merge": "^3.7.0","tw-animate-css": "^1.4.0","vaul": "^1.1.2",@@ -71,7 +73,6 @@"micromatch": "npm:[email protected]","nanoid": "^3.3.18","postcss": "^8.5.10",- "sharp": "^0.35.5",},"packages": {"@alloc/quick-lru": ["@alloc/[email protected]", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="],@@ -118,7 +119,7 @@"@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" } }, "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw=="],- "@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA=="],+ "@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],"@emnapi/wasi-threads": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w=="],@@ -256,6 +257,8 @@"@oxc-project/types": ["@oxc-project/[email protected]", "", {}, "sha512-KYOUGQFlLWR+s4QMV2Q9ko38TZm7EdO87Qm7rvZLqk/webse/cDjtyxKhg/47l0byCbs/k46LT8qc4PKjAikzA=="],+ "@phosphor-icons/react": ["@phosphor-icons/[email protected]", "", { "peerDependencies": { "react": ">= 16.8", "react-dom": ">= 16.8" } }, "sha512-vt8Tvq8GLjheAZZYa+YG/pW7HDbov8El/MANW8pOAz4eGxrwhnbfrQZq0Cp4q8zBEu8NIhHdnr+r8thnfRSNYA=="],+"@playwright/test": ["@playwright/[email protected]", "", { "dependencies": { "playwright": "1.64.0" }, "bin": { "playwright": "cli.js" } }, "sha512-oTN9FNYuN6bqQMwiho6jJKLCG2/QOYCixGXuCjRmzOq23eODeukuY2XiAVoVpAECbuezMt1MHQjAiQxK8F+Y+g=="],"@protobufjs/aspromise": ["@protobufjs/[email protected]", "", {}, "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ=="],@@ -1092,7 +1095,7 @@"scheduler": ["[email protected]", "", {}, "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw=="],- "semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],+ "semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],"set-function-length": ["[email protected]", "", { "dependencies": { "define-data-property": "^1.1.4", "es-errors": "^1.3.0", "function-bind": "^1.1.2", "get-intrinsic": "^1.2.4", "gopd": "^1.0.1", "has-property-descriptors": "^1.0.2" } }, "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg=="],@@ -1238,12 +1241,14 @@"@babel/core/json5": ["[email protected]", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="],+ "@babel/core/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],++ "@babel/helper-compilation-targets/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],+"@eslint-community/eslint-utils/eslint-visitor-keys": ["[email protected]", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="],"@eslint/eslintrc/globals": ["[email protected]", "", {}, "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ=="],- "@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],-"@jridgewell/gen-mapping/@jridgewell/sourcemap-codec": ["@jridgewell/[email protected]", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="],"@jridgewell/trace-mapping/@jridgewell/sourcemap-codec": ["@jridgewell/[email protected]", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="],@@ -1270,33 +1275,35 @@"@typescript-eslint/typescript-estree/minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^5.0.8" } }, "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A=="],- "@typescript-eslint/typescript-estree/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],-"@typescript-eslint/visitor-keys/eslint-visitor-keys": ["[email protected]", "", {}, "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA=="],+ "@unrs/resolver-binding-wasm32-wasi/@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA=="],+"eslint-import-resolver-node/debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.1" } }, "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ=="],"eslint-module-utils/debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.1" } }, "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ=="],"eslint-plugin-import/debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.1" } }, "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ=="],+ "eslint-plugin-import/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],+"eslint-plugin-jsx-a11y/axe-core": ["[email protected]", "", {}, "sha512-s7iGf5GaVMxEG0ENN9x+xTr7GFZCb1ZP/1uATUpCEK2X78nDB3RwbtFCo9pGAf9ru+VwoQ464DkaLEeRM08wJA=="],+ "eslint-plugin-react/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],+"eslint-plugin-react-hooks/zod": ["[email protected]", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],"fast-glob/glob-parent": ["[email protected]", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],- "is-bun-module/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],-"its-fine/@types/react-reconciler": ["@types/[email protected]", "", { "peerDependencies": { "@types/react": "*" } }, "sha512-HHM3nxyUZ3zAylX8ZEyrDNd2XZOnQ0D5XfunJF5FLQnZbHHYq4UWvW1QfelQNXv1ICNkwYhfxjwfnqivYB6bFg=="],"loose-envify/js-tokens": ["[email protected]", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],"minimatch/brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw=="],- "protobufjs/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q=="],+ "node-exports-info/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],- "sharp/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],+ "protobufjs/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q=="],"tinyglobby/picomatch": ["[email protected]", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="],diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex e26641e7..d3730ee6 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -4,22 +4,30 @@Newest first. `docs/PROGRESS.md` is the source of truth for *why* a change was made;this is the *what*, and it is what Settings → Account → About shows as “What's new”.+## 2026-10-22++**Added**++- one-click install and connect converge on a shared shell-app domain step (#136)+- `settings` explain update refusals, merge Server into Devices (#135)+## 2026-10-21**Added**-- `app-store` converge install and connect on one domain step-- `shell-apps` provision public domains for shell apps-- `infra` add managed domain provider abstraction- `cli` print the mso ai reply text instead of SSE frames- `infra` add Linear provider and route Composio key kinds by header**Fixed**-- `composio` refuse Connect consumer keys on the Platform provider-- `app-domain` wire the real provider module and single-source the domain contract+- `proxy` let the owner icon upload reach its own 8 MiB cap+- `host` make agent worktrees owner-private regardless of umask- `deps` pin vite 8.2.4 to clear GHSA-587h-7wmj-h5pm+**Build**++- `deps` make sharp a direct dependency and add @phosphor-icons/react+## 2026-10-20**Fixed**@@ -1500,24 +1508,3 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh- record external MCP consumer compatibility- `readme` the update button, and what Preview actually opens- plain http to an IP cannot complete a login — say so where it matters--## 2026-08-11--**Added**--- `ship` one command that changelogs, pushes, rebuilds and verifies-- `shells` Windows/iOS/Android to their 2026 specs, plus a backup for local state--**Fixed**--- `ship` amend on retry, and collapse a repeated subject in the changelog-- `ai` Codex DOES do tool calling — implement it instead of announcing it cannot-- `pwa,chat` notch clearance, a doubled iOS inset, and an assistant that was lying--**Tests**--- `e2e` a browser that actually loads the page — and the three bugs it found--**Docs**--- `progress` log the shell-spec pass, the springs, and the backupdiff --git a/docs/CLI.md b/docs/CLI.mdindex b49780f3..29953890 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -147,7 +147,10 @@ Commands:service * status | start | stop | restart | logsbuild Compile HEAD out-of-tree (safe against the live checkout)deploy Rebuild active service with runtime quiesce/restore- update [--rebuild] Update from origin/main safely; works even when the web runtime is down+ update [--rebuild] Update safely from the configured channel; works even when the web runtime is down+ update --auto on|off Enable/disable the nightly unattended update timer+ update --channel stable|main Follow release tags (stable) or rolling main+ update status Show the channel, timer state and last unattended attemptupdate reconcile Preserve a local-only/diverged HEAD, then sync main to origin/mainreset [--scope config|all] Preview local factory reset; explicit token required to applydiff --git a/docs/INSTALL.md b/docs/INSTALL.mdindex aa5e94ef..2b10f3cc 100644--- a/docs/INSTALL.md+++ b/docs/INSTALL.md@@ -621,6 +621,47 @@ mso update # preferred: update safely even if :4005 is downmso update log```+#### Update channel++`mso update --channel stable|main` (or Settings → About → Updates) chooses what an update+compares against. The channel is a **two-word enum**; no ref, tag, path or command is ever+accepted from a client or stored verbatim, and the updater resolves the Git target itself:++- `stable` (default) → the highest `vX.Y.Z` release tag reachable from `origin/main`.+- `main` → rolling `origin/main`, unchanged from earlier releases.++Because release tags can lag `package.json`, a checkout that is already past the newest tag+reports up to date on the stable channel **instead of** silently following `main`. The only+exception is a repository with no release tag at all; the status line then says+`no release tag exists yet` and the target is `origin/main`. Both channels still require the+checkout to be on branch `main`, and both still fast-forward only: if `HEAD` is not an+ancestor of the resolved target, the update refuses with "reconcile first" rather than+force-checking out a release.++#### Unattended updates (opt-in, off by default)++```bash+mso update --auto on # install + enable the user timer and record the preference+mso update --auto off # disable and delete the timer, then clear the preference+mso update status # channel, real timer state, last unattended attempt+```++Enabling writes `~/.mso/prefs.json` (`updates.auto`) **and** installs+`~/.config/systemd/user/mso-auto-update.{service,timer}` in the owner's user manager — no sudo,+the same manager the manual update uses. The timer runs `*-*-* 04:30:00` with+`RandomizedDelaySec=25m` and `Persistent=true`. Turning it on is refused outright when the host+cannot host a safe restart (wrong branch, no `mso.service` restart policy, no user manager), so+the panel can never show "on" for a scheduler that does not exist; it also reads the real unit+state, so a manually deleted timer reads "off".++An unattended run refuses, and records the reason in `~/.mso/auto-update-state.json`, when the+checkout is unsupported, dirty, has local commits ahead, already has an update running, when the+previous **two** builds failed in a row, or when the incoming commits touch the updater itself+(`lib/host/self-update*.ts`, `lib/host/update-*.ts`, `scripts/mso-service-update`,+`scripts/self-update.sh`, `scripts/self-update-auto.ts`, `scripts/mso-auto-update`). Those last+ones are applied by a human from a terminal. The pre-flight pins the commit it inspected, and+`scripts/self-update.sh` refuses if the target moved before the build started.+MSO has two explicitly labeled version domains: the app/package version shown in Settings → Account → About and the independently versioned CLI contract shown by `mso --version`. The Git commit/build remains update authority. If commits changed without a CLI bump, status says `N new commits on mso CLI X` rather than rendering `X -> X`.The updater verifies the incoming checkout/build before replacing the service. Re-running the installer on an existing checkout acquires the same checkout-scoped transaction lock **before** Git fetch/checkout mutation and hands that open lock FD to the post-checkout runtime lifecycle, so installer, `mso update`, and `mso deploy` cannot mutate one checkout concurrently. The lock primitive is carried by the verified installer payload itself, so older MSO checkouts that predate the current private-state helper remain upgradeable in place. A normal `mso update` treats fetched `origin/main` as the release authority: after any fast-forward, local `main` must equal that remote commit exactly. A clean branch that is locally ahead or diverged is refused before dependency/build mutation instead of deploying unpushed code. `mso update status` reports that state explicitly; `mso update reconcile` makes recovery explicit and lossless by preserving the previous HEAD on a timestamped local `rescue/mso-update-*` branch before resetting clean `main` to fetched `origin/main`. `mso update --rebuild` is different by design: it rebuilds the already-selected clean checkout without changing Git history. With an activediff --git a/docs/SLICE-CATALOG.md b/docs/SLICE-CATALOG.mdindex 84efbd73..65307bdc 100644--- a/docs/SLICE-CATALOG.md+++ b/docs/SLICE-CATALOG.md@@ -3,7 +3,7 @@> **Current reference.** Counts are checked against the directory tree by> `scripts/check-docs.mjs`; the directory remains the final authority.-<!-- slice-catalog: slices=31 appshell-features=10 -->+<!-- slice-catalog: slices=32 appshell-features=10 -->Every application is a vertical slice under `frontend/slices/`. Host-facing slices use theshared API/host seam rather than reaching arbitrary Node host APIs from client code.@@ -26,6 +26,7 @@ shared API/host seam rather than reaching arbitrary Node host APIs from client c| `extensions` | Shared VPS-backed MCP and Skills Store / Settings installation panels || `files-manager` | VPS Files manager || `image-editor` | Layered raster image editor |+| `icon-picker` | Emoji/Lucide/Phosphor icon chooser with lazy catalogs and `<DynamicIcon>` || `image-picker` | Reusable image/wallpaper picker || `infrastructure` | Dokploy/Cloudflare provider configuration and live inventory apps || `integrations` | Native connection manager shell window using the existing Integrations service |diff --git a/frontend/slices/icon-picker/components/DynamicIcon.test.tsx b/frontend/slices/icon-picker/components/DynamicIcon.test.tsxnew file mode 100644index 00000000..b1ee50d9--- /dev/null+++ b/frontend/slices/icon-picker/components/DynamicIcon.test.tsx@@ -0,0 +1,37 @@+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it } from "vitest";+import { DynamicIcon } from "./DynamicIcon";++// AccountAvatar renders a stored `library` icon on the server (settings page),+// so DynamicIcon must produce markup without a browser. Each branch is checked+// because a silent fallback would show the wrong glyph with no error.+describe("DynamicIcon (used by the account avatar)", () => {+ it("renders a lucide icon", () => {+ const html = renderToStaticMarkup(<DynamicIcon value="lucide:Star" size={32} />);+ expect(html).toContain("svg");+ expect(html).toContain('width="35"'); // 32 / 0.92 fill ratio+ });++ it("renders a phosphor fill icon", () => {+ const html = renderToStaticMarkup(<DynamicIcon value="phosphor:ShieldCheck" size={32} />);+ expect(html).toContain("svg");+ });++ it("renders an emoji glyph as text in native mode", () => {+ const html = renderToStaticMarkup(<DynamicIcon value="🎯?c=0b6e99" size={32} forceNative />);+ expect(html).toContain("🎯");+ // The tint suffix is parsed but not painted on a native glyph — it only+ // affects twemoji framing. Asserting that keeps the behaviour honest.+ expect(html).not.toContain("#0b6e99");+ });++ it("twemoji mode (the default) hot-links the glyph asset, which is why the avatar forces native", () => {+ const html = renderToStaticMarkup(<DynamicIcon value="🎯" size={32} />);+ expect(html).toContain("cdn.jsdelivr.net");+ });++ it("falls back instead of throwing on an unknown name or empty value", () => {+ expect(() => renderToStaticMarkup(<DynamicIcon value="lucide:NotARealIcon" />)).not.toThrow();+ expect(() => renderToStaticMarkup(<DynamicIcon value="" fallback="lucide:FileText" />)).not.toThrow();+ });+});diff --git a/frontend/slices/icon-picker/components/DynamicIcon.tsx b/frontend/slices/icon-picker/components/DynamicIcon.tsxnew file mode 100644index 00000000..2feab715--- /dev/null+++ b/frontend/slices/icon-picker/components/DynamicIcon.tsx@@ -0,0 +1,160 @@+"use client";++import * as React from "react";+import { cn } from "@/lib/utils";+import { parseIconValue, type IconValue } from "../lib/parse";+import { twemojiUrl } from "../lib/twemoji";+import { useIconStyle, type Style } from "../lib/style-pref";+import { LUCIDE_ICONS, FallbackLucideIcon } from "../lib/lucide-icons";+import { PHOSPHOR_ICONS, FallbackPhosphorIcon } from "../lib/phosphor-icons";+import { renderSizeFor, type IconRenderKind } from "../lib/icon-render-config";++interface CommonProps {+ value: string | null | undefined;+ /** Extra Tailwind classes for the wrapping span. Layout only — use+ * the `size` prop for icon sizing, not className `text-*`. */+ className?: string;+ /** Fallback emoji or `lucide:Name` shown when value is empty. */+ fallback?: string;+ /** Title for tooltip (a11y). */+ title?: string;+ /**+ * Target VISIBLE mark size in pixels. The wrapper box stays exactly+ * this size; the inner primitive is up-scaled per kind via+ * `ICON_FILL_RATIO` so the visible mark hits the same target across+ * emoji, twemoji, lucide, and phosphor. See `lib/icon-render-config`.+ *+ * Legacy callers can omit this prop — the inner primitive falls+ * back to `h-[1em]` cascade from the parent font-size.+ */+ size?: number;+}++/** Recommended hero-icon size (page covers, profile, …). */+export const DEFAULT_ICON_SIZE = 72;++const WRAPPER_BASE = "inline-flex items-center justify-center leading-none";++function wrapperStyle(size: number | undefined, color: string | undefined): React.CSSProperties | undefined {+ if (size === undefined) return color ? { color } : undefined;+ return { width: size, height: size, ...(color ? { color } : null) };+}++function resolveValue(value: string | null | undefined, fallback: string): IconValue {+ const primary = parseIconValue(value);+ if (primary.kind === "emoji" && !primary.emoji) return parseIconValue(fallback);+ return primary;+}++interface RawIconProps extends CommonProps {+ /** Explicit render style. When provided, RawIcon does NOT subscribe to+ * the global style store — caller is responsible for the value. */+ style: Style;+}++function RawIconImpl({ value, style, className, fallback = "📄", title, size }: RawIconProps) {+ const parsed = React.useMemo(() => resolveValue(value, fallback), [value, fallback]);++ if (parsed.kind === "lucide") {+ const Cmp = LUCIDE_ICONS[parsed.name] ?? FallbackLucideIcon;+ if (Cmp === FallbackLucideIcon && process.env.NODE_ENV !== "production") {+ console.warn(`[DynamicIcon] Unknown lucide icon: "${parsed.name}". Falling back to FileText.`);+ }+ return renderWithKind("lucide", size, parsed.color, className, title, (renderSize) =>+ renderSize !== undefined+ ? <Cmp size={renderSize} style={{ width: renderSize, height: renderSize }} />+ : <Cmp style={{ width: "1em", height: "1em" }} />,+ );+ }++ if (parsed.kind === "phosphor") {+ const Cmp = PHOSPHOR_ICONS[parsed.name] ?? FallbackPhosphorIcon;+ if (Cmp === FallbackPhosphorIcon && process.env.NODE_ENV !== "production") {+ console.warn(`[DynamicIcon] Unknown phosphor icon: "${parsed.name}". Falling back to FileText.`);+ }+ return renderWithKind("phosphor", size, parsed.color, className, title, (renderSize) =>+ renderSize !== undefined+ ? <Cmp weight="fill" size={renderSize} style={{ width: renderSize, height: renderSize }} />+ : <Cmp weight="fill" style={{ width: "1em", height: "1em" }} />,+ );+ }++ const glyph = parsed.kind === "emoji" ? parsed.emoji : "";+ if (style === "twemoji" && glyph) {+ const url = twemojiUrl(glyph);+ if (url) return <TwemojiImg url={url} glyph={glyph} className={className} title={title} size={size} />;+ }+ // Native emoji branch — render-size drives font-size; wrapper box stays `size`.+ return renderWithKind("emoji", size, undefined, className, title, (renderSize) => (+ <span style={renderSize !== undefined ? { fontSize: renderSize, lineHeight: 1 } : undefined}>+ {glyph}+ </span>+ ));+}++/** Single render path for lucide / phosphor / emoji native. Wrapper+ * box = caller's `size`; inner primitive is up-scaled per kind via+ * `renderSizeFor`. `overflow-visible` lets up-scaled SVGs spill+ * outside the box cleanly. */+function renderWithKind(+ kind: IconRenderKind,+ size: number | undefined,+ color: string | undefined,+ className: string | undefined,+ title: string | undefined,+ inner: (renderSize: number | undefined) => React.ReactNode,+) {+ const renderSize = size !== undefined ? renderSizeFor(kind, size) : undefined;+ return (+ <span className={cn(WRAPPER_BASE, className)} title={title} style={{ overflow: "visible", ...wrapperStyle(size, color) }}>+ {inner(renderSize)}+ </span>+ );+}++export const RawIcon = React.memo(RawIconImpl);++interface DynamicIconProps extends CommonProps {+ /** Force native emoji rendering even when twemoji preference is on. */+ forceNative?: boolean;+}++function DynamicIconImpl({ value, className, fallback, title, forceNative, size }: DynamicIconProps) {+ const [style] = useIconStyle();+ const effective: Style = forceNative ? "native" : style;+ return <RawIcon value={value} style={effective} className={className} fallback={fallback} title={title} size={size} />;+}++export const DynamicIcon = React.memo(DynamicIconImpl);++function TwemojiImgImpl({+ url, glyph, className, title, size,+}: { url: string; glyph: string; className?: string; title?: string; size?: number }) {+ const [failed, setFailed] = React.useState(false);+ const renderSize = size !== undefined ? renderSizeFor("twemoji", size) : undefined;+ if (failed) {+ return renderWithKind("emoji", size, undefined, className, title ?? glyph, (rs) => (+ <span style={rs !== undefined ? { fontSize: rs, lineHeight: 1 } : undefined}>{glyph}</span>+ ));+ }+ return (+ <span className={cn(WRAPPER_BASE, className)} style={wrapperStyle(size, undefined)}>+ {/* eslint-disable-next-line @next/next/no-img-element -- external SVG CDN; next/image can't optimize without custom loader */}+ <img+ src={url}+ alt={glyph}+ title={title ?? glyph}+ loading="lazy"+ decoding="async"+ draggable={false}+ onError={() => setFailed(true)}+ width={renderSize}+ height={renderSize}+ className="select-none object-contain"+ style={renderSize !== undefined ? { width: renderSize, height: renderSize } : undefined}+ />+ </span>+ );+}++const TwemojiImg = React.memo(TwemojiImgImpl);diff --git a/frontend/slices/icon-picker/components/IconPicker.tsx b/frontend/slices/icon-picker/components/IconPicker.tsxnew file mode 100644index 00000000..414d4d52--- /dev/null+++ b/frontend/slices/icon-picker/components/IconPicker.tsx@@ -0,0 +1,165 @@+"use client";++import * as React from "react";+import { Slot } from "@radix-ui/react-slot";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { ResponsiveDialog } from "@/features/appshell";+import { Button } from "@/components/ui/button";+import { DynamicIcon } from "./DynamicIcon";+import { PickerSkeleton } from "./PickerSkeleton";+import type { IconPickerInlineProps } from "./IconPickerInline";++/** Lazy-loaded picker body. Catalogs (~600 emoji strings, ~250 lucide+ * imports, ~190 phosphor imports) sit in this chunk — pages that never+ * open the picker pay zero JS for the catalog. */+const IconPickerInlineLazy = React.lazy(() =>+ import("./IconPickerInline").then((m) => ({ default: m.IconPickerInline })),+);++interface IconPickerPopoverProps extends Omit<IconPickerInlineProps, "onSelect"> {+ children?: React.ReactNode;+ /** Controlled open state. Omit to let the popover manage its own. */+ open?: boolean;+ /** Notified on every open-state change. */+ onOpenChange?: (open: boolean) => void;+ /** Fired ONLY on icon pick — NOT on color pick. Auto-closes. */+ onSelect?: () => void;+ align?: "start" | "center" | "end";+ side?: "top" | "right" | "bottom" | "left";+}++/** Minimum vertical space (px) needed on a side: picker chrome (~150) plus a+ * usable grid (~190). Below this we promote to a centered Dialog. */+const PICKER_MIN_FIT_PX = 340;+const PICKER_EDGE_PADDING = 12;+/** Below this viewport width the ~360px popover would overflow horizontally. */+const PICKER_MIN_VIEWPORT_WIDTH = 360;++/** Smart picker wrapper with auto-flip + center-screen fallback.+ *+ * Behaviour contract:+ * - Color pick → picker stays open. Consumer's `onChange` fires.+ * - Icon pick → picker auto-closes. `onChange` + `onSelect` fire.+ * - Defers mounting the picker body until first open.+ * - Wraps body in `<Suspense fallback={<PickerSkeleton />}>`.+ *+ * Layout is decided once, when the picker opens (event handler, not an+ * effect): a 340px-tall surface either fits beside the trigger or the picker+ * becomes a dialog. Radix's `avoidCollisions` handles small drifts after that;+ * a resize while open keeps the chosen shape for the rest of the interaction. */+export function IconPickerPopover({+ value,+ onChange,+ onClear,+ onSelect,+ children,+ open: controlledOpen,+ onOpenChange,+ align = "start",+ side = "bottom",+}: IconPickerPopoverProps) {+ const isControlled = controlledOpen !== undefined;+ const [internalOpen, setInternalOpen] = React.useState(false);+ const open = isControlled ? !!controlledOpen : internalOpen;++ /** Mounted once, never unmounted: the lazy chunk and the recents ring should+ * survive closing so a second open is instant. */+ const [everOpened, setEverOpened] = React.useState(false);+ const [layout, setLayout] = React.useState<"popover" | "dialog">("popover");+ const triggerRef = React.useRef<HTMLElement | null>(null);+ const setTriggerRef = React.useCallback((node: HTMLElement | null) => {+ triggerRef.current = node;+ }, []);++ const setOpen = React.useCallback(+ (next: boolean) => {+ if (next) {+ setEverOpened(true);+ const node = triggerRef.current;+ if (node && typeof window !== "undefined") {+ const rect = node.getBoundingClientRect();+ const above = rect.top - PICKER_EDGE_PADDING;+ const below = window.innerHeight - rect.bottom - PICKER_EDGE_PADDING;+ const fitsAnySide = above >= PICKER_MIN_FIT_PX || below >= PICKER_MIN_FIT_PX;+ setLayout(fitsAnySide && window.innerWidth >= PICKER_MIN_VIEWPORT_WIDTH ? "popover" : "dialog");+ }+ }+ if (!isControlled) setInternalOpen(next);+ onOpenChange?.(next);+ },+ [isControlled, onOpenChange],+ );++ const handleSelect = React.useCallback(() => {+ setOpen(false);+ onSelect?.();+ }, [setOpen, onSelect]);++ const trigger = (+ <Slot ref={setTriggerRef}>+ {children ?? (+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="inline-flex h-10 w-10 items-center justify-center rounded-md border border-border transition hover:bg-accent"+ style={{ fontSize: "1.5rem" }}+ aria-label="Change icon"+ >+ <DynamicIcon value={value} size={24} />+ </Button>+ )}+ </Slot>+ );++ const body = everOpened ? (+ <React.Suspense fallback={<PickerSkeleton />}>+ <IconPickerInlineLazy+ value={value}+ onChange={onChange}+ onClear={onClear}+ onSelect={handleSelect}+ />+ </React.Suspense>+ ) : (+ <PickerSkeleton />+ );++ // A popover that could not fit becomes a centered dialog. It goes through+ // ResponsiveDialog so the bottom sheet / panel variants match every other feature+ // form instead of a raw Dialog. The hidden Popover keeps the trigger element+ // mounted in the same position.+ if (layout === "dialog") {+ return (+ <Popover open={false} onOpenChange={() => {}}>+ <PopoverTrigger asChild>{trigger}</PopoverTrigger>+ <ResponsiveDialog open={open} onOpenChange={setOpen} size="md">+ <ResponsiveDialog.Body className="flex flex-col gap-0 p-3" style={{ height: "min(560px, 88dvh)" }}>+ {body}+ </ResponsiveDialog.Body>+ </ResponsiveDialog>+ </Popover>+ );+ }++ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>{trigger}</PopoverTrigger>+ <PopoverContent+ align={align}+ side={side}+ sideOffset={6}+ collisionPadding={PICKER_EDGE_PADDING}+ avoidCollisions+ className="flex flex-col overflow-hidden p-3"+ style={{ width: 360, maxHeight: "min(var(--radix-popover-content-available-height), 520px)" }}+ >+ {body}+ </PopoverContent>+ </Popover>+ );+}++/** Re-export the inline picker (eager) for consumers that already render it+ * inside an existing surface and don't want the popover/lazy wrapper. */+export { IconPickerInline } from "./IconPickerInline";diff --git a/frontend/slices/icon-picker/components/IconPickerInline.test.tsx b/frontend/slices/icon-picker/components/IconPickerInline.test.tsxnew file mode 100644index 00000000..91bb35e1--- /dev/null+++ b/frontend/slices/icon-picker/components/IconPickerInline.test.tsx@@ -0,0 +1,30 @@+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it } from "vitest";+import { IconPickerInline } from "./IconPickerInline";++// The picker is adapted to MSO's presentational Tabs (no TabsContent, no radix+// context). A wrong assumption there only shows up at render time, so render the+// whole inline picker once on the server and assert the tabs actually switch+// panels by value.+describe("IconPickerInline on MSO tabs", () => {+ const render = (value: string) =>+ renderToStaticMarkup(<IconPickerInline value={value} onChange={() => {}} />);++ it("opens the emoji tab for an emoji value and the icon tab for a named icon", () => {+ const emoji = render("🎯");+ const lucide = render("lucide:Star");+ // Variant pills differ per tab: emoji renders Native/Twemoji, icon renders+ // Lucide/Phosphor. The active panel follows the stored value.+ expect(emoji).toContain("Native");+ expect(emoji).toContain("Twemoji");+ expect(lucide).toContain("Phosphor fill");+ expect(lucide).toContain("Search lucide icons");+ });++ it("marks the active tab with a real pressed state, not a radix data attribute", () => {+ const html = render("lucide:Star");+ expect(html).toContain("Emoji");+ expect(html).toContain("Icon");+ expect(html).not.toContain("data-state");+ });+});diff --git a/frontend/slices/icon-picker/components/IconPickerInline.tsx b/frontend/slices/icon-picker/components/IconPickerInline.tsxnew file mode 100644index 00000000..1864d53d--- /dev/null+++ b/frontend/slices/icon-picker/components/IconPickerInline.tsx@@ -0,0 +1,185 @@+"use client";++import * as React from "react";+import { Search } from "lucide-react";+import { Input } from "@/components/ui/input";+import { Tabs } from "@/components/ui/tabs";+import { cn } from "@/lib/utils";+import { parseIconValue } from "../lib/parse";+import { useIconStyle, type Style } from "../lib/style-pref";+import { useRecentIcons } from "../lib/recents";+import { filterEmoji, filterLucide, filterPhosphor } from "../lib/search-haystacks";+import {+ buildPickerHandlers, getSearchPlaceholder, handleGridArrowKey,+ type TopTab, type IconVariant,+} from "../lib/picker-handlers";+import { PickerToolbar, VariantPills } from "./picker-parts/Toolbar";+import { ColorRow } from "./picker-parts/ColorRow";++// Per-tab code-split. EmojiTab carries the emoji catalog (~600 strings);+// IconTab carries the lucide + phosphor icon component imports (~440+// named imports). Splitting per tab means the user only downloads the+// catalog for the tab they actually open.+const EmojiTab = React.lazy(() =>+ import("./picker-parts/EmojiTab").then((m) => ({ default: m.EmojiTab })),+);+const IconTab = React.lazy(() =>+ import("./picker-parts/IconTab").then((m) => ({ default: m.IconTab })),+);++function TabFallback() {+ return (+ <div className="flex h-full min-h-0 flex-1 items-center justify-center text-xs text-muted-foreground">+ Loading…+ </div>+ );+}++export interface IconPickerInlineProps {+ value: string | null | undefined;+ /** Fired on every value change — icon pick, color pick, clear. */+ onChange: (next: string) => void;+ onClear?: () => void;+ /** Fired ONLY on icon-pick events (emoji / lucide / phosphor / recent /+ * random / clear). NOT fired on color pick. */+ onSelect?: () => void;+ className?: string;+}++/** Inline picker.+ *+ * Top tabs: Emoji | Icon. Sub-variant pills per tab:+ * - Emoji → Native | Twemoji (switches global `iconStyle` pref)+ * - Icon → Lucide (stroke) | Phosphor (fill)+ *+ * ColorRow shows on the Icon tab (lucide + phosphor both accept color).+ *+ * Perf contract: ONE `useIconStyle` here, propagated as a prop to every+ * cell via `RawIcon` (zero per-cell hooks). Grids use+ * `content-visibility: auto` for free row windowing. Search filter runs+ * in `startTransition` over a precomputed haystack. Panels are mounted only+ * for the active tab because MSO's Tabs has no TabsContent. */+export function IconPickerInline({ value, onChange, onClear, onSelect, className }: IconPickerInlineProps) {+ const parsed = parseIconValue(value);+ const initialTab: TopTab = parsed.kind === "lucide" || parsed.kind === "phosphor" ? "icon" : "emoji";+ const initialIconVariant: IconVariant = parsed.kind === "phosphor" ? "phosphor" : "lucide";++ const [tab, setTab] = React.useState<TopTab>(initialTab);+ const [iconVariant, setIconVariant] = React.useState<IconVariant>(initialIconVariant);+ const [queryInput, setQueryInput] = React.useState("");+ const [query, setQuery] = React.useState("");+ const [isPending, startTransition] = React.useTransition();+ const [iconStyle, setIconStyle] = useIconStyle();+ const recents = useRecentIcons();++ const colorEnabled = tab === "icon";+ const currentColor =+ colorEnabled && (parsed.kind === "lucide" || parsed.kind === "phosphor")+ ? parsed.color+ : undefined;++ React.useEffect(() => {+ startTransition(() => setQuery(queryInput.trim().toLowerCase()));+ }, [queryInput]);++ const filteredEmoji = React.useMemo(() => filterEmoji(query), [query]);+ const filteredLucide = React.useMemo(() => filterLucide(query), [query]);+ const filteredPhosphor = React.useMemo(() => filterPhosphor(query), [query]);++ const activeValue = value ?? "";++ const handlers = buildPickerHandlers({+ parsed, tab, iconVariant, currentColor, colorEnabled,+ onChange, onClear, onSelect, currentValue: activeValue,+ });++ const gridRef = React.useRef<HTMLDivElement | null>(null);+ const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => handleGridArrowKey(e, gridRef);++ return (+ <div+ className={cn("flex h-full min-h-0 w-full flex-col gap-3", className)}+ onKeyDown={onKeyDown}+ ref={gridRef}+ >+ <Tabs className="flex min-h-0 w-full flex-1 flex-col">+ <PickerToolbar tab={tab} onTabChange={setTab} onRandom={handlers.pickRandom} onClear={onClear ? handlers.handleClear : undefined} />++ <div className="mt-2 flex shrink-0 items-center gap-2">+ {tab === "emoji" ? (+ <VariantPills+ value={iconStyle}+ onChange={(v: Style) => setIconStyle(v)}+ options={[+ { value: "native", label: "Native", hint: "Render with the OS emoji font" },+ { value: "twemoji", label: "Twemoji", hint: "Render with Twemoji SVG (Notion-style, consistent across devices)" },+ ]}+ />+ ) : (+ <VariantPills+ value={iconVariant}+ onChange={(v: IconVariant) => setIconVariant(v)}+ options={[+ { value: "lucide", label: "Lucide", hint: "Outline icons (stroke)" },+ { value: "phosphor", label: "Phosphor fill", hint: "Filled icons (solid) — uses chosen color" },+ ]}+ />+ )}+ </div>++ {colorEnabled && (+ <div className="mt-2 shrink-0">+ <ColorRow currentColor={currentColor} onPick={handlers.pickColor} />+ </div>+ )}++ <div className="relative mt-2 shrink-0">+ <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />+ <Input+ placeholder={getSearchPlaceholder(tab, iconVariant, iconStyle)}+ value={queryInput}+ onChange={(e) => setQueryInput(e.target.value)}+ className={cn("pl-7 h-8 text-sm", isPending && "opacity-80")}+ aria-busy={isPending}+ />+ </div>++ {tab === "emoji" ? (+ <div className="mt-2 flex flex-col flex-1 min-h-0">+ <React.Suspense fallback={<TabFallback />}>+ <EmojiTab+ filtered={filteredEmoji}+ parsed={parsed}+ iconStyle={iconStyle}+ recents={recents}+ activeValue={activeValue}+ onPickEmoji={handlers.pickEmoji}+ onPickRecent={handlers.pickRecent}+ />+ </React.Suspense>+ </div>+ ) : (+ <div className="mt-2 flex flex-col flex-1 min-h-0">+ <React.Suspense fallback={<TabFallback />}>+ <IconTab+ variant={iconVariant}+ filteredLucide={filteredLucide}+ filteredPhosphor={filteredPhosphor}+ parsed={parsed}+ iconStyle={iconStyle}+ currentColor={currentColor}+ recents={recents}+ activeValue={activeValue}+ onPickLucide={handlers.pickLucide}+ onPickPhosphor={handlers.pickPhosphor}+ onPickRecent={handlers.pickRecent}+ />+ </React.Suspense>+ </div>+ )}+ </Tabs>+ </div>+ );+}++export default IconPickerInline;diff --git a/frontend/slices/icon-picker/components/PickerSkeleton.tsx b/frontend/slices/icon-picker/components/PickerSkeleton.tsxnew file mode 100644index 00000000..7c869562--- /dev/null+++ b/frontend/slices/icon-picker/components/PickerSkeleton.tsx@@ -0,0 +1,46 @@+/** Layout-matching skeleton shown while the lazy-loaded picker body+ * hydrates. Dimensions mirror IconPickerInline so the popover doesn't+ * shift size when Suspense resolves.+ *+ * Pure CSS — no animation library dep. The `animate-pulse` utility+ * comes from Tailwind (used widely elsewhere in the codebase). */+export function PickerSkeleton() {+ return (+ <div className="w-full space-y-3" aria-busy aria-label="Loading icon picker">+ {/* Toolbar row */}+ <div className="flex items-center gap-2">+ <div className="h-8 w-24 rounded bg-muted/60 animate-pulse" />+ <div className="ml-auto h-8 w-20 rounded bg-muted/60 animate-pulse" />+ </div>++ {/* Color row */}+ <div className="flex items-center gap-1.5">+ <div className="h-3 w-10 rounded bg-muted/40 animate-pulse" />+ {Array.from({ length: 10 }).map((_, i) => (+ <div key={i} className="h-5 w-5 rounded-full bg-muted/60 animate-pulse" />+ ))}+ </div>++ {/* Search box */}+ <div className="h-8 w-full rounded bg-muted/40 animate-pulse" />++ {/* Grid sections */}+ <div className="space-y-3 overflow-hidden" style={{ height: "16rem" }}>+ {Array.from({ length: 3 }).map((_, sec) => (+ <div key={sec} className="space-y-1">+ <div className="h-3 w-20 rounded bg-muted/40 animate-pulse" />+ <div className="grid grid-cols-8 gap-1">+ {Array.from({ length: 24 }).map((_, i) => (+ <div+ key={i}+ className="h-8 w-8 rounded bg-muted/50 animate-pulse"+ style={{ animationDelay: `${(sec * 24 + i) * 8}ms` }}+ />+ ))}+ </div>+ </div>+ ))}+ </div>+ </div>+ );+}diff --git a/frontend/slices/icon-picker/components/picker-parts/ColorRow.tsx b/frontend/slices/icon-picker/components/picker-parts/ColorRow.tsxnew file mode 100644index 00000000..5840b8ab--- /dev/null+++ b/frontend/slices/icon-picker/components/picker-parts/ColorRow.tsx@@ -0,0 +1,42 @@+import { Button } from "@/components/ui/button";+import { cn } from "@/lib/utils";+import { ICON_COLORS } from "../../lib/colors";++export function ColorRow({+ currentColor, onPick,+}: {+ currentColor: string | undefined;+ onPick: (hex: string) => void;+}) {+ return (+ <div className="mt-2 flex items-center gap-1.5">+ <span className="text-[10px] uppercase tracking-wider text-muted-foreground mr-1">Color</span>+ {ICON_COLORS.map((c) => {+ const isSelected =+ (c.hex === "" && !currentColor) ||+ (c.hex !== "" && currentColor?.toLowerCase() === c.hex.toLowerCase());+ return (+ <Button+ key={c.id}+ type="button"+ variant="ghost"+ size="icon"+ onClick={() => onPick(c.hex)}+ className={cn(+ "h-5 w-5 rounded-full border p-0",+ isSelected ? "ring-2 ring-primary/60 ring-offset-2 ring-offset-background" : "",+ )}+ style={{+ backgroundColor: c.hex || "transparent",+ borderColor: c.hex ? c.hex : "var(--border)",+ }}+ title={c.label}+ aria-label={`Color: ${c.label}`}+ >+ {!c.hex && <span className="block text-[10px] leading-none">∅</span>}+ </Button>+ );+ })}+ </div>+ );+}diff --git a/frontend/slices/icon-picker/components/picker-parts/EmojiTab.tsx b/frontend/slices/icon-picker/components/picker-parts/EmojiTab.tsxnew file mode 100644index 00000000..070c6a77--- /dev/null+++ b/frontend/slices/icon-picker/components/picker-parts/EmojiTab.tsx@@ -0,0 +1,71 @@+"use client";++import { EMOJI_GROUPS } from "../../lib/emoji-catalog";+import type { Style } from "../../lib/style-pref";+import type { IconValue } from "../../lib/parse";+import { EmojiCell, Grid, Empty } from "./cells";+import { RecentsSection, Section } from "./Sections";++export interface EmojiTabProps {+ filtered: string[] | null;+ parsed: IconValue;+ iconStyle: Style;+ recents: readonly string[];+ activeValue: string;+ onPickEmoji: (e: string) => void;+ onPickRecent: (v: string) => void;+}++export function EmojiTab({+ filtered,+ parsed,+ iconStyle,+ recents,+ activeValue,+ onPickEmoji,+ onPickRecent,+}: EmojiTabProps) {+ return (+ <div className="h-full min-h-0 flex-1 overflow-y-auto pr-2">+ {filtered ? (+ <Grid>+ {filtered.length === 0 ? <Empty /> : filtered.map((e, i) => (+ <EmojiCell+ key={`f-${e}-${i}`}+ emoji={e}+ style={iconStyle}+ active={parsed.kind === "emoji" && parsed.emoji === e}+ onClick={() => onPickEmoji(e)}+ tabIndex={i === 0 ? 0 : -1}+ index={i}+ />+ ))}+ </Grid>+ ) : (+ <div className="space-y-3">+ {recents.length > 0 && (+ <RecentsSection+ recents={recents}+ style={iconStyle}+ activeValue={activeValue}+ onPick={onPickRecent}+ />+ )}+ {EMOJI_GROUPS.map((g) => (+ <Section key={g.id} label={g.label}>+ {g.items.map((e, i) => (+ <EmojiCell+ key={`${g.id}-${e}-${i}`}+ emoji={e}+ style={iconStyle}+ active={parsed.kind === "emoji" && parsed.emoji === e}+ onClick={() => onPickEmoji(e)}+ />+ ))}+ </Section>+ ))}+ </div>+ )}+ </div>+ );+}diff --git a/frontend/slices/icon-picker/components/picker-parts/IconTab.tsx b/frontend/slices/icon-picker/components/picker-parts/IconTab.tsxnew file mode 100644index 00000000..4862e0ef--- /dev/null+++ b/frontend/slices/icon-picker/components/picker-parts/IconTab.tsx@@ -0,0 +1,146 @@+"use client";++import { LUCIDE_GROUPS } from "../../lib/lucide-catalog";+import { PHOSPHOR_GROUPS } from "../../lib/phosphor-catalog";+import type { Style } from "../../lib/style-pref";+import type { IconValue } from "../../lib/parse";+import { LucideCell, PhosphorCell, Grid, Empty } from "./cells";+import { RecentsSection, Section } from "./Sections";++export interface IconTabProps {+ variant: "lucide" | "phosphor";+ filteredLucide: string[] | null;+ filteredPhosphor: string[] | null;+ parsed: IconValue;+ iconStyle: Style;+ currentColor: string | undefined;+ recents: readonly string[];+ activeValue: string;+ onPickLucide: (n: string) => void;+ onPickPhosphor: (n: string) => void;+ onPickRecent: (v: string) => void;+}++/** Combined Lucide + Phosphor tab. Branches on `variant`. ScrollArea+ * uses `h-full min-h-0 flex-1` so the flex column in IconPickerInline+ * drives final height — works inside popover (capped by Radix avail-+ * height var) AND inside dialog fallback (capped by dialog max-h). */+export function IconTab({+ variant,+ filteredLucide,+ filteredPhosphor,+ parsed,+ iconStyle,+ currentColor,+ recents,+ activeValue,+ onPickLucide,+ onPickPhosphor,+ onPickRecent,+}: IconTabProps) {+ return (+ <div className="h-full min-h-0 flex-1 overflow-y-auto pr-2">+ {variant === "lucide"+ ? renderLucide({ filteredLucide, parsed, iconStyle, currentColor, recents, activeValue, onPickLucide, onPickRecent })+ : renderPhosphor({ filteredPhosphor, parsed, iconStyle, currentColor, recents, activeValue, onPickPhosphor, onPickRecent })}+ </div>+ );+}++function renderLucide({+ filteredLucide, parsed, iconStyle, currentColor, recents, activeValue, onPickLucide, onPickRecent,+}: Pick<IconTabProps, "filteredLucide" | "parsed" | "iconStyle" | "currentColor" | "recents" | "activeValue" | "onPickLucide" | "onPickRecent">) {+ if (filteredLucide) {+ return (+ <Grid>+ {filteredLucide.length === 0 ? <Empty /> : filteredLucide.map((n, i) => (+ <LucideCell+ key={`fl-${n}`}+ name={n}+ color={currentColor}+ style={iconStyle}+ active={parsed.kind === "lucide" && parsed.name === n}+ onClick={() => onPickLucide(n)}+ tabIndex={i === 0 ? 0 : -1}+ index={i}+ />+ ))}+ </Grid>+ );+ }+ return (+ <div className="space-y-3">+ {recents.length > 0 && (+ <RecentsSection+ recents={recents}+ style={iconStyle}+ activeValue={activeValue}+ onPick={onPickRecent}+ />+ )}+ {LUCIDE_GROUPS.map((g) => (+ <Section key={g.id} label={g.label}>+ {g.items.map((n) => (+ <LucideCell+ key={`${g.id}-${n}`}+ name={n}+ color={currentColor}+ style={iconStyle}+ active={parsed.kind === "lucide" && parsed.name === n}+ onClick={() => onPickLucide(n)}+ />+ ))}+ </Section>+ ))}+ </div>+ );+}++function renderPhosphor({+ filteredPhosphor, parsed, iconStyle, currentColor, recents, activeValue, onPickPhosphor, onPickRecent,+}: Pick<IconTabProps, "filteredPhosphor" | "parsed" | "iconStyle" | "currentColor" | "recents" | "activeValue" | "onPickPhosphor" | "onPickRecent">) {+ if (filteredPhosphor) {+ return (+ <Grid>+ {filteredPhosphor.length === 0 ? <Empty /> : filteredPhosphor.map((n, i) => (+ <PhosphorCell+ key={`fp-${n}`}+ name={n}+ color={currentColor}+ style={iconStyle}+ active={parsed.kind === "phosphor" && parsed.name === n}+ onClick={() => onPickPhosphor(n)}+ tabIndex={i === 0 ? 0 : -1}+ index={i}+ />+ ))}+ </Grid>+ );+ }+ return (+ <div className="space-y-3">+ {recents.length > 0 && (+ <RecentsSection+ recents={recents}+ style={iconStyle}+ activeValue={activeValue}+ onPick={onPickRecent}+ />+ )}+ {PHOSPHOR_GROUPS.map((g) => (+ <Section key={`p-${g.id}`} label={g.label}>+ {g.items.map((n) => (+ <PhosphorCell+ key={`p-${g.id}-${n}`}+ name={n}+ color={currentColor}+ style={iconStyle}+ active={parsed.kind === "phosphor" && parsed.name === n}+ onClick={() => onPickPhosphor(n)}+ />+ ))}+ </Section>+ ))}+ </div>+ );+}diff --git a/frontend/slices/icon-picker/components/picker-parts/Sections.tsx b/frontend/slices/icon-picker/components/picker-parts/Sections.tsxnew file mode 100644index 00000000..3e3b5f28--- /dev/null+++ b/frontend/slices/icon-picker/components/picker-parts/Sections.tsx@@ -0,0 +1,35 @@+"use client";++import * as React from "react";+import { Grid, RecentCell } from "./cells";+import type { Style } from "../../lib/style-pref";++export function Section({ label, children }: { label: string; children: React.ReactNode }) {+ return (+ <section>+ <h4 className="mb-1 px-1 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">{label}</h4>+ <Grid>{children}</Grid>+ </section>+ );+}++export function RecentsSection({+ recents, style, activeValue, onPick,+}: { recents: readonly string[]; style: Style; activeValue: string; onPick: (v: string) => void }) {+ return (+ <section>+ <h4 className="mb-1 px-1 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">Recent</h4>+ <Grid>+ {recents.map((v, i) => (+ <RecentCell+ key={`r-${v}-${i}`}+ value={v}+ style={style}+ active={v === activeValue}+ onClick={() => onPick(v)}+ />+ ))}+ </Grid>+ </section>+ );+}diff --git a/frontend/slices/icon-picker/components/picker-parts/Toolbar.tsx b/frontend/slices/icon-picker/components/picker-parts/Toolbar.tsxnew file mode 100644index 00000000..10517b7f--- /dev/null+++ b/frontend/slices/icon-picker/components/picker-parts/Toolbar.tsx@@ -0,0 +1,87 @@+import { Smile, Shapes, Trash2, Shuffle } from "lucide-react";+import { Button } from "@/components/ui/button";+import { TabsList, TabsTrigger } from "@/components/ui/tabs";++/** Top tabs. MSO's tabs primitive is presentational — the parent owns `tab`+ * and passes `onTabChange`, so there is no radix context to depend on. */+export function PickerToolbar({+ tab, onTabChange, onRandom, onClear,+}: {+ tab: "emoji" | "icon";+ onTabChange: (next: "emoji" | "icon") => void;+ onRandom: () => void;+ onClear?: () => void;+}) {+ return (+ <div className="flex items-center gap-2">+ <TabsList className="h-8">+ <TabsTrigger active={tab === "emoji"} onClick={() => onTabChange("emoji")} className="h-7 text-xs gap-1">+ <Smile className="h-3.5 w-3.5" /> Emoji+ </TabsTrigger>+ <TabsTrigger active={tab === "icon"} onClick={() => onTabChange("icon")} className="h-7 text-xs gap-1">+ <Shapes className="h-3.5 w-3.5" /> Icon+ </TabsTrigger>+ </TabsList>+ <div className="ml-auto flex items-center gap-1">+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="h-7 px-2 text-xs"+ onClick={onRandom}+ title="Random"+ >+ <Shuffle className="h-3.5 w-3.5" />+ </Button>+ {onClear && (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="h-7 px-2 text-xs text-muted-foreground"+ onClick={onClear}+ title="Remove icon"+ >+ <Trash2 className="h-3.5 w-3.5" />+ </Button>+ )}+ </div>+ </div>+ );+}++/** Variant pills shown under the top tabs. Two values per tab:+ * - emoji tab → "native" | "twemoji"+ * - icon tab → "lucide" | "phosphor" */+export function VariantPills<T extends string>({+ value, onChange, options,+}: {+ value: T;+ onChange: (next: T) => void;+ options: ReadonlyArray<{ value: T; label: string; hint?: string }>;+}) {+ return (+ <div className="flex h-7 w-full items-center gap-0.5 rounded-md border border-border bg-muted/30 p-0.5">+ {options.map((opt) => {+ const active = opt.value === value;+ return (+ <Button+ key={opt.value}+ type="button"+ variant="ghost"+ onClick={() => onChange(opt.value)}+ title={opt.hint}+ className={+ "flex h-auto h-6 flex-1 items-center justify-center rounded-[5px] px-2 text-[11px] font-medium transition " ++ (active+ ? "bg-background text-foreground shadow-sm"+ : "text-muted-foreground hover:text-foreground")+ }+ >+ {opt.label}+ </Button>+ );+ })}+ </div>+ );+}diff --git a/frontend/slices/icon-picker/components/picker-parts/cells.tsx b/frontend/slices/icon-picker/components/picker-parts/cells.tsxnew file mode 100644index 00000000..514ef01b--- /dev/null+++ b/frontend/slices/icon-picker/components/picker-parts/cells.tsx@@ -0,0 +1,162 @@+import * as React from "react";+import { cn } from "@/lib/utils";+import { Button } from "@/components/ui/button";+import { lucideValue, phosphorValue } from "../../lib/parse";+import { RawIcon } from "../DynamicIcon";+import type { Style } from "../../lib/style-pref";++/** 8-col grid with `content-visibility:auto` so the browser can skip+ * rendering offscreen rows entirely. `contain-intrinsic-size` keeps+ * the scroll height stable while content is skipped. Combined with+ * one section per category, this approximates virtualization without+ * any JS-side measurement. */+export function Grid({ children }: { children: React.ReactNode }) {+ return (+ <div+ className="grid grid-cols-8 gap-1"+ style={{ contentVisibility: "auto", containIntrinsicSize: "0 320px" } as React.CSSProperties}+ >+ {children}+ </div>+ );+}++interface CellProps {+ active: boolean;+ onClick: () => void;+ onMouseEnter?: () => void;+ tabIndex?: number;+ /** Set by the picker once it knows the cell's index, so keyboard nav+ * can walk siblings via the data attribute. */+ index?: number;+}++interface EmojiCellProps extends CellProps {+ emoji: string;+ style: Style;+}++function EmojiCellImpl({ emoji, active, onClick, onMouseEnter, tabIndex, index, style }: EmojiCellProps) {+ return (+ <Button+ type="button"+ variant="ghost"+ size="icon"+ onClick={onClick}+ onMouseEnter={onMouseEnter}+ tabIndex={tabIndex}+ data-icon-cell-index={index}+ className={cn(+ "flex h-auto h-8 w-8 items-center justify-center rounded text-lg leading-none transition",+ active ? "bg-primary/15 ring-1 ring-primary" : "hover:bg-accent",+ )}+ title={emoji}+ aria-label={`Pick ${emoji}`}+ >+ <RawIcon value={emoji} style={style} className="text-lg" />+ </Button>+ );+}++export const EmojiCell = React.memo(EmojiCellImpl);++interface LucideCellProps extends CellProps {+ name: string;+ color: string | undefined;+ style: Style;+}++function LucideCellImpl({ name, color, active, onClick, onMouseEnter, tabIndex, index, style }: LucideCellProps) {+ const value = React.useMemo(() => lucideValue(name, color), [name, color]);+ return (+ <Button+ type="button"+ variant="ghost"+ size="icon"+ onClick={onClick}+ onMouseEnter={onMouseEnter}+ tabIndex={tabIndex}+ data-icon-cell-index={index}+ className={cn(+ "flex h-auto h-8 w-8 items-center justify-center rounded text-lg leading-none transition",+ active ? "bg-primary/15 ring-1 ring-primary" : "hover:bg-accent",+ )}+ title={name}+ aria-label={`Pick ${name}`}+ >+ <RawIcon value={value} style={style} className="text-lg" />+ </Button>+ );+}++export const LucideCell = React.memo(LucideCellImpl);++interface PhosphorCellProps extends CellProps {+ name: string;+ color: string | undefined;+ style: Style;+}++function PhosphorCellImpl({ name, color, active, onClick, onMouseEnter, tabIndex, index, style }: PhosphorCellProps) {+ const value = React.useMemo(() => phosphorValue(name, color), [name, color]);+ return (+ <Button+ type="button"+ variant="ghost"+ size="icon"+ onClick={onClick}+ onMouseEnter={onMouseEnter}+ tabIndex={tabIndex}+ data-icon-cell-index={index}+ className={cn(+ "flex h-auto h-8 w-8 items-center justify-center rounded text-lg leading-none transition",+ active ? "bg-primary/15 ring-1 ring-primary" : "hover:bg-accent",+ )}+ title={name}+ aria-label={`Pick ${name}`}+ >+ <RawIcon value={value} style={style} className="text-lg" />+ </Button>+ );+}++export const PhosphorCell = React.memo(PhosphorCellImpl);++/** Renders a recent entry — value may be either emoji or `lucide:Name`,+ * with optional color suffix. */+interface RecentCellProps extends CellProps {+ value: string;+ style: Style;+}++function RecentCellImpl({ value, active, onClick, onMouseEnter, tabIndex, index, style }: RecentCellProps) {+ return (+ <Button+ type="button"+ variant="ghost"+ size="icon"+ onClick={onClick}+ onMouseEnter={onMouseEnter}+ tabIndex={tabIndex}+ data-icon-cell-index={index}+ className={cn(+ "flex h-auto h-8 w-8 items-center justify-center rounded text-lg leading-none transition",+ active ? "bg-primary/15 ring-1 ring-primary" : "hover:bg-accent",+ )}+ title={value}+ aria-label={`Pick recent ${value}`}+ >+ <RawIcon value={value} style={style} className="text-lg" />+ </Button>+ );+}++export const RecentCell = React.memo(RecentCellImpl);++export function Empty() {+ return (+ <div className="col-span-full py-6 text-center text-xs text-muted-foreground">+ No matches.+ </div>+ );+}diff --git a/frontend/slices/icon-picker/index.ts b/frontend/slices/icon-picker/index.tsnew file mode 100644index 00000000..00d38cf2--- /dev/null+++ b/frontend/slices/icon-picker/index.ts@@ -0,0 +1,24 @@+/** Public barrel for the icon-picker slice.+ *+ * Deliberately narrow: the catalogs (~600 emoji, ~250 lucide, ~190 phosphor+ * components) are reachable only through the lazy picker body, so importing+ * `<DynamicIcon>` or `<IconPickerPopover>` does not drag them into a caller's+ * eager chunk. Render `<DynamicIcon value>` anywhere, `<IconPickerPopover>`+ * to let users pick. Values are `emoji:<char> | lucide:<Name> | phosphor:<Name>`+ * with an optional `?c=<hex>` tint. */++export { DynamicIcon, RawIcon, DEFAULT_ICON_SIZE } from "./components/DynamicIcon";+export { IconPickerPopover, IconPickerInline } from "./components/IconPicker";+export { PickerSkeleton } from "./components/PickerSkeleton";++export {+ parseIconValue,+ isLucideValue,+ isPhosphorValue,+ lucideValue,+ phosphorValue,+ withColor,+ LUCIDE_PREFIX,+ PHOSPHOR_PREFIX,+ type IconValue,+} from "./lib/parse";diff --git a/frontend/slices/icon-picker/lib/colors.ts b/frontend/slices/icon-picker/lib/colors.tsnew file mode 100644index 00000000..b351f7d3--- /dev/null+++ b/frontend/slices/icon-picker/lib/colors.ts@@ -0,0 +1,21 @@+/** Notion-style color palette. Hex values aren't copyrightable; this+ * matches Notion's named colors so users get familiar choices. */++export interface IconColor {+ id: string;+ label: string;+ hex: string;+}++export const ICON_COLORS: IconColor[] = [+ { id: "default", label: "Default", hex: "" }, // empty = inherit currentColor+ { id: "gray", label: "Gray", hex: "#9b9a97" },+ { id: "brown", label: "Brown", hex: "#64473a" },+ { id: "orange", label: "Orange", hex: "#d9730d" },+ { id: "yellow", label: "Yellow", hex: "#dfab01" },+ { id: "green", label: "Green", hex: "#0f7b6c" },+ { id: "blue", label: "Blue", hex: "#0b6e99" },+ { id: "purple", label: "Purple", hex: "#6940a5" },+ { id: "pink", label: "Pink", hex: "#ad1a72" },+ { id: "red", label: "Red", hex: "#e03e3e" },+];diff --git a/frontend/slices/icon-picker/lib/emoji-catalog.ts b/frontend/slices/icon-picker/lib/emoji-catalog.tsnew file mode 100644index 00000000..816eecb6--- /dev/null+++ b/frontend/slices/icon-picker/lib/emoji-catalog.ts@@ -0,0 +1,109 @@+/** Notion-style emoji catalog. Curated, not exhaustive. Stored as raw+ * emoji string in `icon` field — backwards-compatible with existing pages. */++export interface EmojiGroup {+ id: string;+ label: string;+ items: string[];+}++export const EMOJI_GROUPS: EmojiGroup[] = [+ {+ id: "smileys",+ label: "Smileys",+ items: [+ "😀","😃","😄","😁","😆","😅","🤣","😂","🙂","🙃","😉","😊",+ "😇","🥰","😍","🤩","😘","😗","☺️","😚","😙","🥲","😋","😛",+ "😜","🤪","😝","🤑","🤗","🤭","🤫","🤔","🤐","🤨","😐","😑",+ "😶","😏","😒","🙄","😬","🤥","😌","😔","😪","🤤","😴","🤒",+ "🤕","🤧","🥵","🥶","🥴","😵","🤯","🤠","🥳","🥸","😎","🤓",+ ],+ },+ {+ id: "people",+ label: "People",+ items: [+ "👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘",+ "🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛",+ "🤜","👏","🙌","👐","🤲","🤝","🙏","✍️","💅","🤳","💪","🦾",+ "🦵","🦿","🦶","👂","🦻","👃","🧠","🫀","🫁","🦷","🦴","👀",+ ],+ },+ {+ id: "objects",+ label: "Objects",+ items: [+ "📄","📝","📚","📖","📓","📔","📕","📗","📘","📙","📒","📑",+ "📰","🗞️","🗒️","🗓️","📅","📆","🗂️","📂","📁","🗃️","🗄️","📊",+ "📈","📉","📋","🧾","🔖","🏷️","💼","🎯","🧩","🧠","💡","🔦",+ "🕯️","🪔","🧪","🧫","🧬","🔬","🔭","📡","💻","🖥️","⌨️","🖱️",+ "🖨️","📱","☎️","📞","📟","📠","📺","📻","🎙️","🎚️","🎛️","🧰",+ "🛠️","⚙️","🔧","🔨","🪛","🪜","🧲","🔌","🔋","💎","🪙","💰",+ ],+ },+ {+ id: "nature",+ label: "Nature",+ items: [+ "🌱","🌿","🍀","🍃","🌴","🌳","🌲","🪵","🌵","🌾","💐","🌸",+ "🌷","🌹","🥀","🌺","🌻","🌼","🌞","🌝","🌚","🌙","🌛","🌜",+ "⭐","🌟","✨","⚡","☄️","🌈","☀️","🌤️","⛅","🌥️","☁️","🌦️",+ "🌧️","⛈️","🌩️","🌨️","❄️","⛄","🔥","💧","🌊","🌍","🌎","🌏",+ ],+ },+ {+ id: "food",+ label: "Food",+ items: [+ "🍏","🍎","🍐","🍊","🍋","🍌","🍉","🍇","🍓","🫐","🍈","🍒",+ "🍑","🥭","🍍","🥥","🥝","🍅","🍆","🥑","🥦","🥬","🥒","🌶️",+ "🌽","🥕","🥔","🍠","🍞","🥐","🥖","🫓","🥨","🥯","🧀","🥓",+ "🍔","🍟","🍕","🌭","🥪","🌮","🌯","🥙","🍝","🍜","🍲","🍛",+ "🍣","🍱","🥟","🍤","🍙","🍘","🍥","🥮","🍢","🍡","🍧","🍨",+ "🍦","🥧","🧁","🍰","🎂","🍮","🍭","🍬","🍫","🍿","🍩","🍪",+ "☕","🍵","🍶","🍾","🍷","🍸","🍹","🍺","🍻","🥂","🥃","🥤",+ ],+ },+ {+ id: "activity",+ label: "Activity",+ items: [+ "⚽","🏀","🏈","⚾","🥎","🎾","🏐","🏉","🥏","🎱","🪀","🏓",+ "🏸","🏒","🏑","🥍","🏏","🪃","🥅","⛳","🪁","🏹","🎣","🤿",+ "🥊","🥋","🎽","🛹","🛼","🛷","⛸️","🥌","🎿","⛷️","🏂","🪂",+ "🏋️","🤼","🤸","⛹️","🤺","🤾","🏌️","🏇","🧘","🏄","🏊","🤽",+ "🚣","🧗","🚵","🚴","🏆","🥇","🥈","🥉","🏅","🎖️","🏵️","🎗️",+ "🎫","🎟️","🎪","🤹","🎭","🩰","🎨","🎬","🎤","🎧","🎼","🎹",+ ],+ },+ {+ id: "travel",+ label: "Travel",+ items: [+ "🚗","🚕","🚙","🚌","🚎","🏎️","🚓","🚑","🚒","🚐","🛻","🚚",+ "🚛","🚜","🛵","🏍️","🛺","🚲","🛴","🛹","🚨","🚔","🚍","🚘",+ "🚖","🚡","🚠","🚟","🚃","🚋","🚞","🚝","🚄","🚅","🚈","🚂",+ "✈️","🛫","🛬","🛩️","💺","🚁","🚟","🛸","🚀","🛰️","⛵","🛶",+ "🚤","🛥️","🛳️","⛴️","🚢","⚓","🪝","⛽","🚧","🚦","🚥","🗺️",+ "🗿","🗽","🗼","🏰","🏯","🏟️","🎡","🎢","🎠","⛲","⛱️","🏖️",+ ],+ },+ {+ id: "symbols",+ label: "Symbols",+ items: [+ "❤️","🧡","💛","💚","💙","💜","🤎","🖤","🤍","💔","❣️","💕",+ "💞","💓","💗","💖","💘","💝","💟","☮️","✝️","☪️","🕉️","☸️",+ "✡️","🔯","🕎","☯️","☦️","🛐","⛎","♈","♉","♊","♋","♌",+ "♍","♎","♏","♐","♑","♒","♓","🆔","⚛️","🉑","☢️","☣️",+ "📴","📳","🈶","🈚","🈸","🈺","🈷️","✴️","🆚","💮","🉐","㊙️",+ "㊗️","🈴","🈵","🈹","🈲","🅰️","🅱️","🆎","🆑","🅾️","🆘","❌",+ "⭕","🛑","⛔","📛","🚫","💯","💢","♨️","🚷","🚯","🚳","🚱",+ "🔞","📵","🚭","❗","❕","❓","❔","‼️","⁉️","🔅","🔆","〽️",+ "⚠️","🚸","🔱","⚜️","🔰","♻️","✅","🈯","💹","❇️","✳️","❎",+ "🌐","💠","Ⓜ️","🌀","💤","🏧","🚾","♿","🅿️","🛗","🈳","🈂️",+ ],+ },+];++export const ALL_EMOJIS: string[] = EMOJI_GROUPS.flatMap((g) => g.items);diff --git a/frontend/slices/icon-picker/lib/emoji-keywords.ts b/frontend/slices/icon-picker/lib/emoji-keywords.tsnew file mode 100644index 00000000..e345c8e6--- /dev/null+++ b/frontend/slices/icon-picker/lib/emoji-keywords.ts@@ -0,0 +1,183 @@+/** Curated keyword index for the emoji catalog. Lets "heart" match "❤️"+ * in search, which a naive `glyph.includes(query)` cannot do because+ * the haystack is the literal codepoint, not a label.+ *+ * Format: emoji → space-separated keyword string (pre-joined so the+ * search hot path is one `includes()` per emoji, no array walking).+ *+ * Not exhaustive — covers the catalog in `emoji-catalog.ts`. Add new+ * keywords here when you add new emojis to the catalog. */++export const EMOJI_KEYWORDS: Record<string, string> = {+ // Smileys+ "😀": "grin happy smile",+ "😃": "grin smile happy",+ "😄": "smile happy joy laugh",+ "😁": "grin beam happy",+ "😆": "laugh squint happy",+ "😅": "sweat smile relief",+ "🤣": "rofl laugh roll floor",+ "😂": "joy laugh tears",+ "🙂": "smile slight",+ "🙃": "upside down smile",+ "😉": "wink",+ "😊": "blush smile happy",+ "😇": "halo angel innocent",+ "🥰": "love smile hearts",+ "😍": "love heart eyes",+ "🤩": "star struck wow",+ "😘": "kiss blow",+ "😗": "kiss",+ "☺️": "smile relax",+ "😚": "kiss closed eyes",+ "😙": "kiss smile",+ "🥲": "smile tear",+ "😋": "yum tongue",+ "😛": "tongue out",+ "😜": "tongue wink",+ "🤪": "zany crazy",+ "😝": "tongue squint",+ "🤑": "money mouth",+ "🤗": "hug",+ "🤭": "hand mouth oops",+ "🤫": "shush quiet",+ "🤔": "think",+ "🤐": "zipper mouth",+ "🤨": "raised brow",+ "😐": "neutral",+ "😑": "expressionless",+ "😶": "no mouth",+ "😏": "smirk",+ "😒": "unamused",+ "🙄": "eye roll",+ "😬": "grimace",+ "🤥": "lying nose",+ "😌": "relieved",+ "😔": "pensive sad",+ "😪": "sleepy",+ "🤤": "drool",+ "😴": "sleep zzz",+ "🤒": "sick thermometer",+ "🤕": "head bandage",+ "🤧": "sneeze",+ "🥵": "hot heat",+ "🥶": "cold freeze",+ "🥴": "woozy",+ "😵": "dizzy",+ "🤯": "explode mind blown",+ "🤠": "cowboy",+ "🥳": "party",+ "🥸": "disguise glasses",+ "😎": "cool sunglasses",+ "🤓": "nerd glasses",+ // Objects (the ones people search for most)+ "📄": "page document file",+ "📝": "memo note write",+ "📚": "books library",+ "📖": "book open read",+ "📓": "notebook",+ "📔": "notebook decorated",+ "📕": "book closed red",+ "📗": "book green",+ "📘": "book blue",+ "📙": "book orange",+ "📒": "ledger yellow",+ "📑": "tabs bookmark",+ "📰": "news paper",+ "🗞️": "newspaper",+ "🗒️": "spiral notepad",+ "🗓️": "spiral calendar",+ "📅": "calendar date",+ "📆": "tear off calendar",+ "🗂️": "card index dividers",+ "📂": "folder open",+ "📁": "folder",+ "🗃️": "card file box",+ "🗄️": "file cabinet",+ "📊": "chart bar",+ "📈": "chart up trend",+ "📉": "chart down",+ "📋": "clipboard",+ "🧾": "receipt",+ "🔖": "bookmark",+ "🏷️": "tag label",+ "💼": "briefcase work",+ "🎯": "target dart goal",+ "🧩": "puzzle",+ "🧠": "brain",+ "💡": "idea light bulb",+ "🔦": "flashlight",+ "🧪": "test tube science",+ "🧫": "petri dish",+ "🧬": "dna",+ "🔬": "microscope",+ "🔭": "telescope",+ "📡": "satellite antenna",+ "💻": "laptop computer",+ "🖥️": "desktop computer",+ "⌨️": "keyboard",+ "🖱️": "mouse",+ "🖨️": "printer",+ "📱": "phone mobile cell",+ "📺": "tv television",+ "🧰": "toolbox",+ "🛠️": "tools",+ "⚙️": "gear settings",+ "🔧": "wrench",+ "🔨": "hammer",+ "🔌": "plug",+ "🔋": "battery",+ "💎": "gem diamond",+ "💰": "money bag",+ // Nature+ "🌱": "seedling plant",+ "🌿": "herb leaves",+ "🍀": "clover luck four leaf",+ "🌴": "palm tree",+ "🌳": "tree",+ "🌲": "evergreen tree",+ "🌸": "cherry blossom flower",+ "🌷": "tulip flower",+ "🌹": "rose flower",+ "🌻": "sunflower",+ "🌞": "sun face",+ "🌙": "moon crescent",+ "⭐": "star",+ "🌟": "glowing star",+ "✨": "sparkles",+ "⚡": "lightning bolt zap",+ "🌈": "rainbow",+ "☀️": "sun sunny",+ "☁️": "cloud",+ "❄️": "snowflake winter cold",+ "🔥": "fire flame hot",+ "💧": "drop water",+ "🌊": "wave water ocean",+ // Symbols (search hot for these)+ "❤️": "heart love red",+ "🧡": "heart orange",+ "💛": "heart yellow",+ "💚": "heart green",+ "💙": "heart blue",+ "💜": "heart purple",+ "🖤": "heart black",+ "🤍": "heart white",+ "💔": "broken heart",+ "✅": "check mark done",+ "❌": "cross x error",+ "⭕": "circle o",+ "🚫": "no prohibited",+ "💯": "hundred 100",+ "⚠️": "warning",+ "❗": "exclamation",+ "❓": "question",+ "♻️": "recycle",+};++/** Build a single concat string for fast `.includes()` lookup. The string+ * is `<glyph> <keywords>` so both glyph match and keyword match resolve+ * in one scan. Lowercased once at module load. */+export function buildEmojiSearchHaystack(emoji: string): string {+ const kw = EMOJI_KEYWORDS[emoji] ?? "";+ return `${emoji} ${kw}`.toLowerCase();+}diff --git a/frontend/slices/icon-picker/lib/icon-render-config.ts b/frontend/slices/icon-picker/lib/icon-render-config.tsnew file mode 100644index 00000000..cd868fa4--- /dev/null+++ b/frontend/slices/icon-picker/lib/icon-render-config.ts@@ -0,0 +1,36 @@+/**+ * SSOT for cross-kind visual sizing.+ *+ * Different icon sources fill their render box at different ratios:+ * - Native emoji → glyph hits ~75% of font-size+ * - Twemoji <img> → SVG asset, padding inside the canvas, ~85% fill+ * - Lucide outline → stroke marks fill ~92% of viewBox (24×24)+ * - Phosphor fill → solid marks fill ~85% of viewBox (256×256)+ *+ * Without compensation, `size={72}` on all four produces visually+ * UNEQUAL icons — lucide looks biggest, emoji smallest. To make the+ * visible mark equal across kinds, we treat the `size` prop as the+ * TARGET MARK size and back-compute the render-box size each+ * primitive needs.+ *+ * Tuned for Notion visual cadence. Consumers can override by+ * re-exporting `ICON_FILL_RATIO` from a wrapper.+ */+export type IconRenderKind = "emoji" | "twemoji" | "lucide" | "phosphor";++export const ICON_FILL_RATIO: Record<IconRenderKind, number> = {+ emoji: 0.75,+ twemoji: 0.85,+ lucide: 0.92,+ phosphor: 0.85,+};++/**+ * Returns the size we should hand to the underlying primitive+ * (font-size for emoji, `<Cmp size>` for lucide/phosphor, `width`+ * attr for twemoji `<img>`) so the visible mark hits `targetMark`+ * pixels regardless of kind.+ */+export function renderSizeFor(kind: IconRenderKind, targetMark: number): number {+ return Math.round(targetMark / ICON_FILL_RATIO[kind]);+}diff --git a/frontend/slices/icon-picker/lib/lucide-catalog.ts b/frontend/slices/icon-picker/lib/lucide-catalog.tsnew file mode 100644index 00000000..87e9b355--- /dev/null+++ b/frontend/slices/icon-picker/lib/lucide-catalog.ts@@ -0,0 +1,118 @@+/** Curated subset of lucide icons grouped by category. Names match the+ * exported PascalCase symbols from `lucide-react`. The `lucide:` prefix is+ * added when stored in the page `icon` field — see `parseIconValue`. */++export interface LucideGroup {+ id: string;+ label: string;+ items: string[];+}++export const LUCIDE_GROUPS: LucideGroup[] = [+ {+ id: "general",+ label: "General",+ items: [+ "Home","Star","Heart","Bookmark","Flag","Tag","Settings","HelpCircle",+ "Info","Bell","Eye","EyeOff","Lock","Unlock","Key","Pin","MapPin","Map",+ "Globe","Compass","Award","Crown","Gem","Sparkles","Zap","Flame","Trophy",+ ],+ },+ {+ id: "files",+ label: "Files",+ items: [+ "File","FileText","FileCode","FileImage","FileVideo","FileAudio","FileSpreadsheet",+ "FileArchive","FileQuestion","Files","Folder","FolderOpen","FolderKanban","FolderPlus",+ "FolderTree","Archive","Box","Boxes","Package","Layers","Inbox","Trash","Trash2",+ "Save","Download","Upload","Paperclip","Image","Images",+ ],+ },+ {+ id: "communication",+ label: "Communication",+ items: [+ "Mail","MailOpen","MessageCircle","MessageSquare","Send","AtSign","Phone","PhoneCall",+ "Video","VideoOff","Mic","MicOff","Volume2","BellRing","Megaphone","Share","Share2",+ "Link","ExternalLink","Rss","Hash","Reply",+ ],+ },+ {+ id: "productivity",+ label: "Productivity",+ items: [+ "CheckSquare","Square","ListChecks","ListTodo","ClipboardList","ClipboardCheck",+ "Calendar","CalendarDays","CalendarCheck","Clock","Timer","AlarmClock","Hourglass",+ "Bookmark","BookOpen","Book","Library","Notebook","NotebookPen","StickyNote",+ "PenTool","Pencil","Edit","Edit3","Highlighter","Eraser",+ ],+ },+ {+ id: "data",+ label: "Data",+ items: [+ "Database","Table","Table2","LayoutGrid","LayoutList","List","Kanban","Columns",+ "Rows","BarChart","BarChart2","BarChart3","LineChart","PieChart","TrendingUp",+ "TrendingDown","Activity","Sigma","Calculator","Hash","Percent","Binary",+ ],+ },+ {+ id: "development",+ label: "Development",+ items: [+ "Code","Code2","Terminal","Braces","Brackets","GitBranch","GitMerge","GitPullRequest",+ "GitCommit","Server","Cpu","HardDrive","MemoryStick","Bug","Wrench","Hammer",+ "Cog","Workflow","Webhook","Cloud","CloudUpload","CloudDownload",+ ],+ },+ {+ id: "business",+ label: "Business",+ items: [+ "Briefcase","Building","Building2","Store","ShoppingCart","ShoppingBag","CreditCard",+ "Wallet","DollarSign","Coins","Receipt","Banknote","Calendar","Users","User","UserPlus",+ "UserCheck","UserCog","UserMinus","Contact","Handshake","Target","Goal","TrendingUp",+ ],+ },+ {+ id: "media",+ label: "Media",+ items: [+ "Image","Camera","Film","Music","Music2","Music3","Music4","Headphones","Radio",+ "Tv","Tv2","Monitor","Smartphone","Tablet","Laptop","Speaker","Disc","Disc3",+ "Play","Pause","SkipForward","SkipBack","Rewind","FastForward",+ ],+ },+ {+ id: "nature",+ label: "Nature",+ items: [+ "Sun","Moon","Cloud","CloudRain","CloudSnow","CloudLightning","Wind","Snowflake",+ "Droplet","Droplets","Leaf","Trees","TreePine","TreeDeciduous","Sprout","Flower",+ "Flower2","Mountain","MountainSnow","Sunrise","Sunset","Rainbow","Tornado",+ ],+ },+ {+ id: "tools",+ label: "Tools",+ items: [+ "Wrench","Hammer","Settings","Settings2","Cog","Sliders","Filter",+ "Search","ScanSearch","Microscope","Telescope","Ruler","Scissors","Paintbrush",+ "Palette","Pipette","Crop","Wand","Wand2","Magnet",+ ],+ },+ {+ id: "shapes",+ label: "Shapes",+ items: [+ "Circle","Square","Triangle","Hexagon","Pentagon","Octagon","Diamond","Spade",+ "Club","Heart","Plus","Minus","X","Check","Asterisk","Slash","Equal","Divide",+ "ArrowUp","ArrowDown","ArrowLeft","ArrowRight","ArrowUpRight","ArrowDownRight",+ "ChevronUp","ChevronDown","ChevronLeft","ChevronRight",+ ],+ },+];++export const ALL_LUCIDE: string[] = Array.from(+ new Set(LUCIDE_GROUPS.flatMap((g) => g.items)),+);diff --git a/frontend/slices/icon-picker/lib/lucide-icons.ts b/frontend/slices/icon-picker/lib/lucide-icons.tsnew file mode 100644index 00000000..b49593c8--- /dev/null+++ b/frontend/slices/icon-picker/lib/lucide-icons.ts@@ -0,0 +1,105 @@+/** Curated lucide-react import surface for the icon picker.+ *+ * Why this file exists: `import * as Lucide from "lucide-react"` defeats+ * tree-shaking in some bundlers and bloats the client bundle with all+ * ~1500 icons even when the picker only exposes ~250. Named imports+ * here let webpack/turbopack drop the rest precisely (lucide-react sets+ * `sideEffects: false`, so every unused import is shaken).+ *+ * KEEP IN SYNC with `lucide-catalog.ts`. The CI guard+ * `scripts/check-lucide-catalog.mjs` (if added) verifies every catalog+ * name resolves through this map. Names dropped from catalog should be+ * dropped here too to shrink the bundle.+ *+ * GENERATED snapshot (2026-05-16). To regenerate manually:+ * node -e 'const fs=require("fs"); const src=fs.readFileSync(+ * "./lucide-catalog.ts","utf8"); const blocks=src.match(+ * /items:\\s*\\[([\\s\\S]*?)\\]/g)||[]; const all=[]; blocks.forEach(+ * b=>(b.match(/\\"([A-Z][A-Za-z0-9]+)\\"/g)||[]).forEach(s=>all.push(+ * s.slice(1,-1)))); const L=require("lucide-react"); console.log(+ * [...new Set(all)].sort().filter(n=>n in L).join(","));' */++import type { LucideIcon } from "lucide-react";+import {+ Activity, AlarmClock, Archive, ArrowDown, ArrowDownRight, ArrowLeft, ArrowRight, ArrowUp,+ ArrowUpRight, Asterisk, AtSign, Award, Banknote, BarChart, BarChart2, BarChart3,+ Bell, BellRing, Binary, Book, BookOpen, Bookmark, Box, Boxes,+ Braces, Brackets, Briefcase, Bug, Building, Building2, Calculator, Calendar,+ CalendarCheck, CalendarDays, Camera, Check, CheckSquare, ChevronDown, ChevronLeft, ChevronRight,+ ChevronUp, Circle, ClipboardCheck, ClipboardList, Clock, Cloud, CloudDownload, CloudLightning,+ CloudRain, CloudSnow, CloudUpload, Club, Code, Code2, Cog, Coins,+ Columns, Compass, Contact, Cpu, CreditCard, Crop, Crown, Database,+ Diamond, Disc, Disc3, Divide, DollarSign, Download, Droplet, Droplets,+ Edit, Edit3, Equal, Eraser, ExternalLink, Eye, EyeOff, FastForward,+ File, FileArchive, FileAudio, FileCode, FileImage, FileQuestion, FileSpreadsheet, FileText,+ FileVideo, Files, Film, Filter, Flag, Flame, Flower, Flower2,+ Folder, FolderKanban, FolderOpen, FolderPlus, FolderTree, Gem, GitBranch, GitCommit,+ GitMerge, GitPullRequest, Globe, Goal, Hammer, Handshake, HardDrive,+ Hash, Headphones, Heart, HelpCircle, Hexagon, Highlighter, Home, Hourglass,+ Image, Images, Inbox, Info, Kanban, Key, Laptop, Layers,+ LayoutGrid, LayoutList, Leaf, Library, LineChart, Link, List, ListChecks,+ ListTodo, Lock, Magnet, Mail, MailOpen, Map, MapPin, Megaphone,+ MemoryStick, MessageCircle, MessageSquare, Mic, MicOff, Microscope, Minus, Monitor,+ Moon, Mountain, MountainSnow, Music, Music2, Music3, Music4, Notebook,+ NotebookPen, Octagon, Package, Paintbrush, Palette, Paperclip, Pause, PenTool,+ Pencil, Pentagon, Percent, Phone, PhoneCall, PieChart, Pin, Pipette,+ Play, Plus, Radio, Rainbow, Receipt, Reply, Rewind, Rows,+ Rss, Ruler, Save, ScanSearch, Scissors, Search, Send, Server,+ Settings, Settings2, Share, Share2, ShoppingBag, ShoppingCart, Sigma, SkipBack,+ SkipForward, Slash, Sliders, Smartphone, Snowflake, Spade, Sparkles, Speaker,+ Sprout, Square, Star, StickyNote, Store, Sun, Sunrise, Sunset,+ Table, Table2, Tablet, Tag, Target, Telescope, Terminal, Timer,+ Tornado, Trash, Trash2, TreeDeciduous, TreePine, Trees, TrendingDown, TrendingUp,+ Triangle, Trophy, Tv, Tv2, Unlock, Upload, User, UserCheck,+ UserCog, UserMinus, UserPlus, Users, Video, VideoOff, Volume2, Wallet,+ Wand, Wand2, Webhook, Wind, Workflow, Wrench, Zap,+} from "lucide-react";++/** Curated map: name → component. Lookup is O(1). Unknown names resolve+ * to `null`, and `DynamicIcon` falls back to `FileText`. */+export const LUCIDE_ICONS: Readonly<Record<string, LucideIcon>> = {+ Activity, AlarmClock, Archive, ArrowDown, ArrowDownRight, ArrowLeft, ArrowRight, ArrowUp,+ ArrowUpRight, Asterisk, AtSign, Award, Banknote, BarChart, BarChart2, BarChart3,+ Bell, BellRing, Binary, Book, BookOpen, Bookmark, Box, Boxes,+ Braces, Brackets, Briefcase, Bug, Building, Building2, Calculator, Calendar,+ CalendarCheck, CalendarDays, Camera, Check, CheckSquare, ChevronDown, ChevronLeft, ChevronRight,+ ChevronUp, Circle, ClipboardCheck, ClipboardList, Clock, Cloud, CloudDownload, CloudLightning,+ CloudRain, CloudSnow, CloudUpload, Club, Code, Code2, Cog, Coins,+ Columns, Compass, Contact, Cpu, CreditCard, Crop, Crown, Database,+ Diamond, Disc, Disc3, Divide, DollarSign, Download, Droplet, Droplets,+ Edit, Edit3, Equal, Eraser, ExternalLink, Eye, EyeOff, FastForward,+ File, FileArchive, FileAudio, FileCode, FileImage, FileQuestion, FileSpreadsheet, FileText,+ FileVideo, Files, Film, Filter, Flag, Flame, Flower, Flower2,+ Folder, FolderKanban, FolderOpen, FolderPlus, FolderTree, Gem, GitBranch, GitCommit,+ GitMerge, GitPullRequest, Globe, Goal, Hammer, Handshake, HardDrive,+ Hash, Headphones, Heart, HelpCircle, Hexagon, Highlighter, Home, Hourglass,+ Image, Images, Inbox, Info, Kanban, Key, Laptop, Layers,+ LayoutGrid, LayoutList, Leaf, Library, LineChart, Link, List, ListChecks,+ ListTodo, Lock, Magnet, Mail, MailOpen, Map, MapPin, Megaphone,+ MemoryStick, MessageCircle, MessageSquare, Mic, MicOff, Microscope, Minus, Monitor,+ Moon, Mountain, MountainSnow, Music, Music2, Music3, Music4, Notebook,+ NotebookPen, Octagon, Package, Paintbrush, Palette, Paperclip, Pause, PenTool,+ Pencil, Pentagon, Percent, Phone, PhoneCall, PieChart, Pin, Pipette,+ Play, Plus, Radio, Rainbow, Receipt, Reply, Rewind, Rows,+ Rss, Ruler, Save, ScanSearch, Scissors, Search, Send, Server,+ Settings, Settings2, Share, Share2, ShoppingBag, ShoppingCart, Sigma, SkipBack,+ SkipForward, Slash, Sliders, Smartphone, Snowflake, Spade, Sparkles, Speaker,+ Sprout, Square, Star, StickyNote, Store, Sun, Sunrise, Sunset,+ Table, Table2, Tablet, Tag, Target, Telescope, Terminal, Timer,+ Tornado, Trash, Trash2, TreeDeciduous, TreePine, Trees, TrendingDown, TrendingUp,+ Triangle, Trophy, Tv, Tv2, Unlock, Upload, User, UserCheck,+ UserCog, UserMinus, UserPlus, Users, Video, VideoOff, Volume2, Wallet,+ Wand, Wand2, Webhook, Wind, Workflow, Wrench, Zap,+};++export type LucideIconName = keyof typeof LUCIDE_ICONS;++/** Fallback used when an unknown name is passed. Re-exported so consumers+ * can use the same fallback in their own code paths. */+export { FileText as FallbackLucideIcon };++/** Resolve a name from the curated map. Returns `null` for unknown names+ * so callers can choose their own fallback. */+export function resolveLucideIcon(name: string): LucideIcon | null {+ return LUCIDE_ICONS[name] ?? null;+}diff --git a/frontend/slices/icon-picker/lib/parse.test.ts b/frontend/slices/icon-picker/lib/parse.test.tsnew file mode 100644index 00000000..9d676e0b--- /dev/null+++ b/frontend/slices/icon-picker/lib/parse.test.ts@@ -0,0 +1,119 @@+import { describe, expect, it } from "vitest";+import {+ parseIconValue, lucideValue, phosphorValue, withColor, isLucideValue,+ isPhosphorValue, LUCIDE_PREFIX, PHOSPHOR_PREFIX,+} from "./parse";++describe("parseIconValue", () => {+ it("returns empty for null/undefined/empty", () => {+ expect(parseIconValue(null)).toEqual({ kind: "empty" });+ expect(parseIconValue(undefined)).toEqual({ kind: "empty" });+ expect(parseIconValue("")).toEqual({ kind: "empty" });+ });++ it("parses raw emoji", () => {+ expect(parseIconValue("🎯")).toEqual({ kind: "emoji", emoji: "🎯", color: undefined });+ });++ it("parses lucide value with no color", () => {+ expect(parseIconValue("lucide:Star")).toEqual({ kind: "lucide", name: "Star", color: undefined });+ });++ it("parses lucide value with color suffix", () => {+ expect(parseIconValue("lucide:Star?c=f59e0b")).toEqual({+ kind: "lucide", name: "Star", color: "#f59e0b",+ });+ });++ it("parses emoji + color suffix", () => {+ expect(parseIconValue("🎯?c=ff0000")).toEqual({ kind: "emoji", emoji: "🎯", color: "#ff0000" });+ });++ it("normalises hex case + strips leading #", () => {+ const p = parseIconValue("lucide:Star?c=#ABCDEF");+ expect(p.kind === "lucide" && p.color).toBe("#abcdef");+ });++ it("rejects invalid hex (not 3-8 chars)", () => {+ const a = parseIconValue("lucide:Star?c=zz");+ const b = parseIconValue("lucide:Star?c=12345g");+ expect(a.kind === "lucide" && a.color).toBeFalsy();+ expect(b.kind === "lucide" && b.color).toBeFalsy();+ });++ it("returns empty for bare lucide: prefix with no name", () => {+ expect(parseIconValue("lucide:")).toEqual({ kind: "empty" });+ expect(parseIconValue("lucide: ")).toEqual({ kind: "empty" });+ });++ it("ignores unknown query params", () => {+ const p = parseIconValue("lucide:Star?foo=bar&c=ff0000");+ expect(p.kind === "lucide" && p.color).toBe("#ff0000");+ });+});++describe("lucideValue + withColor", () => {+ it("builds canonical lucide string", () => {+ expect(lucideValue("Star")).toBe("lucide:Star");+ expect(lucideValue("Star", "#f59e0b")).toBe("lucide:Star?c=f59e0b");+ });++ it("withColor strips existing color when none provided", () => {+ expect(withColor("lucide:Star?c=f59e0b")).toBe("lucide:Star");+ expect(withColor("🎯?c=ff0000")).toBe("🎯");+ });++ it("withColor normalises hex case + leading #", () => {+ expect(withColor("lucide:Star", "#ABCDEF")).toBe("lucide:Star?c=abcdef");+ });++ it("withColor on empty string is empty", () => {+ expect(withColor("")).toBe("");+ expect(withColor("", "#fff")).toBe("");+ });++ it("round-trips through parseIconValue", () => {+ const v = lucideValue("BookmarkIcon", "#22c55e");+ const parsed = parseIconValue(v);+ expect(parsed).toEqual({ kind: "lucide", name: "BookmarkIcon", color: "#22c55e" });+ });+});++describe("isLucideValue", () => {+ it("detects lucide prefix", () => {+ expect(isLucideValue("lucide:Star")).toBe(true);+ expect(isLucideValue("lucide:Foo?c=ff0")).toBe(true);+ });+ it("rejects emoji + empty", () => {+ expect(isLucideValue("🎯")).toBe(false);+ expect(isLucideValue(null)).toBe(false);+ expect(isLucideValue("")).toBe(false);+ });+});++describe("LUCIDE_PREFIX export", () => {+ it("matches actual prefix", () => {+ expect(LUCIDE_PREFIX).toBe("lucide:");+ });+});++describe("phosphor value", () => {+ it("parses phosphor with no color", () => {+ expect(parseIconValue("phosphor:Star")).toEqual({ kind: "phosphor", name: "Star", color: undefined });+ });+ it("parses phosphor with color", () => {+ expect(parseIconValue("phosphor:Heart?c=ff00aa")).toEqual({ kind: "phosphor", name: "Heart", color: "#ff00aa" });+ });+ it("builds canonical phosphor string", () => {+ expect(phosphorValue("Star")).toBe("phosphor:Star");+ expect(phosphorValue("Star", "#f59e0b")).toBe("phosphor:Star?c=f59e0b");+ });+ it("detects phosphor prefix", () => {+ expect(isPhosphorValue("phosphor:Star")).toBe(true);+ expect(isPhosphorValue("lucide:Star")).toBe(false);+ expect(isPhosphorValue(null)).toBe(false);+ });+ it("exports the prefix constant", () => {+ expect(PHOSPHOR_PREFIX).toBe("phosphor:");+ });+});diff --git a/frontend/slices/icon-picker/lib/parse.ts b/frontend/slices/icon-picker/lib/parse.tsnew file mode 100644index 00000000..4f8d356d--- /dev/null+++ b/frontend/slices/icon-picker/lib/parse.ts@@ -0,0 +1,76 @@+/** Icon value model. Stored as one string in pages/databases.icon. Forms:+ *+ * - "" → empty (default fallback)+ * - "🎯" → emoji glyph (legacy + new)+ * - "lucide:Star" → lucide icon (stroke), currentColor+ * - "lucide:Star?c=f59e0b" → lucide + hex color (no #)+ * - "phosphor:Star" → phosphor icon (fill), currentColor+ * - "phosphor:Star?c=f59e0b" → phosphor + hex color (no #)+ * - "🎯?c=f59e0b" → emoji + tint hint (only used for twemoji bg/ring)+ *+ * Color is suffixed with `?c=<hex>` (no leading #) — backwards-compat+ * with all existing emoji values, no schema migration. */++export type IconValue =+ | { kind: "emoji"; emoji: string; color?: string }+ | { kind: "lucide"; name: string; color?: string }+ | { kind: "phosphor"; name: string; color?: string }+ | { kind: "empty" };++export const LUCIDE_PREFIX = "lucide:";+export const PHOSPHOR_PREFIX = "phosphor:";++export function parseIconValue(raw: string | null | undefined): IconValue {+ if (!raw) return { kind: "empty" };++ const qi = raw.indexOf("?");+ const head = qi >= 0 ? raw.slice(0, qi) : raw;+ const query = qi >= 0 ? raw.slice(qi + 1) : "";+ const color = parseColorParam(query);++ if (head.startsWith(LUCIDE_PREFIX)) {+ const name = head.slice(LUCIDE_PREFIX.length).trim();+ return name ? { kind: "lucide", name, color } : { kind: "empty" };+ }+ if (head.startsWith(PHOSPHOR_PREFIX)) {+ const name = head.slice(PHOSPHOR_PREFIX.length).trim();+ return name ? { kind: "phosphor", name, color } : { kind: "empty" };+ }+ return { kind: "emoji", emoji: head, color };+}++function parseColorParam(q: string): string | undefined {+ if (!q) return undefined;+ for (const part of q.split("&")) {+ const [k, v] = part.split("=");+ if (k === "c" && v) {+ const hex = v.replace(/^#/, "");+ if (/^[0-9a-fA-F]{3,8}$/.test(hex)) return `#${hex.toLowerCase()}`;+ }+ }+ return undefined;+}++export function lucideValue(name: string, color?: string): string {+ return withColor(`${LUCIDE_PREFIX}${name}`, color);+}++export function phosphorValue(name: string, color?: string): string {+ return withColor(`${PHOSPHOR_PREFIX}${name}`, color);+}++export function withColor(raw: string, color?: string): string {+ if (!raw) return raw;+ const base = raw.split("?")[0];+ if (!color) return base;+ const hex = color.replace(/^#/, "").toLowerCase();+ return `${base}?c=${hex}`;+}++export function isLucideValue(raw: string | null | undefined): boolean {+ return !!raw && raw.startsWith(LUCIDE_PREFIX);+}++export function isPhosphorValue(raw: string | null | undefined): boolean {+ return !!raw && raw.startsWith(PHOSPHOR_PREFIX);+}diff --git a/frontend/slices/icon-picker/lib/phosphor-catalog.ts b/frontend/slices/icon-picker/lib/phosphor-catalog.tsnew file mode 100644index 00000000..a61926e5--- /dev/null+++ b/frontend/slices/icon-picker/lib/phosphor-catalog.ts@@ -0,0 +1,118 @@+/** Curated Phosphor icon catalog — fill weight. Mirrors the lucide+ * groupings but uses Phosphor's name space. The `phosphor:` prefix is+ * added when stored in the page `icon` field — see `parseIconValue`. */++export interface PhosphorGroup {+ id: string;+ label: string;+ items: string[];+}++export const PHOSPHOR_GROUPS: PhosphorGroup[] = [+ {+ id: "general",+ label: "General",+ items: [+ "House","Star","Heart","Bookmark","Flag","Tag","Gear","Question",+ "Info","Bell","Eye","EyeSlash","Lock","LockOpen","Key","PushPin",+ "MapPin","MapTrifold","Globe","Compass","Trophy","Crown","Diamond",+ "Sparkle","Lightning","Flame",+ ],+ },+ {+ id: "files",+ label: "Files",+ items: [+ "File","FileText","FileCode","Folder","FolderOpen","Archive","Package",+ "Stack","Tray","Trash","DownloadSimple","UploadSimple","Paperclip",+ "Image","Images",+ ],+ },+ {+ id: "communication",+ label: "Communication",+ items: [+ "Envelope","ChatCircle","ChatText","PaperPlaneTilt","At","Phone","PhoneCall",+ "VideoCamera","Microphone","SpeakerHigh","Megaphone","ShareNetwork","Link",+ "ArrowSquareOut","Hash","ArrowBendUpLeft",+ ],+ },+ {+ id: "productivity",+ label: "Productivity",+ items: [+ "CheckSquare","Square","ListChecks","ListPlus","Clipboard","ClipboardText",+ "Calendar","CalendarBlank","CalendarCheck","Clock","Timer","Alarm","Hourglass",+ "Book","BookOpen","Books","Notebook","NotePencil","Pencil","PencilLine",+ "Highlighter","Eraser",+ ],+ },+ {+ id: "data",+ label: "Data",+ items: [+ "Database","Table","GridFour","ListBullets","List","Kanban","Columns","Rows",+ "ChartBar","ChartBarHorizontal","ChartLine","ChartPie","TrendUp","TrendDown",+ "Pulse","Sigma","Calculator","Percent","Binary",+ ],+ },+ {+ id: "development",+ label: "Development",+ items: [+ "Code","BracketsCurly","BracketsSquare","BracketsRound","GitBranch","GitMerge",+ "GitPullRequest","GitCommit","GithubLogo","HardDrives","Cpu","Memory","Bug",+ "Wrench","Hammer","FlowArrow","Cloud","CloudArrowUp","CloudArrowDown",+ ],+ },+ {+ id: "business",+ label: "Business",+ items: [+ "Briefcase","Buildings","Storefront","ShoppingCart","ShoppingBag","CreditCard",+ "Wallet","CurrencyDollar","Coins","Receipt","Money","Users","User","UserPlus",+ "UserCircle","UserMinus","Handshake","Target","Crosshair",+ ],+ },+ {+ id: "media",+ label: "Media",+ items: [+ "Camera","FilmStrip","MusicNote","Headphones","Radio","Television","Monitor",+ "DeviceMobile","DeviceTablet","Laptop","SpeakerSimpleHigh","Disc","Play",+ "Pause","SkipForward","SkipBack","Rewind","FastForward",+ ],+ },+ {+ id: "nature",+ label: "Nature",+ items: [+ "Sun","Moon","Cloud","CloudRain","CloudSnow","CloudLightning","Wind",+ "Snowflake","Drop","Tree","TreeEvergreen","Plant","Flower","Mountains",+ "SunHorizon","Rainbow","Tornado",+ ],+ },+ {+ id: "tools",+ label: "Tools",+ items: [+ "Wrench","Hammer","Gear","Sliders","Funnel","MagnifyingGlass","Microscope",+ "Ruler","Scissors","PaintBrush","Palette","Eyedropper","Crop","MagicWand",+ "Magnet",+ ],+ },+ {+ id: "shapes",+ label: "Shapes",+ items: [+ "Circle","Square","Triangle","Hexagon","Diamond","Heart","Plus","Minus",+ "X","Check","Asterisk","Equals","Divide","ArrowUp","ArrowDown","ArrowLeft",+ "ArrowRight","ArrowUpRight","ArrowDownRight","CaretUp","CaretDown",+ "CaretLeft","CaretRight",+ ],+ },+];++export const ALL_PHOSPHOR: string[] = Array.from(+ new Set(PHOSPHOR_GROUPS.flatMap((g) => g.items)),+);diff --git a/frontend/slices/icon-picker/lib/phosphor-icons-a.ts b/frontend/slices/icon-picker/lib/phosphor-icons-a.tsnew file mode 100644index 00000000..cacdc9da--- /dev/null+++ b/frontend/slices/icon-picker/lib/phosphor-icons-a.ts@@ -0,0 +1,144 @@+/** Phosphor icon imports A-L (split for ≤200 LOC file cap). */++import type { Icon } from "@phosphor-icons/react";+import {+ Alarm,+ Archive,+ ArrowBendUpLeft,+ ArrowDown,+ ArrowDownRight,+ ArrowLeft,+ ArrowRight,+ ArrowSquareOut,+ ArrowUp,+ ArrowUpRight,+ Asterisk,+ At,+ Bell,+ Binary,+ Book,+ BookOpen,+ Bookmark,+ Books,+ BracketsCurly,+ BracketsRound,+ BracketsSquare,+ Briefcase,+ Bug,+ Buildings,+ Calculator,+ Calendar,+ CalendarBlank,+ CalendarCheck,+ Camera,+ CaretDown,+ CaretLeft,+ CaretRight,+ CaretUp,+ ChartBar,+ ChartBarHorizontal,+ ChartLine,+ ChartPie,+ ChatCircle,+ ChatText,+ Check,+ CheckSquare,+ Circle,+ Clipboard,+ ClipboardText,+ Clock,+ Cloud,+ CloudArrowDown,+ CloudArrowUp,+ CloudLightning,+ CloudRain,+ CloudSnow,+ Code,+ Coins,+ Columns,+ Compass,+ Cpu,+ CreditCard,+ Crop,+ Crosshair,+ Crown,+ CurrencyDollar,+ Database,+ DeviceMobile,+ DeviceTablet,+ Diamond,+ Disc,+ Divide,+ DownloadSimple,+ Drop,+ Envelope,+ Equals,+ Eraser,+ Eye,+ EyeSlash,+ Eyedropper,+ FastForward,+ File,+ FileCode,+ FileText,+ FilmStrip,+ Flag,+ Flame,+ Flower,+ FlowArrow,+ Folder,+ FolderOpen,+ Funnel,+ Gear,+ GitBranch,+ GitCommit,+ GitMerge,+ GitPullRequest,+ GithubLogo,+ Globe,+ GridFour,+ Hammer,+ Handshake,+ HardDrives,+ Hash,+ Headphones,+ Heart,+ Hexagon,+ Highlighter,+ Hourglass,+ House,+ Image,+ Images,+ Info,+ Kanban,+ Key,+ Laptop,+ Lightning,+ Link,+ List,+ ListBullets,+ ListChecks,+ ListPlus,+ Lock,+ LockOpen,+} from "@phosphor-icons/react";++export const PHOSPHOR_ICONS_A: Readonly<Record<string, Icon>> = {+ Alarm, Archive, ArrowBendUpLeft, ArrowDown, ArrowDownRight, ArrowLeft, ArrowRight,+ ArrowSquareOut, ArrowUp, ArrowUpRight, Asterisk, At, Bell, Binary, Book, BookOpen,+ Bookmark, Books, BracketsCurly, BracketsRound, BracketsSquare, Briefcase, Bug,+ Buildings, Calculator, Calendar, CalendarBlank, CalendarCheck, Camera, CaretDown,+ CaretLeft, CaretRight, CaretUp, ChartBar, ChartBarHorizontal, ChartLine, ChartPie,+ ChatCircle, ChatText, Check, CheckSquare, Circle, Clipboard, ClipboardText, Clock,+ Cloud, CloudArrowDown, CloudArrowUp, CloudLightning, CloudRain, CloudSnow, Code,+ Coins, Columns, Compass, Cpu, CreditCard, Crop, Crosshair, Crown, CurrencyDollar,+ Database, DeviceMobile, DeviceTablet, Diamond, Disc, Divide, DownloadSimple, Drop,+ Envelope, Equals, Eraser, Eye, EyeSlash, Eyedropper, FastForward, File, FileCode,+ FileText, FilmStrip, Flag, Flame, Flower, FlowArrow, Folder, FolderOpen, Funnel,+ Gear, GitBranch, GitCommit, GitMerge, GitPullRequest, GithubLogo, Globe, GridFour,+ Hammer, Handshake, HardDrives, Hash, Headphones, Heart, Hexagon, Highlighter,+ Hourglass, House, Image, Images, Info, Kanban, Key, Laptop, Lightning, Link, List,+ ListBullets, ListChecks, ListPlus, Lock, LockOpen,+};++export { FileText as FallbackPhosphorIcon };diff --git a/frontend/slices/icon-picker/lib/phosphor-icons-b.ts b/frontend/slices/icon-picker/lib/phosphor-icons-b.tsnew file mode 100644index 00000000..6ca30a69--- /dev/null+++ b/frontend/slices/icon-picker/lib/phosphor-icons-b.ts@@ -0,0 +1,102 @@+/** Phosphor icon imports M-Z (split for ≤200 LOC file cap). */++import type { Icon } from "@phosphor-icons/react";+import {+ MagicWand,+ Magnet,+ MagnifyingGlass,+ MapPin,+ MapTrifold,+ Megaphone,+ Memory,+ Microphone,+ Microscope,+ Minus,+ Money,+ Monitor,+ Moon,+ Mountains,+ MusicNote,+ Network,+ Notebook,+ NotePencil,+ Package,+ PaintBrush,+ Palette,+ PaperPlaneTilt,+ Paperclip,+ Pause,+ Pencil,+ PencilLine,+ Percent,+ Phone,+ PhoneCall,+ Plant,+ Play,+ Plus,+ Pulse,+ PushPin,+ Question,+ Radio,+ Rainbow,+ Receipt,+ Rewind,+ Rows,+ Ruler,+ Scissors,+ ShareNetwork,+ ShoppingBag,+ ShoppingCart,+ Sigma,+ SkipBack,+ SkipForward,+ Sliders,+ Snowflake,+ Sparkle,+ SpeakerHigh,+ SpeakerSimpleHigh,+ Square,+ Stack,+ Star,+ Storefront,+ Sun,+ SunHorizon,+ Table,+ Tag,+ Target,+ Television,+ Timer,+ Tornado,+ Tray,+ Trash,+ Tree,+ TreeEvergreen,+ TrendDown,+ TrendUp,+ Triangle,+ Trophy,+ UploadSimple,+ User,+ UserCircle,+ UserMinus,+ UserPlus,+ Users,+ VideoCamera,+ Wallet,+ Wind,+ Wrench,+ X,+} from "@phosphor-icons/react";++export const PHOSPHOR_ICONS_B: Readonly<Record<string, Icon>> = {+ MagicWand, Magnet, MagnifyingGlass, MapPin, MapTrifold, Megaphone, Memory, Microphone,+ Microscope, Minus, Money, Monitor, Moon, Mountains, MusicNote, Network, Notebook,+ NotePencil, Package, PaintBrush, Palette, PaperPlaneTilt, Paperclip, Pause, Pencil,+ PencilLine, Percent, Phone, PhoneCall, Plant, Play, Plus, Pulse, PushPin, Question,+ Radio, Rainbow, Receipt, Rewind, Rows, Ruler, Scissors, ShareNetwork, ShoppingBag,+ ShoppingCart, Sigma, SkipBack, SkipForward, Sliders, Snowflake, Sparkle, SpeakerHigh,+ SpeakerSimpleHigh, Square, Stack, Star, Storefront, Sun, SunHorizon, Table, Tag,+ Target, Television, Timer, Tornado, Tray, Trash, Tree, TreeEvergreen, TrendDown,+ TrendUp, Triangle, Trophy, UploadSimple, User, UserCircle, UserMinus, UserPlus, Users,+ VideoCamera, Wallet, Wind, Wrench, X,+};diff --git a/frontend/slices/icon-picker/lib/phosphor-icons.ts b/frontend/slices/icon-picker/lib/phosphor-icons.tsnew file mode 100644index 00000000..c8f589e2--- /dev/null+++ b/frontend/slices/icon-picker/lib/phosphor-icons.ts@@ -0,0 +1,25 @@+/** Curated `@phosphor-icons/react` import surface for the picker.+ *+ * Why named imports: `import * as Ph from "@phosphor-icons/react"`+ * defeats tree-shaking and pulls all ~3000 icons. Named imports keep+ * only the curated subset.+ *+ * Split across `-a` (A-L) and `-b` (M-Z) to honour the 200 LOC file+ * cap. KEEP IN SYNC with `phosphor-catalog.ts`. */++import type { Icon } from "@phosphor-icons/react";+import { PHOSPHOR_ICONS_A, FallbackPhosphorIcon } from "./phosphor-icons-a";+import { PHOSPHOR_ICONS_B } from "./phosphor-icons-b";++export const PHOSPHOR_ICONS: Readonly<Record<string, Icon>> = {+ ...PHOSPHOR_ICONS_A,+ ...PHOSPHOR_ICONS_B,+};++export type PhosphorIconName = keyof typeof PHOSPHOR_ICONS;++export { FallbackPhosphorIcon };++export function resolvePhosphorIcon(name: string): Icon | null {+ return PHOSPHOR_ICONS[name] ?? null;+}diff --git a/frontend/slices/icon-picker/lib/picker-handlers.ts b/frontend/slices/icon-picker/lib/picker-handlers.tsnew file mode 100644index 00000000..2ab55627--- /dev/null+++ b/frontend/slices/icon-picker/lib/picker-handlers.ts@@ -0,0 +1,122 @@+/** Framework-neutral pick / commit handlers shared by React and Svelte renderers. */++import { lucideValue, phosphorValue, parseIconValue, withColor, type IconValue } from "./parse";+import { pushRecent } from "./recents-core";+import { ALL_EMOJIS } from "./emoji-catalog";+import { ALL_LUCIDE } from "./lucide-catalog";+import { ALL_PHOSPHOR } from "./phosphor-catalog";++export type TopTab = "emoji" | "icon";+export type IconVariant = "lucide" | "phosphor";++export interface PickerHandlerDeps {+ parsed: IconValue;+ tab: TopTab;+ iconVariant: IconVariant;+ currentColor: string | undefined;+ colorEnabled: boolean;+ onChange: (next: string) => void;+ onClear?: () => void;+ onSelect?: () => void;+}++export interface PickerHandlers {+ pickEmoji: (emoji: string) => void;+ pickLucide: (name: string) => void;+ pickPhosphor: (name: string) => void;+ pickRecent: (value: string) => void;+ pickColor: (hex: string) => void;+ pickRandom: () => void;+ handleClear: () => void;+}++export function buildPickerHandlers(+ deps: PickerHandlerDeps & { currentValue: string },+): PickerHandlers {+ const {+ parsed, tab, iconVariant, currentColor, colorEnabled,+ onChange, onClear, onSelect, currentValue,+ } = deps;++ const commit = (nextValue: string) => {+ if (nextValue === currentValue) {+ onSelect?.();+ return;+ }+ onChange(nextValue);+ onSelect?.();+ pushRecent(nextValue);+ };++ return {+ pickEmoji: (emoji) => commit(withColor(emoji, undefined)),+ pickLucide: (name) => commit(lucideValue(name, currentColor)),+ pickPhosphor: (name) => commit(phosphorValue(name, currentColor)),+ pickRecent: (value) => {+ const recent = parseIconValue(value);+ if (recent.kind === "empty") return;+ if (recent.color) return commit(value);+ if (recent.kind === "lucide") return commit(lucideValue(recent.name, currentColor));+ if (recent.kind === "phosphor") return commit(phosphorValue(recent.name, currentColor));+ commit(withColor(recent.emoji, undefined));+ },+ pickColor: (hex) => {+ if (!colorEnabled) return;+ if (parsed.kind === "lucide") onChange(withColor(`lucide:${parsed.name}`, hex || undefined));+ else if (parsed.kind === "phosphor") onChange(withColor(`phosphor:${parsed.name}`, hex || undefined));+ },+ pickRandom: () => {+ if (tab === "icon") {+ const names = iconVariant === "phosphor" ? ALL_PHOSPHOR : ALL_LUCIDE;+ const name = names[Math.floor(Math.random() * names.length)];+ commit(iconVariant === "phosphor" ? phosphorValue(name, currentColor) : lucideValue(name, currentColor));+ } else {+ const emoji = ALL_EMOJIS[Math.floor(Math.random() * ALL_EMOJIS.length)];+ commit(withColor(emoji, undefined));+ }+ },+ handleClear: () => {+ onClear?.();+ onSelect?.();+ },+ };+}++export function getSearchPlaceholder(+ tab: TopTab,+ iconVariant: IconVariant,+ iconStyle: "twemoji" | "native",+): string {+ if (tab === "icon") {+ return iconVariant === "phosphor"+ ? "Search phosphor icons (fill)…"+ : "Search lucide icons (outline)…";+ }+ return iconStyle === "twemoji"+ ? "Search emoji (twemoji)…"+ : "Search emoji (native)…";+}++type KeyboardLike = {+ key: string;+ target: EventTarget | null;+ preventDefault: () => void;+};+type ContainerLike = HTMLElement | { current: HTMLElement | null } | null;++/** Arrow-key navigation over cells carrying `data-icon-cell-index`. */+export function handleGridArrowKey(event: KeyboardLike, containerLike: ContainerLike): void {+ if (!["ArrowRight", "ArrowLeft", "ArrowUp", "ArrowDown"].includes(event.key)) return;+ const target = event.target as HTMLElement | null;+ const indexText = target?.getAttribute?.("data-icon-cell-index");+ if (!indexText) return;+ const container = containerLike && "current" in containerLike ? containerLike.current : containerLike;+ const cells = container?.querySelectorAll<HTMLElement>("[data-icon-cell-index]");+ if (!cells?.length) return;+ const index = Number(indexText);+ const delta = event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : event.key === "ArrowDown" ? 8 : -8;+ const next = Math.max(0, Math.min(cells.length - 1, index + delta));+ if (next === index) return;+ event.preventDefault();+ cells[next]?.focus();+}diff --git a/frontend/slices/icon-picker/lib/recents-core.ts b/frontend/slices/icon-picker/lib/recents-core.tsnew file mode 100644index 00000000..6790cedf--- /dev/null+++ b/frontend/slices/icon-picker/lib/recents-core.ts@@ -0,0 +1,77 @@+const KEY = "nosion:iconRecents";+const MAX = 24;++let cache: string[] = [];+let hydrated = false;+let storageBound = false;+const listeners = new Set<() => void>();++function readStorage(): string[] {+ if (typeof window === "undefined") return [];+ try {+ const raw = window.localStorage.getItem(KEY);+ if (!raw) return [];+ const arr: unknown = JSON.parse(raw);+ return Array.isArray(arr)+ ? arr.filter((v): v is string => typeof v === "string" && v.length > 0).slice(0, MAX)+ : [];+ } catch {+ return [];+ }+}++function persist(values: readonly string[]): void {+ if (typeof window === "undefined") return;+ try {+ window.localStorage.setItem(KEY, JSON.stringify(values));+ } catch {+ // Quota/private-mode failures must not break icon selection.+ }+}++function notify(): void {+ for (const listener of listeners) listener();+}++function ensureHydrated(): void {+ if (hydrated || typeof window === "undefined") return;+ cache = readStorage();+ hydrated = true;+ if (storageBound) return;+ storageBound = true;+ window.addEventListener("storage", (event) => {+ if (event.key !== KEY) return;+ cache = readStorage();+ notify();+ });+}++export function subscribeRecentIcons(listener: () => void): () => void {+ ensureHydrated();+ listeners.add(listener);+ return () => listeners.delete(listener);+}++export function getRecentIconsSnapshot(): readonly string[] {+ ensureHydrated();+ return cache;+}++export function getRecentIconsServerSnapshot(): readonly string[] {+ return [];+}++export function pushRecent(value: string): void {+ if (!value) return;+ ensureHydrated();+ cache = [value, ...cache.filter((item) => item !== value)].slice(0, MAX);+ persist(cache);+ notify();+}++export function clearRecents(): void {+ ensureHydrated();+ cache = [];+ persist(cache);+ notify();+}diff --git a/frontend/slices/icon-picker/lib/recents.ts b/frontend/slices/icon-picker/lib/recents.tsnew file mode 100644index 00000000..4c8c7fff--- /dev/null+++ b/frontend/slices/icon-picker/lib/recents.ts@@ -0,0 +1,18 @@+"use client";++import { useSyncExternalStore } from "react";+import {+ getRecentIconsServerSnapshot,+ getRecentIconsSnapshot,+ subscribeRecentIcons,+} from "./recents-core";++export { clearRecents, pushRecent } from "./recents-core";++export function useRecentIcons(): readonly string[] {+ return useSyncExternalStore(+ subscribeRecentIcons,+ getRecentIconsSnapshot,+ getRecentIconsServerSnapshot,+ );+}diff --git a/frontend/slices/icon-picker/lib/search-haystacks.ts b/frontend/slices/icon-picker/lib/search-haystacks.tsnew file mode 100644index 00000000..084f7285--- /dev/null+++ b/frontend/slices/icon-picker/lib/search-haystacks.ts@@ -0,0 +1,53 @@+import { ALL_EMOJIS } from "./emoji-catalog";+import { ALL_LUCIDE } from "./lucide-catalog";+import { ALL_PHOSPHOR } from "./phosphor-catalog";+import { buildEmojiSearchHaystack } from "./emoji-keywords";++/** Precomputed lowercase search haystacks. Built once at module load. */+export const EMOJI_HAYSTACKS: ReadonlyMap<string, string> = (() => {+ const map = new Map<string, string>();+ for (const e of ALL_EMOJIS) map.set(e, buildEmojiSearchHaystack(e));+ return map;+})();++export const LUCIDE_LOWER: ReadonlyMap<string, string> = (() => {+ const map = new Map<string, string>();+ for (const n of ALL_LUCIDE) map.set(n, n.toLowerCase());+ return map;+})();++export const PHOSPHOR_LOWER: ReadonlyMap<string, string> = (() => {+ const map = new Map<string, string>();+ for (const n of ALL_PHOSPHOR) map.set(n, n.toLowerCase());+ return map;+})();++export function filterEmoji(query: string): string[] | null {+ if (!query) return null;+ const out: string[] = [];+ for (const e of ALL_EMOJIS) {+ const hay = EMOJI_HAYSTACKS.get(e);+ if (hay && hay.includes(query)) out.push(e);+ }+ return out;+}++export function filterLucide(query: string): string[] | null {+ if (!query) return null;+ const out: string[] = [];+ for (const n of ALL_LUCIDE) {+ const hay = LUCIDE_LOWER.get(n);+ if (hay && hay.includes(query)) out.push(n);+ }+ return out;+}++export function filterPhosphor(query: string): string[] | null {+ if (!query) return null;+ const out: string[] = [];+ for (const n of ALL_PHOSPHOR) {+ const hay = PHOSPHOR_LOWER.get(n);+ if (hay && hay.includes(query)) out.push(n);+ }+ return out;+}diff --git a/frontend/slices/icon-picker/lib/style-core.ts b/frontend/slices/icon-picker/lib/style-core.tsnew file mode 100644index 00000000..6e1271ca--- /dev/null+++ b/frontend/slices/icon-picker/lib/style-core.ts@@ -0,0 +1,84 @@+const KEY = "icon-picker:style";+const LEGACY_KEYS = ["nosion:iconStyle"] as const;+export const DEFAULT_ICON_STYLE = "twemoji" as const;++export type Style = "twemoji" | "native";++let current: Style = DEFAULT_ICON_STYLE;+let hydrated = false;+let storageBound = false;+const listeners = new Set<() => void>();++function isStyle(value: unknown): value is Style {+ return value === "twemoji" || value === "native";+}++function readStorage(): Style {+ if (typeof window === "undefined") return DEFAULT_ICON_STYLE;+ const raw = window.localStorage.getItem(KEY);+ if (isStyle(raw)) return raw;+ for (const legacy of LEGACY_KEYS) {+ const value = window.localStorage.getItem(legacy);+ if (!isStyle(value)) continue;+ try {+ window.localStorage.setItem(KEY, value);+ window.localStorage.removeItem(legacy);+ } catch {+ // Preserve the migrated in-memory value even when storage is unavailable.+ }+ return value;+ }+ return DEFAULT_ICON_STYLE;+}++function notify(): void {+ for (const listener of listeners) listener();+}++function ensureHydrated(): void {+ if (hydrated || typeof window === "undefined") return;+ current = readStorage();+ hydrated = true;+ if (storageBound) return;+ storageBound = true;+ window.addEventListener("storage", (event) => {+ if (event.key !== KEY) return;+ const next = readStorage();+ if (next === current) return;+ current = next;+ notify();+ });+}++export function subscribeIconStyle(listener: () => void): () => void {+ ensureHydrated();+ listeners.add(listener);+ return () => listeners.delete(listener);+}++export function getIconStyleSnapshot(): Style {+ ensureHydrated();+ return current;+}++export function getIconStyleServerSnapshot(): Style {+ return DEFAULT_ICON_STYLE;+}++export function setIconStyle(next: Style): void {+ ensureHydrated();+ if (next === current) return;+ current = next;+ if (typeof window !== "undefined") {+ try {+ window.localStorage.setItem(KEY, next);+ } catch {+ console.warn("[iconStyle] localStorage write failed");+ }+ }+ notify();+}++export function readIconStyle(): Style {+ return getIconStyleSnapshot();+}diff --git a/frontend/slices/icon-picker/lib/style-pref.ts b/frontend/slices/icon-picker/lib/style-pref.tsnew file mode 100644index 00000000..01c17508--- /dev/null+++ b/frontend/slices/icon-picker/lib/style-pref.ts@@ -0,0 +1,23 @@+"use client";++import { useSyncExternalStore } from "react";+import {+ getIconStyleServerSnapshot,+ getIconStyleSnapshot,+ setIconStyle,+ subscribeIconStyle,+ type Style,+} from "./style-core";++export { readIconStyle, setIconStyle, type Style } from "./style-core";++/** Server snapshot is the default, so hydration never mismatches; the client+ * snapshot takes over immediately after. No mount flag needed. */+export function useIconStyle(): [Style, (next: Style) => void] {+ const style = useSyncExternalStore(+ subscribeIconStyle,+ getIconStyleSnapshot,+ getIconStyleServerSnapshot,+ );+ return [style, setIconStyle];+}diff --git a/frontend/slices/icon-picker/lib/twemoji.ts b/frontend/slices/icon-picker/lib/twemoji.tsnew file mode 100644index 00000000..2febafac--- /dev/null+++ b/frontend/slices/icon-picker/lib/twemoji.ts@@ -0,0 +1,43 @@+/** Twemoji codepoint converter + CDN URL builder.+ *+ * Twemoji = Twitter's open-source SVG emoji set. Notion uses the same+ * set as their default emoji renderer. Licensed MIT (code) + CC-BY 4.0+ * (assets), so safe to hot-link without copyright issue.+ *+ * We hot-link to jsDelivr's mirror of jdecked/twemoji (the actively+ * maintained fork after Twitter open-sourced and abandoned the repo).+ * No npm dep — keeps bundle small. */++const TWEMOJI_VERSION = "15.1.0";+const TWEMOJI_BASE = `https://cdn.jsdelivr.net/gh/jdecked/twemoji@${TWEMOJI_VERSION}/assets/svg`;++const VS16 = /️/g;+const ZWJ = "";++/** Twemoji's official codepoint conversion. Strips variation selector+ * (U+FE0F) for sequences without ZWJ — matches the asset filename. */+function toCodePoint(input: string, sep = "-"): string {+ const cleaned = input.indexOf(ZWJ) < 0 ? input.replace(VS16, "") : input;+ const out: string[] = [];+ let pending = 0;+ for (let i = 0; i < cleaned.length; i++) {+ const c = cleaned.charCodeAt(i);+ if (pending) {+ out.push((0x10000 + ((pending - 0xd800) << 10) + (c - 0xdc00)).toString(16));+ pending = 0;+ } else if (c >= 0xd800 && c <= 0xdbff) {+ pending = c;+ } else {+ out.push(c.toString(16));+ }+ }+ return out.join(sep);+}++/** SVG URL on jsDelivr CDN. Returns null for empty input. */+export function twemojiUrl(emoji: string | null | undefined): string | null {+ if (!emoji) return null;+ const cp = toCodePoint(emoji);+ if (!cp) return null;+ return `${TWEMOJI_BASE}/${cp}.svg`;+}diff --git a/frontend/slices/os-settings/components/account-avatar.test.ts b/frontend/slices/os-settings/components/account-avatar.test.tsnew file mode 100644index 00000000..e4a6a97f--- /dev/null+++ b/frontend/slices/os-settings/components/account-avatar.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from "vitest";+import { libraryValueFromPicker, pickerValueFromLibrary } from "./account-avatar";++// The picker speaks bare emoji (`🎯`, `🎯?c=0b6e99`) and namespaced+// `lucide:`/`phosphor:`. The account store speaks `emoji:`/`lucide:`/`phosphor:`+// only. A mismatch here means a picked emoji is rejected by the trust boundary.+describe("picker/account icon value translation", () => {+ it("namespaces bare emoji without touching named icons", () => {+ expect(libraryValueFromPicker("🎯")).toBe("emoji:🎯");+ expect(libraryValueFromPicker("🎯?c=0b6e99")).toBe("emoji:🎯?c=0b6e99");+ expect(libraryValueFromPicker("lucide:Star")).toBe("lucide:Star");+ expect(libraryValueFromPicker("phosphor:Shield?c=ff0000")).toBe("phosphor:Shield?c=ff0000");+ expect(libraryValueFromPicker("emoji:🎯")).toBe("emoji:🎯");+ expect(libraryValueFromPicker("")).toBe("");+ });++ it("round-trips every value the picker can produce back through the store", () => {+ for (const picked of ["🎯", "🦊?c=f59e0b", "lucide:Star", "lucide:FileText?c=0b6e99", "phosphor:ShieldCheck"]) {+ const stored = libraryValueFromPicker(picked);+ expect(pickerValueFromLibrary(stored)).toBe(picked);+ }+ expect(pickerValueFromLibrary(null)).toBeNull();+ });+});diff --git a/frontend/slices/os-settings/components/account-avatar.tsx b/frontend/slices/os-settings/components/account-avatar.tsxindex f05460b7..89143450 100644--- a/frontend/slices/os-settings/components/account-avatar.tsx+++ b/frontend/slices/os-settings/components/account-avatar.tsx@@ -2,6 +2,7 @@import { Compass, Heart, Leaf, Shield, Sparkles, Star, UserRound, Zap, type LucideIcon } from "lucide-react";import type { AccountIcon, AccountPreset } from "@/lib/auth/account-profile-model";+import { DynamicIcon } from "@/features/icon-picker";import { cn } from "@/lib/utils";const PRESET_ICON: Record<AccountPreset, LucideIcon> = {@@ -15,6 +16,20 @@ const PRESET_ICON: Record<AccountPreset, LucideIcon> = {compass: Compass,};+/** The picker stores emoji as a bare glyph (`🎯`, `🎯?c=0b6e99`) but the account store+ * requires the explicit `emoji:` namespace (see LIBRARY_ICON in+ * lib/auth/account-profile.ts). These two functions are the only translation point. */+export function libraryValueFromPicker(value: string): string {+ if (!value) return value;+ if (value.startsWith("lucide:") || value.startsWith("phosphor:") || value.startsWith("emoji:")) return value;+ return `emoji:${value}`;+}++export function pickerValueFromLibrary(value: string | null): string | null {+ if (!value) return null;+ return value.startsWith("emoji:") ? value.slice("emoji:".length) : value;+}+export function AccountAvatar({ icon, className }: { icon: AccountIcon; className?: string }) {if (icon.type === "image") {// Owner-uploaded data URLs are authenticated bytes, not optimizer inputs.@@ -23,6 +38,15 @@ export function AccountAvatar({ icon, className }: { icon: AccountIcon; classNam<img src={icon.src} alt="" className={cn("size-16 rounded-full object-cover", className)} />);}+ if (icon.type === "library") {+ return (+ <span className={cn("grid size-16 place-items-center rounded-full bg-primary text-primary-foreground", className)}>+ {/* forceNative: an account avatar must not fetch a glyph from a CDN. */}+ <DynamicIcon value={pickerValueFromLibrary(icon.value)} size={32} forceNative />+ </span>+ );+ }+ // Stored `preset` icons predate the picker; they must keep rendering.const Icon = PRESET_ICON[icon.id];return (<span className={cn("grid size-16 place-items-center rounded-full bg-primary text-primary-foreground", className)}>diff --git a/frontend/slices/os-settings/components/account-profile-card.tsx b/frontend/slices/os-settings/components/account-profile-card.tsxindex 8d9151aa..c378dcd6 100644--- a/frontend/slices/os-settings/components/account-profile-card.tsx+++ b/frontend/slices/os-settings/components/account-profile-card.tsx@@ -8,11 +8,46 @@ import { Input } from "@/components/ui/input";import { ACCOUNT_PRESETS, DEFAULT_ACCOUNT_PROFILE, type AccountIcon, type AccountProfile } from "@/lib/auth/account-profile-model";import { IS_DEMO } from "@/lib/demo";import { SettingsBlock, SettingsSection } from "@/features/shell-settings";+import { IconPickerPopover } from "@/features/icon-picker";import type { DeviceRole } from "@/lib/auth/roles";import type { SessionStatus } from "@/features/auth";-import { AccountAvatar, AccountPresetButton } from "./account-avatar";+import { AccountAvatar, AccountPresetButton, libraryValueFromPicker, pickerValueFromLibrary } from "./account-avatar";++// The route caps the raw upload at 8 MiB, but proxy.ts (and scripts/server.mjs)+// reject any body over 1 MiB before a route runs, so a phone photo is pre-shrunk+// here. This is a transport optimisation only: the server decodes and re-encodes+// what it stores, and the client's bytes are never trusted.+const MAX_UPLOAD_BYTES = 8 * 1024 * 1024;+/** Mirror of `PROXY_BODY_LIMIT` in scripts/server-body-policy.mjs. */+const TRANSPORT_LIMIT_BYTES = 1024 * 1024;+const PRESHRINK_MAX_EDGE = 1024;+const UPLOAD_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif", "image/avif"];++/** Downscale + re-encode in the browser so the upload clears the proxy body+ * limit. Falls back to the original file when canvas is unavailable. */+async function preshrink(file: File): Promise<Blob> {+ try {+ const bitmap = await createImageBitmap(file, { imageOrientation: "from-image" });+ const scale = Math.min(1, PRESHRINK_MAX_EDGE / Math.max(bitmap.width, bitmap.height));+ const width = Math.max(1, Math.round(bitmap.width * scale));+ const height = Math.max(1, Math.round(bitmap.height * scale));+ const canvas = document.createElement("canvas");+ canvas.width = width;+ canvas.height = height;+ const context = canvas.getContext("2d");+ if (!context) return file;+ context.drawImage(bitmap, 0, 0, width, height);+ bitmap.close();+ for (const quality of [0.9, 0.75, 0.6]) {+ const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, "image/webp", quality));+ if (blob && blob.size > 0 && blob.size < file.size) return blob;+ }+ return file;+ } catch {+ return file;+ }+}-const MAX_IMAGE_BYTES = 24 * 1024;async function saveProfile(patch: { name?: string; icon?: AccountIcon }): Promise<AccountProfile> {const response = await fetch("/api/auth/account", {@@ -26,6 +61,31 @@ async function saveProfile(patch: { name?: string; icon?: AccountIcon }): Promisreturn body;}+async function uploadIcon(file: File): Promise<AccountProfile> {+ const shrunk = await preshrink(file);+ // proxy.ts rejects any body over 1 MiB before the route sees it, so surface the+ // real reason here instead of a bare 413 from middleware.+ if (shrunk.size > TRANSPORT_LIMIT_BYTES) throw new Error("too_large");+ const response = await fetch("/api/auth/account/icon", {+ method: "POST",+ credentials: "same-origin",+ headers: { "content-type": shrunk.type || "image/webp" },+ body: shrunk,+ });+ const body = (await response.json().catch(() => ({}))) as AccountProfile & { error?: string };+ if (!response.ok) throw new Error(body.error || "upload_failed");+ return body;+}++const UPLOAD_ERROR: Record<string, string> = {+ too_large: "That image is too large to upload. Pick a smaller one.",+ too_many_pixels: "That image has too many pixels to convert safely.",+ unsupported_type: "Use a PNG, JPEG, WebP, GIF, or AVIF.",+ invalid_image: "Couldn't decode that image.",+ owner_required: "Only an Owner device can change the icon.",+ request_too_large: "That image is too large to upload. Pick a smaller one.",+};+export function AccountProfileCard({ status, role }: { status: SessionStatus; role: DeviceRole | null }) {const owner = status === "in" && role === "owner";const [profile, setProfile] = useState<AccountProfile>(DEFAULT_ACCOUNT_PROFILE);@@ -34,6 +94,7 @@ export function AccountProfileCard({ status, role }: { status: SessionStatus; roconst [notice, setNotice] = useState<string | null>(null);const [busy, setBusy] = useState(false);const [loaded, setLoaded] = useState(false);+ const [classic, setClassic] = useState(false);const fileRef = useRef<HTMLInputElement>(null);useEffect(() => {@@ -71,24 +132,35 @@ export function AccountProfileCard({ status, role }: { status: SessionStatus; ro}}- function onFile(file: File | undefined) {+ async function onFile(file: File | undefined) {if (!file) return;- if (!["image/png", "image/jpeg", "image/webp", "image/gif"].includes(file.type) || file.size > MAX_IMAGE_BYTES) {- setError("Use a PNG, JPEG, WebP, or GIF under 24 KB.");- return;+ setError(null);+ setNotice(null);+ if (!UPLOAD_TYPES.includes(file.type)) { setError(UPLOAD_ERROR.unsupported_type!); return; }+ if (file.size > MAX_UPLOAD_BYTES) { setError(UPLOAD_ERROR.too_large!); return; }+ setBusy(true);+ try {+ const next = await uploadIcon(file);+ setProfile(next);+ setName(next.name);+ setNotice("Icon updated.");+ } catch (cause) {+ const code = cause instanceof Error ? cause.message : "";+ setError(UPLOAD_ERROR[code] ?? "Couldn't convert that image.");+ } finally {+ setBusy(false);}- const reader = new FileReader();- reader.onload = () => {- const src = typeof reader.result === "string" ? reader.result : "";- if (!src.startsWith("data:image/")) {- setError("Couldn't read that image.");- return;- }- void commit({ icon: { type: "image", src } }, "Icon updated.");- };- reader.readAsDataURL(file);}+ /** The picker emits bare glyphs for emoji; the store needs the `emoji:` namespace. */+ function onPickIcon(next: string) {+ const value = libraryValueFromPicker(next);+ if (!value || value === "emoji:") return;+ void commit({ icon: { type: "library", value } }, "Icon updated.");+ }++ const pickerValue = profile.icon.type === "library" ? pickerValueFromLibrary(profile.icon.value) : null;+return (<SettingsSection icon={<UserRound />} title="Profile" footnote={owner ? "The display name and icon are for this server's owner account. They are not the login secret." : undefined}>{IS_DEMO ? <SettingsBlock><p className="text-sm text-muted-foreground">Account name and icon are unavailable in this demo.</p></SettingsBlock> : null}@@ -113,13 +185,23 @@ export function AccountProfileCard({ status, role }: { status: SessionStatus; ro<Button type="button" className="min-h-11" disabled={busy || name.trim() === profile.name} onClick={() => void commit({ name }, "Account renamed.")}>Rename account</Button><div className="space-y-2"><p className="text-sm">Change icon</p>- <div className="grid grid-cols-4 gap-2" role="group" aria-label="Change icon">- {ACCOUNT_PRESETS.map((id) => (- <AccountPresetButton key={id} id={id} disabled={busy} pressed={profile.icon.type === "preset" && profile.icon.id === id} onSelect={(preset) => void commit({ icon: { type: "preset", id: preset } }, "Icon updated.")} />- ))}+ <div className="flex flex-wrap items-center gap-2">+ <IconPickerPopover value={pickerValue} onChange={onPickIcon} onClear={() => void commit({ icon: { type: "preset", id: "user" } }, "Icon reset.")}>+ <Button type="button" variant="secondary" className="min-h-11" disabled={busy}>Choose icon…</Button>+ </IconPickerPopover>+ <Button type="button" variant="secondary" className="min-h-11" disabled={busy} onClick={() => fileRef.current?.click()}>Upload image</Button>+ <input ref={fileRef} type="file" accept={UPLOAD_TYPES.join(",")} className="sr-only" aria-label="Upload icon" onChange={(event) => { void onFile(event.target.files?.[0]); event.target.value = ""; }} /></div>- <Button type="button" variant="secondary" className="min-h-11" disabled={busy} onClick={() => fileRef.current?.click()}>Upload icon</Button>- <input ref={fileRef} type="file" accept="image/png,image/jpeg,image/webp,image/gif" className="sr-only" aria-label="Upload icon" onChange={(event) => { onFile(event.target.files?.[0]); event.target.value = ""; }} />+ <Button type="button" variant="ghost" className="h-8 px-2 text-xs text-muted-foreground" aria-expanded={classic} onClick={() => setClassic((open) => !open)}>+ {classic ? "Hide classic icons" : "Classic icons"}+ </Button>+ {classic ? (+ <div className="grid grid-cols-4 gap-2" role="group" aria-label="Classic icons">+ {ACCOUNT_PRESETS.map((id) => (+ <AccountPresetButton key={id} id={id} disabled={busy} pressed={profile.icon.type === "preset" && profile.icon.id === id} onSelect={(preset) => void commit({ icon: { type: "preset", id: preset } }, "Icon updated.")} />+ ))}+ </div>+ ) : null}</div></> : <p className="text-sm text-muted-foreground">An Owner device can rename this account or change its icon.</p>}{error ? <p role="alert" className="text-sm text-destructive">{error}</p> : null}diff --git a/frontend/slices/os-settings/components/update-automation-card.test.ts b/frontend/slices/os-settings/components/update-automation-card.test.tsnew file mode 100644index 00000000..d464dbc3--- /dev/null+++ b/frontend/slices/os-settings/components/update-automation-card.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from "vitest";+import { readFileSync } from "node:fs";+import path from "node:path";+import { describeLastAttempt, automationDisabledReason } from "./update-automation-client";++const dir = __dirname;+const card = readFileSync(path.join(dir, "update-automation-card.tsx"), "utf8");++const last = (over: Partial<Parameters<typeof describeLastAttempt>[0]> = {}) => ({+ lastAttemptAt: Date.UTC(2026, 9, 21, 4, 31, 9),+ lastResult: "failed" as const,+ consecutiveFailures: 1,+ detail: "FAILED: in-place build failed",+ channel: "stable" as const,+ ...over,+});++describe("update automation panel", () => {+ it("never claims the timer is on when the host says it is not", () => {+ // The card must read `active` (pref AND a real, enabled unit), never `prefs.auto`.+ expect(card).toContain("view?.active === true");+ expect(card).toContain("installed but not enabled");+ expect(card).toContain("not installed");+ });++ it("disables the controls and explains why when the host cannot update", () => {+ const reason = automationDisabledReason({ supported: false, reason: "software updates require the checkout to be on main (current: feat/x)" });+ expect(reason).toContain("on main");+ expect(reason).toContain("stay off");+ expect(card).toContain("disabled={busy || blocked !== null || view === null}");+ expect(card).toContain('role="note"');+ expect(automationDisabledReason({ supported: true, reason: null })).toBeNull();+ expect(automationDisabledReason(null)).toBeNull();+ });++ it("reports the last unattended attempt and surfaces the two-failure pause", () => {+ expect(describeLastAttempt(last())).toBe("Last attempt 2026-10-21 04:31:09 UTC — failed.");+ expect(describeLastAttempt(last({ consecutiveFailures: 2 }))).toContain("Paused after 2 failed builds");+ expect(describeLastAttempt(last({ lastResult: "ok", consecutiveFailures: 0 }))).toContain("succeeded");+ expect(describeLastAttempt(last({ lastAttemptAt: null }))).toBe("No automatic attempt yet.");+ });++ it("names the updater rule and the honest stable fallback in the copy", () => {+ expect(card).toContain("never");+ expect(card).toContain("updater itself");+ expect(card).toContain("no tag exists yet");+ });+});diff --git a/frontend/slices/os-settings/components/update-automation-card.tsx b/frontend/slices/os-settings/components/update-automation-card.tsxnew file mode 100644index 00000000..712f8afd--- /dev/null+++ b/frontend/slices/os-settings/components/update-automation-card.tsx@@ -0,0 +1,120 @@+"use client";++import { useCallback, useEffect, useState } from "react";+import { MoonStar } from "lucide-react";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Switch } from "@/components/ui/switch";+import { IS_DEMO } from "@/lib/demo";+import { SettingsRow as Row, SettingsValueRow } from "@/features/shell-settings";+import {+ automationDisabledReason,+ describeLastAttempt,+ readAutomation,+ writeAutomation,+ type AutomationView,+} from "./update-automation-client";++/**+ * Opt-in unattended updates + channel. Mounts INSIDE the Updates card, so it+ * renders rows rather than another card. Every value it shows comes from the host+ * (pref + the REAL timer unit state), never from local state: a stored `auto:true`+ * with a deleted unit must read "off".+ */+export function UpdateAutomationCard() {+ const [view, setView] = useState<AutomationView | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);++ const load = useCallback(+ () => readAutomation().then((next) => { setView(next); setError(null); }, (cause: unknown) => {+ setError(cause instanceof Error ? cause.message : "Could not read update automation.");+ }),+ [],+ );++ useEffect(() => {+ if (!IS_DEMO) void load();+ }, [load]);++ const save = async (patch: { auto?: boolean; channel?: "stable" | "main" }) => {+ setBusy(true);+ try {+ setView(await writeAutomation(patch));+ setError(null);+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : "Could not save automatic updates.");+ // The host refused (unsupported checkout, missing timer): re-read so the+ // switch snaps back to the truth instead of showing the click.+ await load();+ } finally {+ setBusy(false);+ }+ };++ if (IS_DEMO) return null;++ const blocked = automationDisabledReason(view);+ const active = view?.active === true;+ const channel = view?.prefs.channel ?? "stable";++ return (+ <>+ <Row label="Update automatically at night">+ <Switch+ checked={active}+ disabled={busy || blocked !== null || view === null}+ onCheckedChange={(next) => void save({ auto: next })}+ aria-label="Update automatically at night"+ />+ </Row>+ <Row label="Update channel">+ <Select+ value={channel}+ disabled={busy || blocked !== null || view === null}+ onValueChange={(next) => void save({ channel: next === "main" ? "main" : "stable" })}+ >+ <SelectTrigger className="w-44" aria-label="Update channel">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="stable">Stable releases</SelectItem>+ <SelectItem value="main">Rolling main</SelectItem>+ </SelectContent>+ </Select>+ </Row>+ <SettingsValueRow+ label="Nightly timer"+ value={+ view === null+ ? "checking…"+ : active+ ? `scheduled${view.timer.nextRun ? ` · next ${view.timer.nextRun}` : ""}`+ : view.timer.installed+ ? "installed but not enabled"+ : "not installed"+ }+ />+ <SettingsValueRow label="Last automatic attempt" value={describeLastAttempt(view?.last)} />++ <div className="px-4 pb-3 text-[11px] leading-relaxed text-muted-foreground">+ {blocked ? (+ <p role="note" className="text-destructive-text">{blocked}</p>+ ) : (+ <p className="flex gap-1.5">+ <MoonStar className="mt-0.5 size-3.5 shrink-0" aria-hidden />+ <span>+ Runs between 04:30 and 04:55 with a random delay. It refuses on a dirty+ checkout, a running update, or two failed builds in a row, and never+ applies a commit that changes the updater itself.+ {channel === "stable"+ ? " Stable updates to the newest release tag; if no tag exists yet it follows main."+ : " Rolling main applies every commit on main."}+ </span>+ </p>+ )}+ {view?.drift && <p role="alert" className="mt-1.5 text-amber-500">{view.drift}</p>}+ {error && <p role="alert" className="mt-1.5 text-destructive-text">{error}</p>}+ </div>+ </>+ );+}diff --git a/frontend/slices/os-settings/components/update-automation-client.ts b/frontend/slices/os-settings/components/update-automation-client.tsnew file mode 100644index 00000000..7f811486--- /dev/null+++ b/frontend/slices/os-settings/components/update-automation-client.ts@@ -0,0 +1,59 @@+import type { AutoUpdateResult } from "@/lib/prefs/auto-update-state";+import type { PrefUpdates } from "@/lib/prefs/updates";++/** Shape of GET/POST /api/v1/sys/update/automation. `active` is the intersection of+ * the pref and the REAL timer unit — never the pref alone. */+export interface AutomationView {+ prefs: PrefUpdates;+ timer: { installed: boolean; enabled: boolean; active: boolean; nextRun: string | null };+ active: boolean;+ last: {+ lastAttemptAt: number | null;+ lastResult: AutoUpdateResult | null;+ consecutiveFailures: number;+ detail: string | null;+ channel: "stable" | "main" | null;+ };+ drift: string | null;+ supported: boolean;+ reason: string | null;+}++export async function readAutomation(): Promise<AutomationView> {+ const res = await fetch("/api/v1/sys/update/automation", { cache: "no-store", signal: AbortSignal.timeout(20_000) });+ if (!res.ok) throw new Error(res.status === 401 || res.status === 403+ ? "Sign in as an Owner to change automatic updates."+ : `Could not read update automation (HTTP ${res.status}).`);+ return (await res.json()) as AutomationView;+}++export async function writeAutomation(patch: { auto?: boolean; channel?: "stable" | "main" }): Promise<AutomationView> {+ const res = await fetch("/api/v1/sys/update/automation", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ updates: patch }),+ cache: "no-store",+ signal: AbortSignal.timeout(50_000),+ });+ const body = (await res.json().catch(() => ({}))) as AutomationView & { error?: string };+ if (!res.ok) throw new Error(body.error ?? `Could not save automatic updates (HTTP ${res.status}).`);+ return body;+}++/** The timer is off for a reason the operator cannot fix from this screen. */+export function automationDisabledReason(view: Pick<AutomationView, "supported" | "reason"> | null): string | null {+ if (view && view.supported === false) {+ return `${view.reason ?? "This deployment cannot update itself."} Automatic updates stay off until the checkout can update.`;+ }+ return null;+}++const RESULTS: Record<AutoUpdateResult, string> = { ok: "succeeded", failed: "failed", skipped: "skipped" };++export function describeLastAttempt(last: AutomationView["last"] | undefined): string {+ if (!last?.lastAttemptAt) return "No automatic attempt yet.";+ const when = new Date(last.lastAttemptAt).toISOString().replace("T", " ").slice(0, 19) + " UTC";+ const result = last.lastResult ? RESULTS[last.lastResult] : "finished";+ const pause = last.consecutiveFailures >= 2 ? " Paused after 2 failed builds." : "";+ return `Last attempt ${when} — ${result}.${pause}`;+}diff --git a/frontend/slices/os-settings/components/update-section.tsx b/frontend/slices/os-settings/components/update-section.tsxindex 8cfb1f3f..d216e181 100644--- a/frontend/slices/os-settings/components/update-section.tsx+++ b/frontend/slices/os-settings/components/update-section.tsx@@ -5,6 +5,7 @@ import { ArrowDownToLine, BookOpen, RefreshCw, Search } from "lucide-react";import { SettingsActionRow, SettingsSection } from "@/features/shell-settings";import { IS_DEMO } from "@/lib/demo";import type { UpdateStatus } from "@/lib/host/self-update";+import { UpdateAutomationCard } from "./update-automation-card";import { UpdateNotesDrawer } from "./update-notes-drawer";import { UpdateStatusCard, UpdateStatusSkeleton, UpdateStatusUnavailable } from "./update-status-card";import { UpdateStatusUnsupported } from "./update-status-unsupported";@@ -152,6 +153,10 @@ export function UpdateSection() {finished={finished}/>+ {/* Opt-in nightly updates. Rendered inside the same SettingsSection because it+ reads as settings rows, not as a second card. */}+ <UpdateAutomationCard />+{behind > 0 && ahead === 0 && (<SettingsActionRowlabel={diff --git a/lib/auth/account-icon-image.test.ts b/lib/auth/account-icon-image.test.tsnew file mode 100644index 00000000..87da81b1--- /dev/null+++ b/lib/auth/account-icon-image.test.ts@@ -0,0 +1,138 @@+import sharp from "sharp";+import { describe, expect, it } from "vitest";+import {+ AccountIconError,+ buildIco,+ convertAccountIcon,+ MAX_INPUT_BYTES,+ MAX_PIXELS,+} from "./account-icon-image";++const PNG_SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);++async function photoWithExif(): Promise<Buffer> {+ return sharp({ create: { width: 300, height: 200, channels: 3, background: "#3a7bd5" } })+ .jpeg({ quality: 90 })+ .withMetadata({+ exif: {+ IFD0: { ImageDescription: "MSO-TEST-EXIF", Make: "MSO", Model: "TestCam" },+ IFD3: { GPSLatitudeRef: "S", GPSLatitude: "1/1 2/1 3/1" },+ },+ })+ .toBuffer();+}++describe("convertAccountIcon", () => {+ it("strips EXIF/GPS and returns WebP by magic", async () => {+ const input = await photoWithExif();+ expect((await sharp(input).metadata()).exif).toBeTruthy();++ const out = await convertAccountIcon(input, "image/jpeg");+ const meta = await sharp(out.webp).metadata();+ expect(meta.format).toBe("webp");+ expect(meta.width).toBe(256);+ expect(meta.height).toBe(256);+ // No EXIF, GPS, or ICC profile survives the re-encode.+ expect(meta.exif).toBeUndefined();+ expect(meta.icc).toBeUndefined();+ expect(out.webp.subarray(0, 4).toString("ascii")).toBe("RIFF");+ expect(out.webp.subarray(8, 12).toString("ascii")).toBe("WEBP");+ expect(out.webp.length).toBeLessThanOrEqual(28_000);+ expect(out.webp.includes(Buffer.from("EXIF"))).toBe(false);+ expect(out.webp.includes(Buffer.from("GPS"))).toBe(false);+ expect(out.webp.includes(Buffer.from("MSO-TEST-EXIF"))).toBe(false);+ expect(out.webp.includes(Buffer.from("TestCam"))).toBe(false);+ });++ it("emits square PNGs for the manifest and Apple touch icon", async () => {+ const out = await convertAccountIcon(await photoWithExif(), "image/jpeg");+ for (const [buffer, size] of [[out.png192, 192], [out.png512, 512], [out.apple180, 180]] as const) {+ expect(buffer.subarray(0, 8).equals(PNG_SIG)).toBe(true);+ const meta = await sharp(buffer).metadata();+ expect(meta.format).toBe("png");+ expect([meta.width, meta.height]).toEqual([size, size]);+ }+ });++ it("builds an ICO whose directory offsets tile the PNG payloads exactly", async () => {+ const out = await convertAccountIcon(await photoWithExif(), "image/jpeg");+ const ico = out.ico;+ expect(ico.readUInt16LE(0)).toBe(0); // reserved+ expect(ico.readUInt16LE(2)).toBe(1); // type = icon+ const count = ico.readUInt16LE(4);+ expect(count).toBe(3);++ let expectedOffset = 6 + 16 * count;+ const sizes: number[] = [];+ for (let index = 0; index < count; index++) {+ const entry = 6 + 16 * index;+ const width = ico.readUInt8(entry);+ const height = ico.readUInt8(entry + 1);+ expect(width).toBe(height);+ sizes.push(width === 0 ? 256 : width);+ expect(ico.readUInt8(entry + 2)).toBe(0); // palette+ expect(ico.readUInt8(entry + 3)).toBe(0); // reserved+ expect(ico.readUInt16LE(entry + 4)).toBe(1); // planes+ expect(ico.readUInt16LE(entry + 6)).toBe(32); // bpp++ const length = ico.readUInt32LE(entry + 8);+ const offset = ico.readUInt32LE(entry + 12);+ // Every entry starts exactly where the previous payload ended…+ expect(offset).toBe(expectedOffset);+ // …lands on a real PNG signature…+ expect(ico.subarray(offset, offset + 8).equals(PNG_SIG)).toBe(true);+ // …and covers a complete PNG of that size.+ const payload = ico.subarray(offset, offset + length);+ expect(payload.length).toBe(length);+ const meta = await sharp(payload).metadata();+ expect(meta.format).toBe("png");+ expect([meta.width, meta.height]).toEqual([sizes[index], sizes[index]]);+ expectedOffset += length;+ }+ // No gaps and nothing after the last payload.+ expect(expectedOffset).toBe(ico.length);+ expect(sizes).toEqual([16, 32, 48]);+ });++ it("rejects oversize input rather than truncating it", async () => {+ const oversize = Buffer.alloc(MAX_INPUT_BYTES + 1, 0x41);+ await expect(convertAccountIcon(oversize, "image/png")).rejects.toMatchObject({ code: "too_large" });+ await expect(convertAccountIcon(oversize, "image/png")).rejects.toBeInstanceOf(AccountIconError);+ });++ it("rejects a decompression bomb by decoded area before decoding", async () => {+ // 9000×5000 = 45 MP: small as a JPEG, far too large once decoded.+ const bomb = await sharp({ create: { width: 9000, height: 5000, channels: 3, background: "#101010" } })+ .jpeg({ quality: 40 })+ .toBuffer();+ expect(bomb.length).toBeLessThan(MAX_INPUT_BYTES);+ expect(9000 * 5000).toBeGreaterThan(MAX_PIXELS);+ await expect(convertAccountIcon(bomb, "image/jpeg")).rejects.toMatchObject({ code: "too_many_pixels" });+ });++ it("rejects a declared type it cannot decode and non-image bytes", async () => {+ await expect(convertAccountIcon(Buffer.from("hello"), "text/plain")).rejects.toMatchObject({ code: "unsupported_type" });+ await expect(convertAccountIcon(Buffer.from("not an image"), "image/png")).rejects.toMatchObject({ code: "invalid_image" });+ await expect(convertAccountIcon(Buffer.alloc(0), "image/png")).rejects.toMatchObject({ code: "invalid_image" });+ });++ it("rasterises SVG and flattens alpha onto a square background", async () => {+ const svg = Buffer.from(+ `<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><circle cx="32" cy="32" r="30" fill="#ffffff"/></svg>`,+ );+ const out = await convertAccountIcon(svg, "image/svg+xml");+ const meta = await sharp(out.webp).metadata();+ expect([meta.width, meta.height]).toEqual([256, 256]);+ expect(meta.hasAlpha).toBe(false);+ });++ it("writes an ICO directory with the documented header layout", () => {+ const ico = buildIco([{ size: 16, png: Buffer.from([1, 2, 3]) }]);+ expect(ico.length).toBe(6 + 16 + 3);+ expect(ico.readUInt16LE(2)).toBe(1);+ expect(ico.readUInt16LE(4)).toBe(1);+ expect(ico.readUInt32LE(6 + 8)).toBe(3);+ expect(ico.readUInt32LE(6 + 12)).toBe(22);+ expect(ico.readUInt8(6)).toBe(16);+ });+});diff --git a/lib/auth/account-icon-image.ts b/lib/auth/account-icon-image.tsnew file mode 100644index 00000000..ed8df98d--- /dev/null+++ b/lib/auth/account-icon-image.ts@@ -0,0 +1,191 @@+import sharp from "sharp";+import type { AccountIcon } from "./account-profile-model";++// Server-side icon pipeline: one decode, then every size the app needs. The+// browser never decides what is stored — it uploads raw bytes, this module+// normalises and re-encodes them. Metadata (EXIF/GPS/ICC) is dropped because no+// output below calls `withMetadata()`.+//+// sharp cannot write ICO (its output formats stop at png/webp/jpeg/avif/tiff/gif+// on this host), so `buildIco` writes the 6-byte ICONDIR + N×16-byte entries by+// hand and embeds PNG payloads. That is the whole format browsers need.++export const MAX_INPUT_BYTES = 8 * 1024 * 1024;+/** Decoded-area cap checked BEFORE any resize: a 40 MP image is already 160 MB+ * of RGBA, so anything larger is a decompression bomb, not a phone photo. */+export const MAX_PIXELS = 40_000_000;+/** Headroom under account-profile.ts `imageIcon()` (32_000 decoded bytes). */+const STORED_WEBP_BUDGET = 28_000;+const ICON_WEBP_SIZE = 256;+const ICON_BACKGROUND = "#0a0a0a";+const ICO_SIZES = [16, 32, 48] as const;++const ACCEPTED_MIME = new Set([+ "image/png",+ "image/jpeg",+ "image/webp",+ "image/gif",+ "image/avif",+ "image/heic",+ "image/heif",+ "image/svg+xml",+]);++export type ConvertedIcon = {+ webp: Buffer;+ png192: Buffer;+ png512: Buffer;+ apple180: Buffer;+ ico: Buffer;+};++export class AccountIconError extends Error {+ constructor(+ readonly code:+ | "too_large"+ | "too_many_pixels"+ | "unsupported_type"+ | "invalid_image"+ | "webp_too_large",+ ) {+ super(code);+ this.name = "AccountIconError";+ }+}++/** `limitInputPixels` is enforced by libvips during decode, so a bomb fails+ * before the pixel buffer is allocated. */+function load(bytes: Buffer) {+ return sharp(bytes, { limitInputPixels: MAX_PIXELS, animated: false, failOn: "error" }).rotate();+}++/** Header-only probe. `limitInputPixels: false` is safe here because metadata()+ * reads dimensions without allocating the pixel buffer; the area check below+ * then decides whether a full decode is allowed. Decoding always goes through+ * `load()`, which re-imposes the limit, so a lying header cannot get past it. */+function probe(bytes: Buffer) {+ return sharp(bytes, { limitInputPixels: false, animated: false, failOn: "error" });+}++function square(input: Buffer, size: number) {+ return load(input)+ .flatten({ background: ICON_BACKGROUND })+ .resize(size, size, { fit: "cover", position: "centre" });+}++async function squarePng(input: Buffer, size: number): Promise<Buffer> {+ return square(input, size).png({ compressionLevel: 9 }).toBuffer();+}++async function squareWebp(input: Buffer): Promise<Buffer> {+ // Photos at q82 land around 10–20 KB; step down only when a noisy image would+ // otherwise break the stored cap. Never truncate — re-encode or reject.+ for (const quality of [82, 72, 62, 52, 40]) {+ const out = await square(input, ICON_WEBP_SIZE).webp({ quality, effort: 4 }).toBuffer();+ if (out.length <= STORED_WEBP_BUDGET) return out;+ }+ throw new AccountIconError("webp_too_large");+}++/** ICONDIR + ICONDIRENTRY table, then the PNG payloads back to back. Width and+ * height are one byte each, with 256 encoded as 0. */+export function buildIco(images: readonly { size: number; png: Buffer }[]): Buffer {+ const header = Buffer.alloc(6 + 16 * images.length);+ header.writeUInt16LE(0, 0); // reserved+ header.writeUInt16LE(1, 2); // type: icon+ header.writeUInt16LE(images.length, 4);+ let offset = header.length;+ images.forEach((image, index) => {+ const entry = 6 + 16 * index;+ const edge = image.size >= 256 ? 0 : image.size;+ header.writeUInt8(edge, entry);+ header.writeUInt8(edge, entry + 1);+ header.writeUInt8(0, entry + 2); // palette size+ header.writeUInt8(0, entry + 3); // reserved+ header.writeUInt16LE(1, entry + 4); // colour planes+ header.writeUInt16LE(32, entry + 6); // bits per pixel+ header.writeUInt32LE(image.png.length, entry + 8);+ header.writeUInt32LE(offset, entry + 12);+ offset += image.png.length;+ });+ return Buffer.concat([header, ...images.map((image) => image.png)]);+}++/** Convert raw upload bytes into every stored/served form. Throws+ * `AccountIconError` for anything the trust boundary refuses. */+export async function convertAccountIcon(input: Buffer, mime: string): Promise<ConvertedIcon> {+ if (input.length === 0) throw new AccountIconError("invalid_image");+ if (input.length > MAX_INPUT_BYTES) throw new AccountIconError("too_large");+ if (!ACCEPTED_MIME.has(mime.split(";")[0]!.trim().toLowerCase())) {+ throw new AccountIconError("unsupported_type");+ }+ let width = 0;+ let height = 0;+ try {+ const meta = await probe(input).metadata();+ width = meta.width ?? 0;+ height = meta.height ?? 0;+ } catch {+ throw new AccountIconError("invalid_image");+ }+ // SVG without intrinsic width/height is refused: there is nothing to bound.+ if (width < 1 || height < 1) throw new AccountIconError("invalid_image");+ if (width * height > MAX_PIXELS) throw new AccountIconError("too_many_pixels");++ const [webp, png192, png512, apple180, ...icoPngs] = await Promise.all([+ squareWebp(input),+ squarePng(input, 192),+ squarePng(input, 512),+ squarePng(input, 180),+ ...ICO_SIZES.map((size) => squarePng(input, size)),+ ]);+ return {+ webp,+ png192,+ png512,+ apple180,+ ico: buildIco(ICO_SIZES.map((size, index) => ({ size, png: icoPngs[index]! }))),+ };+}++const DATA_URL = /^data:image\/[a-z+]+;base64,([A-Za-z0-9+/]+={0,2})$/;++function storedBytes(icon: AccountIcon): Buffer | null {+ if (icon.type !== "image") return null;+ const match = DATA_URL.exec(icon.src);+ return match?.[1] ? Buffer.from(match[1], "base64") : null;+}++/** Brand art fallback, inlined on purpose. Reading `public/icon.svg` at request time+ * with `fs.readFile(path.join(process.cwd(), …))` made Turbopack trace the whole+ * project as a dynamic filesystem dependency ("Dynamic filesystem access causes+ * tracing of the whole project"), which the release gate treats as a build warning+ * and therefore a failure. The mark is a fixed glyph, so it belongs in the bundle. */+const BRAND_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><defs><linearGradient id="b" x1="48" y1="40" x2="466" y2="474" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#4a7cf8"/><stop offset="1" stop-color="#6a54f8"/></linearGradient></defs><rect width="512" height="512" rx="116" fill="url(#b)"/><g fill="none" stroke="#ffffff" stroke-width="20" stroke-linecap="round" stroke-linejoin="round"><path d="M138 150 L238 150 L292 179 L374 179 Q402 179 402 207 L402 370 Q402 398 374 398 L138 398 Q110 398 110 370 L110 178 Q110 150 138 150 Z"/><path d="M166 272 L204 302 L166 332"/><path d="M226 348 L286 348"/><path d="M320 272 L358 302 L320 332"/></g><g fill="#ffffff"><circle cx="150" cy="188" r="11"/><circle cx="186" cy="188" r="11"/><circle cx="222" cy="188" r="11"/></g></svg>`;++export async function brandPng(size: number): Promise<Buffer> {+ return load(Buffer.from(BRAND_SVG))+ .flatten({ background: ICON_BACKGROUND })+ .resize(size, size, { fit: "contain", position: "centre" })+ .png({ compressionLevel: 9 })+ .toBuffer();+}++/** Square PNG for a public icon route: the owner's image when one is stored,+ * the brand mark otherwise. Never throws: a corrupt stored icon must not take+ * the favicon down with it. */+export async function accountIconPng(icon: AccountIcon, size: number): Promise<Buffer> {+ const bytes = storedBytes(icon);+ if (bytes) {+ try {+ return await squarePng(bytes, size);+ } catch {+ // Fall through to the brand mark.+ }+ }+ try {+ return await brandPng(size);+ } catch {+ return Buffer.alloc(0);+ }+}diff --git a/lib/auth/account-profile-model.ts b/lib/auth/account-profile-model.tsindex 8d01d033..429ad99c 100644--- a/lib/auth/account-profile-model.ts+++ b/lib/auth/account-profile-model.ts@@ -7,6 +7,9 @@ export type AccountPreset = (typeof ACCOUNT_PRESETS)[number];export type AccountIcon =| { type: "preset"; id: AccountPreset }+ // Emoji/lucide/phosphor value from the icon-picker slice, e.g. "lucide:Star"+ // or "phosphor:Shield?c=0b6e99". Validated in account-profile.ts.+ | { type: "library"; value: string }| { type: "image"; src: string };export type AccountProfile = {diff --git a/lib/auth/account-profile.test.ts b/lib/auth/account-profile.test.tsindex bf8fe472..da6ed77f 100644--- a/lib/auth/account-profile.test.ts+++ b/lib/auth/account-profile.test.ts@@ -61,6 +61,45 @@ describe("account profile", () => {expect(await readAccountProfile()).toEqual(DEFAULT_ACCOUNT_PROFILE);});+ it("stores library icons from the picker and rejects anything outside the allowlist", async () => {+ const accepted = [+ "emoji:🦊",+ "emoji:👨👩👧",+ "lucide:Star",+ "lucide:FileText",+ "phosphor:ShieldCheck?c=0b6e99",+ "emoji:🎯?c=F59E0B",+ ];+ for (const value of accepted) {+ await writeAccountProfile({ icon: { type: "library", value } });+ expect(await readAccountProfile()).toMatchObject({ icon: { type: "library", value } });+ }+ // Old stores still load: preset and image icons keep working beside it.+ await writeAccountProfile({ icon: { type: "preset", id: "leaf" } });+ expect(await readAccountProfile()).toMatchObject({ icon: { type: "preset", id: "leaf" } });+ await writeAccountProfile({ icon: { type: "image", src: png } });+ expect(await readAccountProfile()).toMatchObject({ icon: { type: "image", src: png } });++ const rejected = [+ "lucide:__proto__",+ "lucide:Star?c=12345",+ "lucide:Star?c=0b6e99&x=1",+ "lucide:../etc/passwd",+ "phosphor:<script>",+ "emoji:",+ "emoji:two words",+ "javascript:alert(1)",+ "lucide:Star?c=0b6e99\n",+ "x".repeat(97),+ ];+ for (const value of rejected) {+ await expect(writeAccountProfile({ icon: { type: "library", value } })).rejects.toMatchObject({ code: "invalid" });+ }+ const before = await readAccountProfile();+ await expect(writeAccountProfile({ icon: { type: "library", value: { $ne: null } } })).rejects.toMatchObject({ code: "invalid" });+ expect(await readAccountProfile()).toEqual(before);+ });+it("fails closed on a corrupt profile instead of replacing it", async () => {await fs.mkdir(dir, { recursive: true });await fs.writeFile(file, "{", "utf8");diff --git a/lib/auth/account-profile.ts b/lib/auth/account-profile.tsindex 2e091440..18f02f60 100644--- a/lib/auth/account-profile.ts+++ b/lib/auth/account-profile.ts@@ -12,6 +12,10 @@ import {const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);const DATA_URL = /^data:image\/(png|jpeg|webp|gif);base64,([A-Za-z0-9+/]+={0,2})$/;+// Picker values: emoji glyph (1..8 non-space chars), lucide:Name, phosphor:Name,+// and an optional `?c=<6-digit hex>` tint. Charset-only names mean `__proto__`+// and friends cannot survive; the length cap bounds the rest.+const LIBRARY_ICON = /^(emoji:[^\s]{1,8}|lucide:[A-Za-z0-9]+|phosphor:[A-Za-z0-9]+)(\?c=[0-9a-fA-F]{6})?$/;export class AccountProfileError extends Error {constructor(readonly code: "corrupt" | "invalid") {@@ -94,8 +98,18 @@ function imageIcon(value: unknown): AccountIcon | null {return { type: "image", src: prefix + encodeBase64(bytes) };}+/** Icon-picker value. The picker emits raw glyphs for emoji, so the stored+ * form is `emoji:<glyph>` for those and `lucide:`/`phosphor:` as-is. */+function libraryIcon(value: unknown): AccountIcon | null {+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;+ const row = value as Record<string, unknown>;+ if (row.type !== "library" || typeof row.value !== "string") return null;+ if (row.value.length > 96 || !LIBRARY_ICON.test(row.value)) return null;+ return { type: "library", value: row.value };+}+export function cleanAccountIcon(value: unknown): AccountIcon | null {- return presetIcon(value) ?? imageIcon(value);+ return presetIcon(value) ?? libraryIcon(value) ?? imageIcon(value);}function parseProfile(raw: string): AccountProfile {diff --git a/lib/config/env-example.test.ts b/lib/config/env-example.test.tsindex c1108a2f..484ee92e 100644--- a/lib/config/env-example.test.ts+++ b/lib/config/env-example.test.ts@@ -39,6 +39,9 @@ const NOT_A_KNOB: Record<string, string> = {PATH: "standard executable search path inherited by the lifecycle test harness",HOME: "the OS's",XDG_RUNTIME_DIR: "set by logind, or by the unit — see lib/managed-apps/user-bus.ts",+ // Standard XDG base directory. Read only as the default parent of the update timer+ // units; MSO_SYSTEMD_USER_DIR is the documented override.+ XDG_CONFIG_HOME: "standard XDG base-directory convention; MSO_SYSTEMD_USER_DIR overrides its use",// systemd's, read by instrumentation for the watchdog handshake.NOTIFY_SOCKET: "systemd's",WATCHDOG_USEC: "systemd's",diff --git a/lib/host/project-worktree.test.ts b/lib/host/project-worktree.test.tsindex 758946f6..f768bd9a 100644--- a/lib/host/project-worktree.test.ts+++ b/lib/host/project-worktree.test.ts@@ -78,4 +78,24 @@ describe("task-owned project worktrees", () => {})).resolves.toBe(true);await expect(fs.lstat(workspace.workspacePath)).rejects.toMatchObject({ code: "ENOENT" });});++ it("creates the workspace owner-private even under a group-writable umask", async () => {+ // A host with umask 0002 used to yield a 0775 workspace. Every security store+ // pinned inside it then refused the parent as group-writable, so `bun run verify`+ // failed locally on tests that CI (umask 0022) passed.+ const { repo } = repoFixture();+ const previous = process.umask(0o002);+ let workspace;+ try {+ workspace = await prepareProjectWorktree(repo);+ } finally {+ process.umask(previous);+ }+ const mode = (await fs.stat(workspace.workspacePath)).mode & 0o777;+ expect(mode & 0o022).toBe(0);+ expect(mode).toBe(0o700);+ // The contents still belong to git, so the tree must stay usable.+ expect(execFileSync("git", ["status", "--porcelain"], { cwd: workspace.workspacePath, encoding: "utf8" }).trim()).toBe("");+ await expect(fs.readFile(path.join(workspace.workspacePath, "README.md"), "utf8")).resolves.toBe("fixture\n");+ });});diff --git a/lib/host/project-worktree.ts b/lib/host/project-worktree.tsindex 16bc171e..3989c881 100644--- a/lib/host/project-worktree.ts+++ b/lib/host/project-worktree.ts@@ -84,6 +84,12 @@ export async function prepareProjectWorktree(projectPath: string): Promise<Prepaif (await fs.lstat(workspacePath).catch(() => null)) throw new HostError("Generated agent worktree path already exists");await git(canonicalPath, ["worktree", "add", "--no-track", "-b", branch, workspacePath, baseCommit]);+ // `git worktree add` creates the directory with the process umask, so a host+ // running umask 0002 produces a group-writable workspace. Everything downstream+ // that pins a security store inside the worktree then refuses it as unsafe, which+ // made a local gate run fail on the same tests CI passed. The workspace is this+ // owner's private scratch tree, so it gets the same mode as the root above.+ await fs.chmod(/* turbopackIgnore: true */ workspacePath, 0o700);const workspaceReal = await fs.realpath(workspacePath).catch(() => null);if (!workspaceReal || workspaceReal !== workspacePath) throw new HostError("Created worktree could not be verified");const [workspaceTop, workspaceHead, workspaceStatus] = await Promise.all([diff --git a/lib/host/self-update-auto-contract.test.ts b/lib/host/self-update-auto-contract.test.tsnew file mode 100644index 00000000..a1f3242f--- /dev/null+++ b/lib/host/self-update-auto-contract.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from "vitest";+import { readFileSync } from "node:fs";+import path from "node:path";+import { autoUpdateGate } from "./update-decision";++const root = path.join(__dirname, "..", "..");+const entry = readFileSync(path.join(root, "scripts/mso-auto-update"), "utf8");+const preflight = readFileSync(path.join(root, "scripts/self-update-auto.ts"), "utf8");+const inner = readFileSync(path.join(root, "scripts/self-update.sh"), "utf8");++describe("unattended update wiring", () => {+ it("keeps a refusal out of the unit's failure state", () => {+ // A `SKIP` is a correct decision. Exiting non-zero would make systemd record a+ // failed unit and, with Restart=, retry a host that must not be touched.+ // Accept both spellings of the case pattern: escaped (`SKIP\ *)`), which strict+ // Semgrep cannot parse, and quoted (`"SKIP "*)`), which it can. Both are bash-identical.+ expect(entry.includes("SKIP\\ *) exit 0 ;;") || entry.includes('"SKIP "*) exit 0 ;;')).toBe(true);+ expect(preflight).toContain("SKIP ${reason}");+ });++ it("never lets the timer pass a ref: only the channel enum reaches the updater", () => {+ expect(entry).toContain('stable|main) ;;');+ expect(entry).toContain('"--channel=$channel"');+ expect(entry).not.toMatch(/--channel=\$\(/);+ });++ it("pins the commit the pre-flight inspected", () => {+ expect(preflight).toContain("MSO_AUTO_TARGET_SHA=");+ expect(entry).toContain("export MSO_AUTO_TARGET_SHA");+ expect(inner).toContain("the $CHANNEL target moved after the pre-flight decision");+ });++ it("records a failure with the log's own reason, not a generic one", () => {+ expect(entry).toContain("--record failed");+ expect(preflight).toContain('line.includes("FAILED:")');+ expect(preflight).toContain('consecutiveFailures: result === "failed" ? state.consecutiveFailures + 1');+ });++ it("stops the run before the network when the owner never opted in", () => {+ const off = autoUpdateGate({+ auto: false, supported: true, reason: null, dirty: false, running: false, ahead: 0,+ behind: 4, pendingBuild: false, consecutiveFailures: 0, changedPaths: ["app/page.tsx"],+ target: "origin/main", targetFallback: false,+ });+ expect(off).toMatchObject({ run: false });+ // Compare inside the function body: the import line mentions the collector too.+ const body = preflight.slice(preflight.indexOf("async function decide"));+ expect(body.indexOf("if (!prefs.auto)")).toBeGreaterThan(0);+ expect(body.indexOf("if (!prefs.auto)")).toBeLessThan(body.indexOf("collectUpdateFacts"));+ });+});diff --git a/lib/host/self-update-channel.test.ts b/lib/host/self-update-channel.test.tsnew file mode 100644index 00000000..8c534019--- /dev/null+++ b/lib/host/self-update-channel.test.ts@@ -0,0 +1,60 @@+import { describe, expect, it } from "vitest";+import { chooseUpdateTarget, fetchArgs, releaseTags, resolveUpdateTarget, stableRelationAhead } from "./self-update-channel";++describe("stable channel target resolution", () => {+ it("orders release tags by semver, not by git's output order", () => {+ // `git tag` sorts lexically by default, which puts v0.10.0 before v0.9.0.+ expect(releaseTags("v0.2.0\nv0.10.0\nv0.9.1\n")).toEqual(["v0.10.0", "v0.9.1", "v0.2.0"]);+ });++ it("drops every tag that is not a plain release number", () => {+ // A tag becomes an argv element downstream, so anything else is ignored here+ // rather than escaped later.+ expect(releaseTags("v1.2.3-rc.1\nnightly\nv1.2\nmain\nbackup/pre-update-1\nv0.2.0")).toEqual(["v0.2.0"]);+ });++ it("resolves stable to the newest tag, and rolling to origin/main", () => {+ expect(chooseUpdateTarget("stable", "v0.2.0\nv0.3.1")).toMatchObject({ ref: "v0.3.1", fallback: false });+ expect(chooseUpdateTarget("main", "v9.9.9")).toMatchObject({ ref: "origin/main", fallback: false });+ });++ it("is honest when tags lag behind the running build: no silent rolling fallback", () => {+ // v0.2.0 is an ancestor of main and package.json is far ahead; "stable" still+ // means the tag, so the panel compares against the tag and reports "current".+ const target = chooseUpdateTarget("stable", "v0.2.0");+ expect(target.ref).toBe("v0.2.0");+ expect(target.fallback).toBe(false);+ });++ it("falls back to rolling main ONLY when zero release tags exist, and says so", () => {+ const target = chooseUpdateTarget("stable", "nightly\n");+ expect(target).toMatchObject({ ref: "origin/main", fallback: true });+ expect(target.label).toContain("no release tag exists yet");+ });++ it("never lets a client-supplied string become the ref", async () => {+ const git = async (args: readonly string[]) => {+ if (args[0] === "tag") return { code: 0, stdout: "v1.0.0\n$(rm -rf /)\n../../etc/passwd", stderr: "" };+ return { code: 0, stdout: "abc", stderr: "" };+ };+ const target = await resolveUpdateTarget("stable", git);+ expect(target.ref).toBe("v1.0.0");+ expect(target.ref).not.toContain("passwd");+ // Only fixed argv ever reaches git.+ for (const call of [fetchArgs("stable"), fetchArgs("main")]) {+ for (const arg of call) expect(["fetch", "--quiet", "--tags", "origin", "main"]).toContain(arg);+ }+ });++ it("treats an unreadable tag list as a fallback instead of throwing", async () => {+ const target = await resolveUpdateTarget("stable", async () => ({ code: 1, stdout: "", stderr: "boom" }));+ expect(target.fallback).toBe(true);+ expect(target.ref).toBe("origin/main");+ });++ it("only reports local commits as 'ahead' when the release has something to apply", () => {+ // Past a release tag with no newer tag: this is the normal state, not unpushed work.+ expect(stableRelationAhead(7, 0)).toBe(0);+ expect(stableRelationAhead(7, 2)).toBe(7);+ });+});diff --git a/lib/host/self-update-channel.ts b/lib/host/self-update-channel.tsnew file mode 100644index 00000000..fce84f94--- /dev/null+++ b/lib/host/self-update-channel.ts@@ -0,0 +1,96 @@+import type { UpdateChannel } from "../prefs/updates";++// WHICH COMMIT A "SOFTWARE UPDATE" MEANS. The rolling branch is what this file+// always used; the stable channel is the newest release tag that is reachable from+// `origin/main`. Both are resolved HERE, on the server, from git output — the only+// thing a request (or a unit argument) may choose is the two-word enum.+//+// A tag becomes a git argv element, so it is filtered by this grammar first. A tag+// that does not match is not quoted, escaped or "cleaned": it is ignored.+const RELEASE_TAG = /^v?(\d{1,4})\.(\d{1,4})\.(\d{1,4})$/;++/** The rolling branch. Unchanged from pre-Phase-4 behaviour. */+export const ROLLING_REF = "origin/main";++export interface UpdateTarget {+ channel: UpdateChannel;+ /** Resolved server-side: always `ROLLING_REF` or a RELEASE_TAG match. */+ ref: string;+ /** Human label for the panel. Never used as a command. */+ label: string;+ /** Stable found no release tag and is therefore tracking rolling main. Always+ * reported to the operator — a silent fallback would be a lie about the channel. */+ fallback: boolean;+}++interface Ran {+ code: number;+ stdout: string;+ stderr: string;+}++export type TargetGitRunner = (args: readonly string[]) => Promise<Ran>;++function parts(tag: string): [number, number, number] | null {+ const m = RELEASE_TAG.exec(tag);+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;+}++/** Strict semver release tags, newest first. Unknown shapes are dropped. */+export function releaseTags(stdout: string): string[] {+ const seen = new Set(stdout.split("\n").map((line) => line.trim()).filter((tag) => RELEASE_TAG.test(tag)));+ return [...seen].sort((a, b) => {+ const pa = parts(a) ?? [0, 0, 0];+ const pb = parts(b) ?? [0, 0, 0];+ return pb[0] - pa[0] || pb[1] - pa[1] || pb[2] - pa[2];+ });+}++/** Pure decision: `git tag --merged origin/main --list 'v*'` output → target. */+export function chooseUpdateTarget(channel: UpdateChannel, tagOutput: string): UpdateTarget {+ if (channel === "main") return { channel, ref: ROLLING_REF, label: ROLLING_REF, fallback: false };+ const [tag] = releaseTags(tagOutput);+ if (!tag) {+ return { channel, ref: ROLLING_REF, label: `${ROLLING_REF} (no release tag exists yet)`, fallback: true };+ }+ return { channel, ref: tag, label: tag, fallback: false };+}++/**+ * Ask git for the release tag list, then confirm the chosen tag names a commit.+ *+ * Deliberately no `--sort=-v:refname`: git's version sort orders pre-releases and+ * build metadata differently from semver, and the ordering decision belongs in+ * `releaseTags`, which is covered by tests instead of by a git version.+ */+export async function resolveUpdateTarget(channel: UpdateChannel, git: TargetGitRunner): Promise<UpdateTarget> {+ if (channel === "main") return chooseUpdateTarget("main", "");+ const tags = await git(["tag", "--merged", ROLLING_REF, "--list", "v*"]);+ if (tags.code !== 0) {+ return { channel, ref: ROLLING_REF, label: `${ROLLING_REF} (release tag list unavailable)`, fallback: true };+ }+ const target = chooseUpdateTarget("stable", tags.stdout);+ if (target.fallback) return target;+ const commit = await git(["rev-parse", "--verify", `${target.ref}^{commit}`]);+ if (commit.code === 0) return target;+ return { channel, ref: ROLLING_REF, label: `${ROLLING_REF} (release tag ${target.ref} is unreadable)`, fallback: true };+}++/** `git fetch` arguments. Fixed strings only — no request input.+ * `--tags` is unconditional: a release tag created on a commit we already have is+ * NOT auto-followed by a plain `fetch origin main`, and the stable channel has to+ * see it without a second round trip. */+export function fetchArgs(channel: UpdateChannel): string[] {+ void channel;+ return ["fetch", "--quiet", "--tags", "origin", "main"];+}++/**+ * Stable compares the checkout with a TAG, and a checkout that carries commits+ * after that tag is normal and healthy — it is not "local work that was not+ * pushed". So `ahead` is only meaningful when it also has incoming commits+ * (diverged); otherwise it is reported as 0 and a no-op update reads "up to date".+ */+export function stableRelationAhead(ahead: number, behind: number): number {+ return behind > 0 ? ahead : 0;+}diff --git a/lib/host/self-update-offline.ts b/lib/host/self-update-offline.tsindex c8b3d882..0a106474 100644--- a/lib/host/self-update-offline.ts+++ b/lib/host/self-update-offline.ts@@ -7,7 +7,8 @@ import path from "node:path";* systemd-less hosts still need the updater to outlive the web process it* replaces. `setsid -f` creates a detached process group; the wrapper redirects* its stdio immediately, then runs the same guarded `mso update` path used from a- * terminal. The API still exposes only one boolean: normal update vs rebuild.+ * terminal. The API still exposes only one boolean: normal update vs rebuild. The+ * wrapper reads the channel from the same preference file the panel writes.*/export function offlineUpdateArgs(root: string, rebuildOnly = false): string[] {return [diff --git a/lib/host/self-update-status.test.ts b/lib/host/self-update-status.test.tsindex 5bde89ca..6417aab2 100644--- a/lib/host/self-update-status.test.ts+++ b/lib/host/self-update-status.test.ts@@ -1,8 +1,9 @@import { beforeEach, describe, expect, it, vi } from "vitest";-const fixture = vi.hoisted(() => ({ branch: "main", fetchFails: false, noGit: false, behind: 13 }));+const fixture = vi.hoisted(() => ({ branch: "main", fetchFails: false, noGit: false, behind: 13, tags: "", targetSha: "7cffd11" }));vi.mock("server-only", () => ({}));vi.mock("node:fs", () => ({ promises: { readFile: vi.fn(async () => "") } }));+vi.mock("@/lib/prefs/store", () => ({ readPrefs: vi.fn(async () => ({})) }));vi.mock("node:child_process", () => ({execFile: vi.fn((command: string, args: string[], _options: unknown, done: (error: { code: number } | null, stdout: string, stderr: string) => void) => {let output = "", code = 0;@@ -14,8 +15,12 @@ vi.mock("node:child_process", () => ({else if (key === "remote get-url origin") output = "https://github.com/rahmanef63/mso.git";else if (key === "rev-parse --short HEAD") output = "16860d9";else if (key === "rev-parse --short origin/main") output = "7cffd11";+ else if (key === "rev-parse --short v0.2.0") code = 1;+ else if (key === "rev-parse --verify origin/main^{commit}") output = fixture.targetSha;+ else if (key === "tag --merged origin/main --list v*") output = fixture.tags;else if (args[0] === "fetch") code = fixture.fetchFails ? 1 : 0;else if (args[0] === "rev-list") output = `0\t${fixture.behind}`;+ else if (args[0] === "diff") output = "app/page.tsx";else if (key === "log -1 --format=%s") output = "installed build";else if (args[0] === "log" && fixture.behind) output = "7cffd11\x1flatest update\x1f2026-09-12";done(code ? { code } : null, output, "");@@ -23,31 +28,52 @@ vi.mock("node:child_process", () => ({}));const { getUpdateStatus, blockingReason } = await import("./self-update");-beforeEach(() => { fixture.branch = "main"; fixture.fetchFails = false; fixture.noGit = false; fixture.behind = 13; });+beforeEach(() => {+ fixture.branch = "main"; fixture.fetchFails = false; fixture.noGit = false;+ fixture.behind = 13; fixture.tags = ""; fixture.targetSha = "7cffd11";+});describe("version discovery independent of restart mechanism", () => {it("offers the same update on a systemd-less host when detached handoff is available", async () => {- const result = await getUpdateStatus(true);+ const result = await getUpdateStatus(true, "main");expect(result).toMatchObject({ current: "16860d9", latest: "7cffd11", behind: 13, remoteChecked: true, supported: true, reason: null });expect(result.commits).toHaveLength(1);expect(blockingReason(result, false)).toBeNull();});it("still reports available versions on detached HEAD but refuses mutation", async () => {fixture.branch = "";- const result = await getUpdateStatus(true);+ const result = await getUpdateStatus(true, "main");expect(result).toMatchObject({ behind: 13, remoteChecked: true, supported: false });expect(result.reason).toContain("detached HEAD");});it("does not claim a failed fetch was verified", async () => {fixture.fetchFails = true;fixture.behind = 0;- expect(await getUpdateStatus(true)).toMatchObject({ behind: 0, remoteChecked: false, supported: true });+ expect(await getUpdateStatus(true, "main")).toMatchObject({ behind: 0, remoteChecked: false, supported: true });});it("does not claim a cached-only poll checked the remote", async () => {- expect(await getUpdateStatus(false)).toMatchObject({ behind: 13, remoteChecked: false });+ expect(await getUpdateStatus(false, "main")).toMatchObject({ behind: 13, remoteChecked: false });});it("keeps an archive deployment explicitly unknown", async () => {fixture.noGit = true;- expect(await getUpdateStatus(true)).toMatchObject({ current: "unknown", remoteChecked: false, supported: false });+ expect(await getUpdateStatus(true, "main")).toMatchObject({ current: "unknown", remoteChecked: false, supported: false });+ });+});++describe("stable channel", () => {+ it("compares against the newest release tag, not origin/main", async () => {+ fixture.tags = "v0.2.0\nv0.9.0";+ const result = await getUpdateStatus(true, "stable");+ expect(result).toMatchObject({ channel: "stable", target: "v0.9.0", targetFallback: false });+ // The fixture reports 13 commits for any rev-list target; what matters is that+ // the tag was chosen and reported so the operator can see the comparison.+ expect(result.behind).toBe(13);+ });++ it("says out loud that stable is following main when no tag exists", async () => {+ fixture.tags = "";+ const result = await getUpdateStatus(true, "stable");+ expect(result).toMatchObject({ channel: "stable", targetFallback: true });+ expect(result.target).toContain("no release tag exists yet");});});diff --git a/lib/host/self-update-timer.test.ts b/lib/host/self-update-timer.test.tsnew file mode 100644index 00000000..ecb81a55--- /dev/null+++ b/lib/host/self-update-timer.test.ts@@ -0,0 +1,99 @@+import { describe, expect, it } from "vitest";+import { installTimer, readTimerState, removeTimer, unitFiles, unitPaths, type TimerMutation } from "./self-update-timer";+import type { Ran, Runner } from "./update-host-support";++function io(over: Partial<TimerMutation> & { calls?: string[][] } = {}): TimerMutation {+ const calls = over.calls ?? [];+ const run: Runner = async (command, args) => {+ calls.push([command, ...args]);+ return { code: 0, stdout: "", stderr: "" } as Ran;+ };+ return {+ run: over.run ?? run,+ writeFile: over.writeFile ?? (async () => undefined),+ removeFile: over.removeFile ?? (async () => undefined),+ mkdir: over.mkdir ?? (async () => undefined),+ };+}++describe("nightly update timer units", () => {+ it("schedules a jittered, persistent nightly run of the fixed entry point", () => {+ const files = unitFiles("/srv/mso", "/home/alice/.mso/self-update.log");+ expect(files.timer).toContain("OnCalendar=*-*-* 04:30:00");+ expect(files.timer).toContain("RandomizedDelaySec=25m");+ expect(files.timer).toContain("Persistent=true");+ expect(files.timer).toContain("Unit=mso-auto-update.service");+ expect(files.service).toContain("Type=oneshot");+ expect(files.service).toContain('WorkingDirectory="/srv/mso"');+ expect(files.service).toContain('/srv/mso/scripts/mso-auto-update');+ // No unit argument: the channel comes from prefs at run time, not from a file a+ // client could have influenced.+ expect(files.service).not.toContain("--channel");+ });++ it("quotes a checkout path with spaces instead of splitting it into two argv", () => {+ const files = unitFiles("/srv/my mso", "/tmp/a b.log");+ expect(files.service).toContain('WorkingDirectory="/srv/my mso"');+ expect(files.service).toContain('MSO_UPDATE_LOG="/tmp/a b.log"');+ });++ it("never reports the timer as installed when the manager does not know it", async () => {+ const unknown = await readTimerState(async () => ({ code: 1, stdout: "", stderr: "not found" }));+ expect(unknown).toEqual({ installed: false, enabled: false, active: false, nextRun: null });+ // systemd answers `n/a` for a loaded-but-unscheduled timer: that is not a date.+ const loaded = await readTimerState(async (_command, args) => {+ if (args.includes("LoadState")) return { code: 0, stdout: "loaded\n", stderr: "" };+ if (args.includes("is-enabled")) return { code: 0, stdout: "enabled\n", stderr: "" };+ if (args.includes("is-active")) return { code: 0, stdout: "active\n", stderr: "" };+ return { code: 0, stdout: "n/a\n", stderr: "" };+ });+ expect(loaded).toMatchObject({ installed: true, enabled: true, active: true, nextRun: null });+ });++ it("enables the timer after writing both units, and surfaces a refusal", async () => {+ const calls: string[][] = [];+ const written: string[] = [];+ const result = await installTimer("/srv/mso", "/tmp/log", io({+ calls,+ writeFile: async (file) => { written.push(file); },+ }));+ expect(result).toEqual({ ok: true });+ expect(written.map((f) => f.split("/").pop())).toEqual(["mso-auto-update.service", "mso-auto-update.timer"]);+ expect(calls.map((c) => c.join(" "))).toContain("systemctl --user daemon-reload");+ expect(calls.map((c) => c.join(" ")).some((c) => c.includes("enable --now mso-auto-update.timer"))).toBe(true);+ });++ it("reports a failed enable instead of pretending the pref is enough", async () => {+ const result = await installTimer("/srv/mso", "/tmp/log", io({+ run: async (_command, args) =>+ args.includes("enable") ? { code: 1, stdout: "", stderr: "permission denied" } : { code: 0, stdout: "", stderr: "" },+ }));+ expect(result).toEqual({ ok: false, error: "could not enable the update timer: permission denied" });+ });++ it("disables and deletes both units, tolerating units that were never installed", async () => {+ const calls: string[][] = [];+ const removed: string[] = [];+ expect(await removeTimer(io({+ calls,+ removeFile: async (file) => { removed.push(file.split("/").pop() ?? file); },+ }))).toEqual({ ok: true });+ expect(removed).toEqual(["mso-auto-update.timer", "mso-auto-update.service"]);+ const flat = calls.map((c) => c.join(" "));+ expect(flat.some((c) => c.includes("disable --now mso-auto-update.timer"))).toBe(true);+ });++ it("places units beside the user's other MSO units", () => {+ const previous = process.env.MSO_SYSTEMD_USER_DIR;+ process.env.MSO_SYSTEMD_USER_DIR = "/tmp/units";+ try {+ expect(unitPaths()).toEqual({+ service: "/tmp/units/mso-auto-update.service",+ timer: "/tmp/units/mso-auto-update.timer",+ });+ } finally {+ if (previous === undefined) delete process.env.MSO_SYSTEMD_USER_DIR;+ else process.env.MSO_SYSTEMD_USER_DIR = previous;+ }+ });+});diff --git a/lib/host/self-update-timer.ts b/lib/host/self-update-timer.tsnew file mode 100644index 00000000..6bcf9c36--- /dev/null+++ b/lib/host/self-update-timer.ts@@ -0,0 +1,156 @@+// The nightly timer's unit files and their REAL state.+//+// Where the units ship: written at runtime by this module, not by the installer.+// The installer already enables linger and hands mso.service a user bus, so the web+// app can do this without sudo; install-core.sh is also at its line ratchet. The+// consequence is that the UI must read the manager's state rather than the pref —+// a pref saying "auto" with no unit file is not an enabled host.+import { promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+import { AUTO_UPDATE_UNIT, type Ran, type Runner, execRunner } from "./update-host-support";++export interface TimerState {+ installed: boolean;+ enabled: boolean;+ active: boolean;+ /** ISO date of the next elapse, or null when the timer is not scheduled. */+ nextRun: string | null;+}++const DISABLED: TimerState = { installed: false, enabled: false, active: false, nextRun: null };++/** `$XDG_CONFIG_HOME/systemd/user`, else `~/.config/systemd/user`. */+export function unitDir(): string {+ const base = process.env.XDG_CONFIG_HOME?.trim() || path.join(os.homedir(), ".config");+ return process.env.MSO_SYSTEMD_USER_DIR?.trim() || path.join(base, "systemd", "user");+}++export const unitPaths = (): { service: string; timer: string } => {+ const dir = unitDir();+ return { service: path.join(dir, `${AUTO_UPDATE_UNIT}.service`), timer: path.join(dir, `${AUTO_UPDATE_UNIT}.timer`) };+};++/** systemd exec arguments are space-split with quote support; a checkout path with+ * a space must survive as ONE argument, so quote and escape rather than join raw. */+const exec = (value: string): string => `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;++/** Pure: unit text for a given checkout. No request value reaches this string. */+export function unitFiles(root: string, logPath: string): { service: string; timer: string } {+ const service = `[Unit]+Description=MSO unattended self-update (the pre-flight decides whether anything changes)++[Service]+Type=oneshot+WorkingDirectory=${exec(root)}+Environment=MSO_UPDATE_LOG=${exec(logPath)}+# A build on a small VPS is minutes. The transient update unit already has its own+# 1h start timeout; this is the outer bound for pre-flight + that wait.+TimeoutStartSec=5400+ExecStart=/bin/bash ${exec(path.join(root, "scripts", "mso-auto-update"))}+`;+ const timer = `[Unit]+Description=MSO nightly unattended self-update++[Timer]+# Nightly, jittered, and caught up after downtime. Never a fixed minute on every+# host: every MSO deployment would otherwise fetch the same commit together.+OnCalendar=*-*-* 04:30:00+RandomizedDelaySec=25m+Persistent=true+Unit=${AUTO_UPDATE_UNIT}.service++[Install]+WantedBy=timers.target+`;+ return { service, timer };+}++/** True only when the manager actually knows the timer unit. */+export async function readTimerState(run: Runner = execRunner): Promise<TimerState> {+ const [installed, enabled, active] = await Promise.all([+ run("systemctl", ["--user", "show", "-p", "LoadState", "--value", `${AUTO_UPDATE_UNIT}.timer`], 10_000),+ run("systemctl", ["--user", "is-enabled", `${AUTO_UPDATE_UNIT}.timer`], 10_000),+ run("systemctl", ["--user", "is-active", `${AUTO_UPDATE_UNIT}.timer`], 10_000),+ ]);+ if (installed.code !== 0 || installed.stdout.trim() !== "loaded") return { ...DISABLED };+ const next = await run("systemctl", ["--user", "show", "-p", "NextElapseUSecRealtime", "--value", `${AUTO_UPDATE_UNIT}.timer`], 10_000);+ const raw = next.code === 0 ? next.stdout.trim() : "";+ // systemd prints `n/a` for a timer that is loaded but not scheduled.+ return {+ installed: true,+ enabled: enabled.code === 0 && enabled.stdout.trim() === "enabled",+ active: active.code === 0 && active.stdout.trim() === "active",+ nextRun: raw && raw !== "n/a" ? raw : null,+ };+}++export interface TimerMutation {+ run: Runner;+ /** Injected so tests exercise the decision without touching a real manager. */+ writeFile: (file: string, content: string) => Promise<void>;+ removeFile: (file: string) => Promise<void>;+ mkdir: (dir: string) => Promise<void>;+}++/** Production IO: real user-manager calls and 0600 unit files. */+export const realTimerIo = (): TimerMutation => ({+ run: execRunner,+ mkdir: async (dir) => {+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });+ },+ writeFile: async (file, content) => {+ const tmp = `${file}.tmp`;+ await fs.writeFile(tmp, content, { encoding: "utf8", mode: 0o600 });+ await fs.rename(tmp, file);+ },+ removeFile: async (file) => {+ await fs.rm(file, { force: true });+ },+});++const reload = async (run: Runner): Promise<Ran> => run("systemctl", ["--user", "daemon-reload"], 20_000);++/** Write both units, then enable the timer. Throws nothing: the caller decides. */+export async function installTimer(+ root: string,+ logPath: string,+ io: TimerMutation,+): Promise<{ ok: true } | { ok: false; error: string }> {+ const files = unitFiles(root, logPath);+ const paths = unitPaths();+ try {+ await io.mkdir(unitDir());+ await io.writeFile(paths.service, files.service);+ await io.writeFile(paths.timer, files.timer);+ } catch (cause) {+ return { ok: false, error: `could not write the update timer units: ${String(cause).slice(0, 200)}` };+ }+ const reloaded = await reload(io.run);+ if (reloaded.code !== 0) {+ return { ok: false, error: `systemd --user daemon-reload failed: ${(reloaded.stderr || reloaded.stdout).trim().slice(0, 200)}` };+ }+ const enabled = await io.run("systemctl", ["--user", "enable", "--now", `${AUTO_UPDATE_UNIT}.timer`], 30_000);+ if (enabled.code !== 0) {+ return { ok: false, error: `could not enable the update timer: ${(enabled.stderr || enabled.stdout).trim().slice(0, 200)}` };+ }+ return { ok: true };+}++/** Disable and delete. Missing units are already "off", not an error. */+export async function removeTimer(io: TimerMutation): Promise<{ ok: true } | { ok: false; error: string }> {+ await io.run("systemctl", ["--user", "disable", "--now", `${AUTO_UPDATE_UNIT}.timer`], 30_000);+ // Stopping the oneshot is best-effort: a run already past its pre-flight owns the+ // update lock and will finish the build it started.+ await io.run("systemctl", ["--user", "stop", `${AUTO_UPDATE_UNIT}.service`], 30_000);+ const paths = unitPaths();+ await io.removeFile(paths.timer).catch(() => undefined);+ await io.removeFile(paths.service).catch(() => undefined);+ const reloaded = await reload(io.run);+ if (reloaded.code !== 0) {+ return { ok: false, error: `systemd --user daemon-reload failed: ${(reloaded.stderr || reloaded.stdout).trim().slice(0, 200)}` };+ }+ return { ok: true };+}++export { AUTO_UPDATE_UNIT };diff --git a/lib/host/self-update.test.ts b/lib/host/self-update.test.tsindex e294af3d..acf3cd87 100644--- a/lib/host/self-update.test.ts+++ b/lib/host/self-update.test.ts@@ -79,6 +79,27 @@ describe("updateUnitArgs", () => {const args = updateUnitArgs("/srv/mso", "/tmp/update.log", true);expect(args.at(-1)).toBe("--rebuild-only");});++ it("passes the channel as one of exactly two fixed flags — never a ref", () => {+ expect(updateUnitArgs("/srv/mso", "/tmp/log", false, "stable")).toContain("--channel=stable");+ expect(updateUnitArgs("/srv/mso", "/tmp/log", false, "main")).toContain("--channel=main");+ // Both knobs, together: the channel flag and the rebuild boolean, nothing else.+ expect(updateUnitArgs("/srv/mso", "/tmp/log", true, "main").slice(-2)).toEqual(["--channel=main", "--rebuild-only"]);+ });++ it("cannot be turned into a command injection by any request-shaped string", () => {+ // The channel parameter is a TypeScript union, but a hand-rolled HTTP body is not+ // typed: whatever reaches this function must still yield the safe default.+ const hostile = ["origin/main", "refs/heads/main; rm -rf /", "$(id)", "--unit=evil", "\n--property=User=root"] as unknown as "main"[];+ for (const channel of hostile) {+ const argv = updateUnitArgs("/srv/mso", "/tmp/log", false, channel).join(" ");+ expect(argv).toContain("--channel=stable");+ expect(argv).not.toContain("rm -rf");+ expect(argv).not.toContain("$(id)");+ expect(argv).not.toContain("--unit=evil");+ expect(argv).not.toContain("User=root");+ }+ });});describe("offlineUpdateArgs", () => {diff --git a/lib/host/self-update.ts b/lib/host/self-update.tsindex 76624fd5..a12cd548 100644--- a/lib/host/self-update.ts+++ b/lib/host/self-update.ts@@ -1,90 +1,69 @@// Host-owned runtime data is not a build asset; tracing exclusions preserve runtime guards.import "server-only";-import { execFile } from "node:child_process";import { promises as fs } from "node:fs";-import os from "node:os";import path from "node:path";import { HostError } from "./host-error";import { offlineUpdateArgs, offlineUpdateRunning } from "./self-update-offline";import { prepareUpdateOrigin, updateGitEnv } from "./update-remote-authority";+import { blockingReason, parseCommits, updateBranchReason, type UpdateStatus } from "./update-decision";+import { fetchArgs } from "./self-update-channel";+import type { UpdateChannel } from "@/lib/prefs/updates";+import { collectUpdateFacts } from "./update-facts";+import { readPrefs } from "@/lib/prefs/store";+import { resolveUpdates } from "@/lib/prefs/updates";+import {+ AUTO_UPDATE_UNIT,+ SELF_UPDATE_UNIT,+ automaticUpdateReason,+ execRunner,+ isUpdateRunning,+ readUpdateLog,+ updateLogPath,+ type Ran,+} from "./update-host-support";// SERVER-ONLY. "Is there a newer MSO, and pull it in" — the deploy that CLAUDE.md// describes (`git pull` → build → restart), driven from Settings instead of from a// terminal the owner may not have open.//-// Prod is systemd with NO webhook, so a commit on main changes nothing anyone can-// see until someone rebuilds. That someone was always a person with ssh. This makes-// it a button.-//// THE UPDATE DOES NOT RUN IN THIS PROCESS, and that is not a style choice: the last// step replaces the process serving MSO, and systemd's default KillMode kills every-// child in mso.service's cgroup. A detached child is still in that cgroup, so it-// would die mid-`next build`, with `.next` already deleted and nothing to restart-// into. The job is therefore handed to the OWNER'S transient user unit via-// `systemd-run --user`. That gives it a separate cgroup without granting the web app-// passwordless root. At the end the updater signals mso.service's same-UID MainPID;-// Restart=always brings the system unit back on the freshly-built checkout.-const UNIT = "mso-self-update";-const LOG_TAIL = 12_000;-const GIT_TIMEOUT_MS = 20_000;-const FETCH_TIMEOUT_MS = 45_000;-/** Enough to see what is coming without turning the panel into a git log. */-const MAX_COMMITS = 25;--export interface UpdateCommit {- sha: string;- subject: string;- date: string;-}+// child in mso.service's cgroup. The job is therefore handed to the OWNER'S+// transient user unit via `systemd-run --user`. That gives it a separate cgroup+// without granting the web app passwordless root. At the end the updater signals+// mso.service's same-UID MainPID; Restart=always brings the system unit back on the+// freshly-built checkout.+//+// The DECISIONS live in ./update-decision and the ref resolution in+// ./self-update-channel, both free of Next-only imports, because the nightly timer+// (scripts/self-update-auto.ts) must refuse on exactly the same facts.-export interface UpdateStatus {- /** False when this deployment cannot self-update (for example, not a checkout or no safe handoff runtime). */- supported: boolean;- /** Why not, when `supported` is false — shown to the operator verbatim. */- reason: string | null;- /** HEAD of the CHECKOUT — what a rebuild would compile. */- current: string;- currentSubject: string;- /** Latest fetched origin/main commit, independent of restart support. */- latest?: string;- /** The commit the RUNNING build was compiled from (baked in by next.config), or- * "" when the build carried no .git. Differs from `current` whenever someone- * pulled without rebuilding — the state the panel calls "a build is pending". */- buildSha: string;- pendingBuild: boolean;- ahead: number;- behind: number;- commits: UpdateCommit[];- /** Uncommitted work in the checkout: a `--ff-only` merge would fail, so refuse early. */- dirty: boolean;- running: boolean;- /** False when `git fetch` could not reach the remote — `behind` is then only local knowledge. */- remoteChecked: boolean;- log: string;-}+export type { UpdateCommit, UpdateStatus } from "./update-decision";+export { blockingReason, parseCommits, updateBranchReason };+export { AUTO_UPDATE_UNIT, SELF_UPDATE_UNIT };+export type { UpdateChannel };-export const updateLogPath = (): string => {- const override = process.env.MSO_UPDATE_LOG?.trim();- return override || path.join(os.homedir(), ".mso", "self-update.log");-};+const GIT_TIMEOUT_MS = 20_000;+const FETCH_TIMEOUT_MS = 45_000;const repoRoot = (): string => process.cwd();-export function updateBranchReason(branch: string): string | null {- const current = branch.trim();- return current === "main"- ? null- : `software updates require the checkout to be on main (current: ${current || "detached HEAD"})`;-}--/** Arguments are pure/testable because this boundary is security-sensitive: the- * request may choose only update vs rebuild. No path, command, ref, or root-capable- * argument comes from the client. */-export function updateUnitArgs(root: string, logPath: string, rebuildOnly = false): string[] {+/**+ * Arguments are pure/testable because this boundary is security-sensitive: a+ * request may choose only rebuild vs update, and the CHANNEL is the stored enum —+ * never a ref, path, tag or command. `--channel=` carries the two-word value; the+ * updater re-validates it and resolves the actual Git ref itself.+ */+export function updateUnitArgs(+ root: string,+ logPath: string,+ rebuildOnly = false,+ channel: UpdateChannel = "stable",+): string[] {return ["--user","--collect",- `--unit=${UNIT}`,+ `--unit=${SELF_UPDATE_UNIT}`,`--property=WorkingDirectory=${root}`,// A build on a small VPS is minutes, not seconds; the default 90s start// timeout would kill it exactly at the point of no return.@@ -92,224 +71,100 @@ export function updateUnitArgs(root: string, logPath: string, rebuildOnly = fals`--setenv=MSO_UPDATE_LOG=${logPath}`,"/bin/bash",path.join(root, "scripts", "mso-service-update"),+ `--channel=${channel === "main" ? "main" : "stable"}`,...(rebuildOnly ? ["--rebuild-only"] : []),];}-interface Ran {- code: number;- stdout: string;- stderr: string;-}--function run(command: string, args: readonly string[], timeout = GIT_TIMEOUT_MS, env?: NodeJS.ProcessEnv): Promise<Ran> {- return new Promise((resolve) => {- execFile(- command,- [...args],- { cwd: repoRoot(), timeout, maxBuffer: 1024 * 1024, windowsHide: true, shell: false, ...(env ? { env } : {}) },- (error, stdout, stderr) => {- const code = typeof (error as { code?: number } | null)?.code === "number" ? (error as { code: number }).code : error ? 1 : 0;- resolve({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });- },- );- });-}--const git = (args: readonly string[], timeout?: number) => run("git", args, timeout, updateGitEnv());--/** `<sha>\x1f<subject>\x1f<iso date>` per line — a separator no subject can contain. */-export function parseCommits(stdout: string): UpdateCommit[] {- return stdout- .split("\n")- .map((line) => line.trim())- .filter(Boolean)- .slice(0, MAX_COMMITS)- .map((line) => {- const [sha = "", subject = "", date = ""] = line.split("\x1f");- return { sha, subject: subject.slice(0, 200), date: date.slice(0, 10) };- })- .filter((c) => c.sha);-}--/**- * Why this update must not start, or `null` when it may.- *- * Pure, and separate from the doing, because every one of these is a refusal an- * operator has to be able to read — "nothing happened and here is why" beats a- * build that fails halfway through with the live `.next` already deleted.- */-export function blockingReason(status: UpdateStatus, rebuildOnly: boolean): string | null {- if (!status.supported) return status.reason ?? "this deployment cannot update itself";- if (status.running) return "an update is already running";- if (status.dirty) {- return "the checkout has uncommitted changes — commit or stash them on the host first, a fast-forward would refuse anyway";- }- if (!rebuildOnly && status.ahead > 0) {- return status.behind > 0- ? `local main has diverged from origin/main (ahead ${status.ahead}, behind ${status.behind}); reconcile it before updating`- : `local main is ahead of origin/main by ${status.ahead} commit(s); push or reconcile it before updating`;- }- // `pendingBuild` is a reason to run even with nothing to pull: the checkout- // already holds code the running process was not built from, and refusing with- // "already up to date" would be describing the wrong thing as up to date.- if (!rebuildOnly && status.behind === 0 && !status.pendingBuild) return "already up to date";- return null;-}--async function isRunning(): Promise<boolean> {- // `is-active` on a transient unit that has been collected exits non-zero, which- // is the same answer as "never ran" — both mean "not running", so the code is- // all we need here. Check the old system-unit location too while installations- // migrate from the pre-0.2.1 sudo-based updater.- const [userUnit, legacySystemUnit] = await Promise.all([- run("systemctl", ["--user", "is-active", `${UNIT}.service`], 10_000),- run("systemctl", ["is-active", `${UNIT}.service`], 10_000),- ]);- if (userUnit.code === 0 || legacySystemUnit.code === 0) return true;- return offlineUpdateRunning();-}--async function readLog(): Promise<string> {- const raw = await fs.readFile(/* turbopackIgnore: true */ updateLogPath(), "utf8").catch(() => "");- return raw.length > LOG_TAIL ? raw.slice(-LOG_TAIL) : raw;-}--/** Restart authority must never suppress read-only version discovery. */-async function automaticUpdateReason(): Promise<string | null> {- const branch = await git(["branch", "--show-current"]);- const branchReason = updateBranchReason(branch.stdout);- if (branch.code !== 0 || branchReason) {- return branch.code === 0 ? branchReason : "could not determine the checkout branch";- }-- // The installer enables linger and gives mso.service XDG_RUNTIME_DIR precisely- // so the service can reach this per-user manager. Unlike the old sudo path, this- // is both non-interactive and non-root.- const userManager = await run("systemctl", ["--user", "show-environment"], 10_000);- if (userManager.code !== 0) {- // A container/hosted runtime can legitimately have no systemd at all (PID 1- // may be tini). The CLI already has a safe offline update path that quiesces- // only MSO-owned runtimes under the checkout exclusion lock. `setsid -f` is- // the missing handoff boundary: it lets that path survive the Next process it- // intentionally stops and replaces. No sudo and no arbitrary client argv.- const setsid = process.platform === "linux" ? await run("setsid", ["--version"], 5_000) : { code: 1 };- if (setsid.code === 0) return null;- return "Automatic restart is unavailable on this host. Run mso update from a terminal; version checks still work.";- }-- const [loadState, serviceUser, restartPolicy] = await Promise.all([- run("systemctl", ["show", "-p", "LoadState", "--value", "mso.service"], 10_000),- run("systemctl", ["show", "-p", "User", "--value", "mso.service"], 10_000),- run("systemctl", ["show", "-p", "Restart", "--value", "mso.service"], 10_000),- ]);- if (loadState.code !== 0 || loadState.stdout.trim() !== "loaded") {- return "mso.service is not installed; run mso update from a terminal for this host.";- }- if (restartPolicy.code !== 0 || restartPolicy.stdout.trim() === "no") {- return "mso.service has no automatic restart policy; refusing to stop the running process during self-update";- }- const owner = os.userInfo().username;- if (serviceUser.code !== 0 || serviceUser.stdout.trim() !== owner) {- return `mso.service runs as ${serviceUser.stdout.trim() || "an unknown user"}, not ${owner}; refusing a cross-user update`;- }-- return null;-}+/** `git` with the non-interactive remote policy. The authority module is plain+ * data (no Next import), so both the panel and the timer use the same env. */+const git = (args: readonly string[], timeout = GIT_TIMEOUT_MS) =>+ execRunner("git", args, timeout, updateGitEnv());/*** @param fetchRemote when true, ask the remote first. A check costs a network* round trip, so the panel asks for one and the poller during an update does not.+ * @param channel override; defaults to the owner's stored pref.*/-export async function getUpdateStatus(fetchRemote = true): Promise<UpdateStatus> {+export async function getUpdateStatus(fetchRemote = true, channel?: UpdateChannel): Promise<UpdateStatus> {const buildSha = (process.env.NEXT_PUBLIC_COMMIT_SHA ?? "").trim();// Read ONCE: the panel polls this every 3s while a build runs, and the log is// the biggest thing in the response.- const log = await readLog();+ const log = await readUpdateLog();+ const effective = channel ?? resolveUpdates((await readPrefs()).updates).channel;const base: UpdateStatus = {supported: false, reason: null, current: "unknown", currentSubject: "", buildSha,pendingBuild: false, ahead: 0, behind: 0, commits: [], dirty: false,- running: false, remoteChecked: false, log,+ running: false, remoteChecked: false, log, channel: effective,+ target: "origin/main", targetFallback: false,};- const inside = await git(["rev-parse", "--is-inside-work-tree"]);- if (inside.code !== 0 || inside.stdout.trim() !== "true") {- return { ...base, reason: "this deployment is not a git checkout, so there is nothing to pull" };- }-- const running = await isRunning();- const [head, subject, status] = await Promise.all([- git(["rev-parse", "--short", "HEAD"]),- git(["log", "-1", "--format=%s"]),- git(["status", "--porcelain"]),- ]);-- let remoteChecked = false;- if (fetchRemote && !running) {- // Quiet + a hard timeout: an unreachable remote must degrade to "could not- // check", never hang the Settings panel that is waiting on this.- const originReady = await prepareUpdateOrigin(git);- const fetched = originReady- ? await git(["fetch", "--quiet", "origin", "main"], FETCH_TIMEOUT_MS)- : { code: 1, stdout: "", stderr: "origin unavailable" };- remoteChecked = fetched.code === 0;+ // `git` needs the remote credentials policy for fetch only; reads are local.+ const running = await isUpdateRunning(execRunner, offlineUpdateRunning);+ const facts = await collectUpdateFacts({+ git: (args) => git(args),+ channel: effective,+ fetch: fetchRemote && !running,+ fetchRemote: async () => {+ const ready = await prepareUpdateOrigin((args) => git(args, FETCH_TIMEOUT_MS));+ if (!ready) return { code: 1 };+ return git(fetchArgs(effective), FETCH_TIMEOUT_MS);+ },+ });+ if (!facts.insideWorkTree) {+ return { ...base, reason: "this deployment is not a git checkout, so there is nothing to pull", running };}- const [relationCount, commitLog, latest] = await Promise.all([- git(["rev-list", "--left-right", "--count", "HEAD...origin/main"]),- git(["log", "--format=%h%x1f%s%x1f%cs", `-${MAX_COMMITS}`, "HEAD..origin/main"]),- git(["rev-parse", "--short", "origin/main"]),- ]);- const [aheadRaw = "0", behindRaw = "0"] = relationCount.stdout.trim().split(/\s+/);- const ahead = relationCount.code === 0 ? Number(aheadRaw) || 0 : 0;- const behind = relationCount.code === 0 ? Number(behindRaw) || 0 : 0;-- const current = head.stdout.trim() || "unknown";- const reason = await automaticUpdateReason();+ const reason = await automaticUpdateReason(execRunner);return {...base,supported: reason === null,reason,- current,- latest: latest.code === 0 ? latest.stdout.trim() : "",- currentSubject: subject.stdout.trim(),+ current: facts.head,+ latest: facts.latest,+ currentSubject: facts.subject,// Only when we know both: a build with no sha baked in (an archive export, a// dev server) must not be reported as permanently stale.- pendingBuild: Boolean(buildSha) && current !== "unknown" && !buildSha.startsWith(current) && !current.startsWith(buildSha),- ahead,- behind,- commits: commitLog.code === 0 ? parseCommits(commitLog.stdout) : [],- dirty: status.stdout.trim().length > 0,+ pendingBuild: Boolean(buildSha) && facts.head !== "unknown" && !buildSha.startsWith(facts.head) && !facts.head.startsWith(buildSha),+ ahead: facts.ahead,+ behind: facts.behind,+ commits: facts.commits,+ dirty: facts.dirty,running,- remoteChecked: remoteChecked && relationCount.code === 0 && latest.code === 0,+ remoteChecked: facts.remoteChecked,log,+ channel: effective,+ target: facts.targetLabel,+ targetFallback: facts.targetFallback,};}/*** Hand the update to a transient systemd unit and return immediately.*- * Nothing from the request reaches a shell: the only knob is a boolean, and the- * ref is hard-coded to `origin/main`.+ * Nothing from the request reaches a shell: the only knobs are a boolean and the+ * stored channel enum, and the ref is resolved server-side.*/-export async function startUpdate(rebuildOnly = false): Promise<UpdateStatus> {- const status = await getUpdateStatus(true);+export async function startUpdate(rebuildOnly = false, channel?: UpdateChannel): Promise<UpdateStatus> {+ const effective = channel ?? resolveUpdates((await readPrefs()).updates).channel;+ const status = await getUpdateStatus(true, effective);const blocked = blockingReason(status, rebuildOnly);if (blocked) throw new HostError(blocked);- const userManager = await run("systemctl", ["--user", "show-environment"], 10_000);+ const userManager = await execRunner("systemctl", ["--user", "show-environment"], 10_000);let started: Ran;if (userManager.code === 0) {const script = path.join(repoRoot(), "scripts", "mso-service-update");if (!(await fs.stat(script).catch(() => null))) throw new HostError(`missing ${script}`);- started = await run("systemd-run", updateUnitArgs(repoRoot(), updateLogPath(), rebuildOnly), 30_000);+ started = await execRunner("systemd-run", updateUnitArgs(repoRoot(), updateLogPath(), rebuildOnly, effective), 30_000);} else {const script = path.join(repoRoot(), "scripts", "mso-offline-update-job");if (!(await fs.stat(script).catch(() => null))) throw new HostError(`missing ${script}`);// The wrapper writes its PID before doing any mutation and redirects stdout/// stderr to the same log the panel already polls. setsid receives only a- // compile-time script path and the one allowed boolean flag.- started = await run("setsid", offlineUpdateArgs(repoRoot(), rebuildOnly), 30_000);+ // compile-time script path and the one allowed boolean flag; the wrapper reads+ // the channel from the same preference file this function just read.+ started = await execRunner("setsid", offlineUpdateArgs(repoRoot(), rebuildOnly), 30_000);}if (started.code !== 0) {throw new HostError(diff --git a/lib/host/update-automation.test.ts b/lib/host/update-automation.test.tsnew file mode 100644index 00000000..40c8abaa--- /dev/null+++ b/lib/host/update-automation.test.ts@@ -0,0 +1,97 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++// The acceptance rule this file exists for: enabling writes the pref AND installs the+// timer; disabling removes the timer BEFORE the pref says "off"; a host that cannot+// host a timer is refused instead of storing an intent nobody will execute.+const mocks = vi.hoisted(() => ({+ stored: {} as Record<string, unknown>,+ reason: null as string | null,+ written: [] as unknown[],+ install: vi.fn(),+ remove: vi.fn(),+ timer: { installed: true, enabled: true, active: true, nextRun: null as string | null },+}));+vi.mock("../prefs/store", () => ({+ readPrefs: async () => ({ updates: mocks.stored }),+ writePrefs: async (patch: unknown) => { mocks.written.push(patch); return {}; },+}));+vi.mock("../prefs/auto-update-state", () => ({+ readAutoUpdateState: async () => ({ lastAttemptAt: null, lastResult: null, consecutiveFailures: 0, detail: null, channel: null }),+}));+vi.mock("./update-host-support", () => ({+ automaticUpdateReason: async () => mocks.reason,+ execRunner: async () => ({ code: 0, stdout: "", stderr: "" }),+ updateLogPath: () => "/tmp/self-update.log",+}));+vi.mock("./self-update-timer", () => ({+ readTimerState: async () => mocks.timer,+ realTimerIo: () => ({}),+ installTimer: (...args: unknown[]) => mocks.install(...args),+ removeTimer: (...args: unknown[]) => mocks.remove(...args),+}));++const { applyAutomation, readAutomationState } = await import("./update-automation");+const ctx = { root: "/srv/mso" };++beforeEach(() => {+ mocks.stored = {};+ mocks.reason = null;+ mocks.written = [];+ mocks.timer = { installed: true, enabled: true, active: true, nextRun: null };+ mocks.install.mockReset().mockResolvedValue({ ok: true });+ mocks.remove.mockReset().mockResolvedValue({ ok: true });+});++describe("update automation authority", () => {+ it("installs the timer and stores the pref when the owner enables it", async () => {+ mocks.timer = { installed: false, enabled: false, active: false, nextRun: null };+ await applyAutomation({ auto: true }, ctx);+ expect(mocks.install).toHaveBeenCalledWith("/srv/mso", "/tmp/self-update.log", expect.anything());+ expect(mocks.written).toEqual([{ updates: { auto: true, channel: "main" } }]);+ });++ it("removes the timer when the owner disables it", async () => {+ mocks.stored = { auto: true, channel: "main" };+ await applyAutomation({ auto: false }, ctx);+ expect(mocks.remove).toHaveBeenCalledOnce();+ expect(mocks.install).not.toHaveBeenCalled();+ expect(mocks.written).toEqual([{ updates: { auto: false, channel: "main" } }]);+ });++ it("refuses to store auto:true on a host with no safe restart path", async () => {+ mocks.reason = "mso.service has no automatic restart policy; refusing to stop the running process during self-update";+ await expect(applyAutomation({ auto: true }, ctx)).rejects.toThrow(/no automatic restart policy/);+ expect(mocks.install).not.toHaveBeenCalled();+ expect(mocks.written).toEqual([]);+ });++ it("does not store auto:true when the timer could not be enabled", async () => {+ mocks.install.mockResolvedValue({ ok: false, error: "could not enable the update timer: permission denied" });+ await expect(applyAutomation({ auto: true }, ctx)).rejects.toThrow(/permission denied/);+ expect(mocks.written).toEqual([]);+ });++ it("changes only the channel without touching the timer", async () => {+ mocks.stored = { auto: false, channel: "stable" };+ await applyAutomation({ channel: "main" }, ctx);+ expect(mocks.install).not.toHaveBeenCalled();+ expect(mocks.remove).not.toHaveBeenCalled();+ expect(mocks.written).toEqual([{ updates: { auto: false, channel: "main" } }]);+ });++ it("reports 'active' only when the pref and the real unit agree, and names the drift", async () => {+ mocks.stored = { auto: true, channel: "stable" };+ mocks.timer = { installed: false, enabled: false, active: false, nextRun: null };+ const state = await readAutomationState();+ expect(state.active).toBe(false);+ expect(state.drift).toContain("timer is missing");++ mocks.timer = { installed: true, enabled: true, active: true, nextRun: null };+ expect((await readAutomationState()).active).toBe(true);++ mocks.stored = { auto: false, channel: "stable" };+ const leftover = await readAutomationState();+ expect(leftover.active).toBe(false);+ expect(leftover.drift).toContain("still scheduled");+ });+});diff --git a/lib/host/update-automation.ts b/lib/host/update-automation.tsnew file mode 100644index 00000000..cf17f6e9--- /dev/null+++ b/lib/host/update-automation.ts@@ -0,0 +1,74 @@+// The single place where "auto: true" becomes a real timer.+//+// No `server-only`, no Next-only import: the Settings route and the nightly entry+// point (scripts/self-update-auto.ts) both call this, so the browser and the CLI+// cannot install different units or disagree about what "enabled" means.+import { readAutoUpdateState, type AutoUpdateState } from "../prefs/auto-update-state";+import { readPrefs, writePrefs } from "../prefs/store";+import { resolveUpdates, type PrefUpdates, type UpdateChannel } from "../prefs/updates";+import { automaticUpdateReason, execRunner, updateLogPath } from "./update-host-support";+import { installTimer, readTimerState, realTimerIo, removeTimer, type TimerState } from "./self-update-timer";+import { HostError } from "./host-error";++export interface AutomationState {+ prefs: PrefUpdates;+ timer: TimerState;+ /** True only when the pref AND the installed, enabled timer agree. The UI shows+ * this — never `prefs.auto` alone, which would claim "on" for a deleted unit. */+ active: boolean;+ last: AutoUpdateState;+ /** Set when the two disagree, so the panel can say what is wrong. */+ drift: string | null;+}++export interface AutomationPatch {+ auto?: boolean;+ channel?: UpdateChannel;+}++/** `root` is the checkout the timer builds. Explicit so the CLI can pass the+ * service checkout even when it is invoked from somewhere else. */+export interface AutomationContext {+ root: string;+}++export async function readAutomationState(): Promise<AutomationState> {+ const prefs = resolveUpdates((await readPrefs()).updates);+ const [timer, last] = await Promise.all([readTimerState(), readAutoUpdateState()]);+ const active = prefs.auto && timer.installed && timer.enabled;+ const drift = prefs.auto && !active+ ? timer.installed+ ? "the nightly update timer is installed but not enabled — toggle it off and on to re-enable it"+ : "automatic updates are enabled in preferences but the timer is missing on this host — toggle it off and on to reinstall it"+ : !prefs.auto && timer.active+ ? "a nightly update timer is still scheduled although automatic updates are off — run mso update --auto off"+ : null;+ return { prefs, timer, active, last, drift };+}++/**+ * Apply an owner patch. Refuses the whole change when this host cannot host a+ * timer, rather than storing `auto: true` for a scheduler that will never exist.+ */+export async function applyAutomation(patch: AutomationPatch, ctx: AutomationContext): Promise<AutomationState> {+ const current = resolveUpdates((await readPrefs()).updates);+ const next: PrefUpdates = { ...current, ...patch };+ const io = realTimerIo();++ if (next.auto) {+ const reason = await automaticUpdateReason(execRunner);+ if (reason) throw new HostError(`automatic updates are unavailable: ${reason}`);+ const installed = await installTimer(ctx.root, updateLogPath(), io);+ if (!installed.ok) throw new HostError(installed.error);+ } else if (current.auto || patch.auto === false) {+ // Unconditional on an explicit `off`: this is also how an operator clears the+ // drift where a timer survived a pref that already says false.+ const removed = await removeTimer(io);+ if (!removed.ok) throw new HostError(removed.error);+ }+ // A channel change needs no timer action: the unit reads the channel from prefs+ // at run time, so the very next night already uses it.++ await writePrefs({ updates: next });+ return readAutomationState();+}diff --git a/lib/host/update-decision.test.ts b/lib/host/update-decision.test.tsnew file mode 100644index 00000000..1aa8c2c3--- /dev/null+++ b/lib/host/update-decision.test.ts@@ -0,0 +1,96 @@+import { describe, expect, it } from "vitest";+import { autoUpdateGate, parseCommits, touchesUpdater, type AutoGateFacts } from "./update-decision";++const facts = (over: Partial<AutoGateFacts> = {}): AutoGateFacts => ({+ auto: true,+ supported: true,+ reason: null,+ dirty: false,+ running: false,+ ahead: 0,+ behind: 3,+ pendingBuild: false,+ consecutiveFailures: 0,+ changedPaths: ["app/page.tsx"],+ target: "v0.2.0",+ targetFallback: false,+ ...over,+});++describe("parseCommits", () => {+ it("splits the unit-separated format git is asked for", () => {+ const out = ["9f3c9ee\x1ffix(deps): pin nanoid\x1f2026-08-17", "ecce676\x1fMerge pull request #3\x1f2026-08-16"].join("\n");+ expect(parseCommits(out)).toEqual([+ { sha: "9f3c9ee", subject: "fix(deps): pin nanoid", date: "2026-08-17" },+ { sha: "ecce676", subject: "Merge pull request #3", date: "2026-08-16" },+ ]);+ });++ it("returns nothing for the up-to-date case rather than an empty-shaped row", () => {+ expect(parseCommits("")).toEqual([]);+ expect(parseCommits("\n \n")).toEqual([]);+ });+});++describe("autoUpdateGate", () => {+ it("runs when every precondition holds", () => {+ expect(autoUpdateGate(facts())).toEqual({ run: true });+ });++ it("refuses when the owner never opted in, even if the timer fired", () => {+ // A timer that survived a `--auto off` must not keep updating the host.+ expect(autoUpdateGate(facts({ auto: false }))).toMatchObject({ run: false });+ });++ it("refuses an unsupported checkout, a dirty tree, a running update and local commits", () => {+ expect(autoUpdateGate(facts({ supported: false, reason: "checkout is on feat/x" }))).toEqual({+ run: false, reason: "checkout is on feat/x",+ });+ expect(autoUpdateGate(facts({ dirty: true })).run).toBe(false);+ expect(autoUpdateGate(facts({ running: true })).run).toBe(false);+ expect(autoUpdateGate(facts({ ahead: 2 })).run).toBe(false);+ expect(autoUpdateGate(facts({ ahead: 2, behind: 3 })).run).toBe(false);+ });++ it("pauses after two consecutive failed builds, and says which state it is in", () => {+ expect(autoUpdateGate(facts({ consecutiveFailures: 1 }))).toEqual({ run: true });+ const paused = autoUpdateGate(facts({ consecutiveFailures: 2 }));+ expect(paused.run).toBe(false);+ expect(paused.run === false && paused.reason).toContain("paused after 2 consecutive failed builds");+ });++ it("never auto-applies a commit that changes the updater", () => {+ for (const path of ["lib/host/self-update.ts", "scripts/mso-service-update", "scripts/self-update.sh"]) {+ const gate = autoUpdateGate(facts({ changedPaths: ["app/page.tsx", path] }));+ expect(gate.run, path).toBe(false);+ expect(gate.run === false && gate.reason).toContain(path);+ expect(gate.run === false && gate.reason).toContain("manually");+ }+ });++ it("does not apply the updater rule when there is nothing to pull", () => {+ // A pendingBuild-only run changes no commit, so no incoming diff is involved.+ expect(autoUpdateGate(facts({ behind: 0, pendingBuild: true, changedPaths: [] }))).toEqual({ run: true });+ expect(autoUpdateGate(facts({ behind: 0, changedPaths: ["scripts/self-update.sh"] }))).toMatchObject({ run: false });+ });++ it("calls a tag-lagging stable checkout current instead of falling back to main", () => {+ const gate = autoUpdateGate(facts({ behind: 0, target: "v0.2.0" }));+ expect(gate.run).toBe(false);+ expect(gate.run === false && gate.reason).toContain("already up to date with v0.2.0");+ });++ it("names the rolling fallback when no release tag exists yet", () => {+ const gate = autoUpdateGate(facts({ behind: 0, target: "origin/main (no release tag exists yet)", targetFallback: true }));+ expect(gate.run === false && gate.reason).toContain("no release tag exists yet");+ });+});++describe("touchesUpdater", () => {+ it("matches allowlisted updater paths only, never a prefix or a similar name", () => {+ expect(touchesUpdater(["lib/host/self-update.ts"])).toBe("lib/host/self-update.ts");+ expect(touchesUpdater(["lib/host/self-update.tsx"])).toBeNull();+ expect(touchesUpdater(["docs/self-update.sh.md"])).toBeNull();+ expect(touchesUpdater([])).toBeNull();+ });+});diff --git a/lib/host/update-decision.ts b/lib/host/update-decision.tsnew file mode 100644index 00000000..dce59687--- /dev/null+++ b/lib/host/update-decision.ts@@ -0,0 +1,178 @@+// The update DECISIONS, with no I/O: what `git` said (parseCommits), whether a+// checkout may update at all (updateBranchReason / blockingReason), and whether an+// UNATTENDED run may proceed (autoUpdateGate).+//+// This module is deliberately free of `server-only` and `@/` imports: the timer's+// pre-flight (scripts/self-update-auto.ts) runs it under bun, outside Next.+import type { UpdateChannel } from "../prefs/updates";++export interface UpdateCommit {+ sha: string;+ subject: string;+ date: string;+}++export interface UpdateStatus {+ /** False when this deployment cannot self-update (for example, not a checkout or no safe handoff runtime). */+ supported: boolean;+ /** Why not, when `supported` is false — shown to the operator verbatim. */+ reason: string | null;+ /** HEAD of the CHECKOUT — what a rebuild would compile. */+ current: string;+ currentSubject: string;+ /** Latest commit of the RESOLVED target (origin/main, or a release tag), independent of restart support. */+ latest?: string;+ /** The commit the RUNNING build was compiled from (baked in by next.config), or+ * "" when the build carried no .git. Differs from `current` whenever someone+ * pulled without rebuilding — the state the panel calls "a build is pending". */+ buildSha: string;+ pendingBuild: boolean;+ ahead: number;+ behind: number;+ commits: UpdateCommit[];+ /** Uncommitted work in the checkout: a `--ff-only` merge would fail, so refuse early. */+ dirty: boolean;+ running: boolean;+ /** False when `git fetch` could not reach the remote — `behind` is then only local knowledge. */+ remoteChecked: boolean;+ log: string;+ /** Which channel produced this comparison. Optional so older fixtures stay valid. */+ channel?: UpdateChannel;+ /** Server-resolved target label (`origin/main`, `v1.2.3`, …). Never a request value. */+ target?: string;+ /** Stable found no release tag at all and is tracking rolling main — said out loud. */+ targetFallback?: boolean;+}++/** `<sha>\x1f<subject>\x1f<iso date>` per line — a separator no subject can contain. */+export function parseCommits(stdout: string): UpdateCommit[] {+ return stdout+ .split("\n")+ .map((line) => line.trim())+ .filter(Boolean)+ .slice(0, 25)+ .map((line) => {+ const [sha = "", subject = "", date = ""] = line.split("\x1f");+ return { sha, subject: subject.slice(0, 200), date: date.slice(0, 10) };+ })+ .filter((c) => c.sha);+}++export function updateBranchReason(branch: string): string | null {+ const current = branch.trim();+ return current === "main"+ ? null+ : `software updates require the checkout to be on main (current: ${current || "detached HEAD"})`;+}++/**+ * Why this update must not start, or `null` when it may.+ *+ * Pure, and separate from the doing, because every one of these is a refusal an+ * operator has to be able to read — "nothing happened and here is why" beats a+ * build that fails halfway through with the live `.next` already deleted.+ */+export function blockingReason(status: UpdateStatus, rebuildOnly: boolean): string | null {+ const target = status.target ?? "origin/main";+ if (!status.supported) return status.reason ?? "this deployment cannot update itself";+ if (status.running) return "an update is already running";+ if (status.dirty) {+ return "the checkout has uncommitted changes — commit or stash them on the host first, a fast-forward would refuse anyway";+ }+ if (!rebuildOnly && status.ahead > 0) {+ return status.behind > 0+ ? `local main has diverged from ${target} (ahead ${status.ahead}, behind ${status.behind}); reconcile it before updating`+ : `local main is ahead of ${target} by ${status.ahead} commit(s); push or reconcile it before updating`;+ }+ // `pendingBuild` is a reason to run even with nothing to pull: the checkout+ // already holds code the running process was not built from, and refusing with+ // "already up to date" would be describing the wrong thing as up to date.+ if (!rebuildOnly && status.behind === 0 && !status.pendingBuild) return "already up to date";+ return null;+}++/** Files whose unattended replacement can strand the host: the updater itself, its+ * lifecycle wrapper, and the unit/restart logic. A human must apply these. */+export const UPDATER_PATHS = [+ "lib/host/self-update.ts",+ "lib/host/update-decision.ts",+ "lib/host/self-update-channel.ts",+ "lib/host/self-update-timer.ts",+ "scripts/mso-service-update",+ "scripts/self-update.sh",+ "scripts/self-update-auto.ts",+ "scripts/mso-auto-update",+];++export function touchesUpdater(paths: readonly string[]): string | null {+ const hit = paths.map((p) => p.trim()).find((p) => p && UPDATER_PATHS.includes(p));+ return hit ?? null;+}++export interface AutoGateFacts {+ /** The owner opted in. A timer that survived a `false` pref must still refuse. */+ auto: boolean;+ /** `UpdateStatus.supported` for the resolved channel. */+ supported: boolean;+ reason: string | null;+ dirty: boolean;+ running: boolean;+ ahead: number;+ behind: number;+ pendingBuild: boolean;+ /** Consecutive failed unattended builds, read from the updater-written state. */+ consecutiveFailures: number;+ /** Paths in `HEAD..target`. Only read when there is something to apply. */+ changedPaths: readonly string[];+ target: string;+ /** Stable channel had no release tag and is tracking rolling main. */+ targetFallback: boolean;+}++export type AutoGate = { run: true } | { run: false; reason: string };++/**+ * Unattended-run gate. Stricter than `blockingReason`: it also refuses after two+ * consecutive failed builds and whenever the incoming commits touch the updater.+ * Every refusal is a sentence, because nobody is watching when it happens.+ */+export function autoUpdateGate(facts: AutoGateFacts): AutoGate {+ if (!facts.auto) return { run: false, reason: "automatic updates are turned off" };+ if (!facts.supported) return { run: false, reason: facts.reason ?? "this deployment cannot update itself" };+ if (facts.running) return { run: false, reason: "an update is already running" };+ if (facts.dirty) {+ return { run: false, reason: "the checkout has uncommitted changes; a fast-forward would refuse anyway" };+ }+ if (facts.consecutiveFailures >= 2) {+ return {+ run: false,+ reason: "paused after 2 consecutive failed builds — inspect the update log, then run mso update from a terminal",+ };+ }+ if (facts.ahead > 0) {+ return {+ run: false,+ reason: facts.behind > 0+ ? `local main has diverged from ${facts.target} (ahead ${facts.ahead}, behind ${facts.behind}); reconcile first`+ : `local main is ahead of ${facts.target} by ${facts.ahead} commit(s); push or reconcile first`,+ };+ }+ if (facts.behind === 0 && !facts.pendingBuild) {+ return {+ run: false,+ reason: facts.targetFallback+ ? `no release tag exists yet, so ${facts.target} is the target; already up to date`+ : `already up to date with ${facts.target}`,+ };+ }+ if (facts.behind > 0) {+ const hit = touchesUpdater(facts.changedPaths);+ if (hit) {+ return {+ run: false,+ reason: `the incoming commits change ${hit}, part of the updater; apply this one manually with mso update`,+ };+ }+ }+ return { run: true };+}diff --git a/lib/host/update-facts.ts b/lib/host/update-facts.tsnew file mode 100644index 00000000..abe028c6--- /dev/null+++ b/lib/host/update-facts.ts@@ -0,0 +1,94 @@+// Raw comparison between the checkout and the resolved update target. No+// `server-only`, no Next alias: lib/host/self-update.ts (inside Next) and+// scripts/self-update-auto.ts (the nightly timer, outside Next) collect the SAME+// facts through this module, so an unattended run cannot decide on different+// numbers than the panel it is configured from.+import type { UpdateCommit } from "./update-decision";+import { parseCommits } from "./update-decision";+import { resolveUpdateTarget, stableRelationAhead, type TargetGitRunner } from "./self-update-channel";++export interface UpdateFacts {+ insideWorkTree: boolean;+ branch: string;+ head: string;+ subject: string;+ dirty: boolean;+ remoteChecked: boolean;+ ahead: number;+ behind: number;+ commits: UpdateCommit[];+ latest: string;+ /** Full sha of the resolved target; what an unattended run pins before building. */+ targetSha: string;+ /** Paths in `HEAD..target`, only read when `behind > 0` (see `autoUpdateGate`). */+ changedPaths: string[];+ targetRef: string;+ targetLabel: string;+ targetFallback: boolean;+}++export interface CollectOptions {+ git: TargetGitRunner;+ channel: "stable" | "main";+ /** A network round trip; the panel polls without it while a build runs. */+ fetch: boolean;+ /** `git fetch --quiet origin main …`; overridable so the timer can skip it. */+ fetchRemote?: () => Promise<{ code: number }>;+}++const EMPTY: UpdateFacts = {+ insideWorkTree: false, branch: "", head: "", subject: "", dirty: false,+ remoteChecked: false, ahead: 0, behind: 0, commits: [], latest: "",+ targetSha: "", changedPaths: [], targetRef: "origin/main", targetLabel: "origin/main", targetFallback: false,+};++export async function collectUpdateFacts(opts: CollectOptions): Promise<UpdateFacts> {+ const { git } = opts;+ const inside = await git(["rev-parse", "--is-inside-work-tree"]);+ if (inside.code !== 0 || inside.stdout.trim() !== "true") return { ...EMPTY };++ const [branch, head, subject, status] = await Promise.all([+ git(["branch", "--show-current"]),+ git(["rev-parse", "--short", "HEAD"]),+ git(["log", "-1", "--format=%s"]),+ git(["status", "--porcelain"]),+ ]);++ let remoteChecked = false;+ if (opts.fetch && opts.fetchRemote) {+ const fetched = await opts.fetchRemote();+ remoteChecked = fetched.code === 0;+ }++ const target = await resolveUpdateTarget(opts.channel, git);+ const relation = await git(["rev-list", "--left-right", "--count", `HEAD...${target.ref}`]);+ const [aheadRaw = "0", behindRaw = "0"] = relation.stdout.trim().split(/\s+/);+ const rawAhead = relation.code === 0 ? Number(aheadRaw) || 0 : 0;+ const behind = relation.code === 0 ? Number(behindRaw) || 0 : 0;+ // A stable checkout past its release tag is not "unpushed local work".+ const ahead = opts.channel === "stable" ? stableRelationAhead(rawAhead, behind) : rawAhead;++ const [commitLog, latest, sha, changed] = await Promise.all([+ git(["log", "--format=%h%x1f%s%x1f%cs", "-25", `HEAD..${target.ref}`]),+ git(["rev-parse", "--short", target.ref]),+ git(["rev-parse", "--verify", `${target.ref}^{commit}`]),+ behind > 0 ? git(["diff", "--name-only", `HEAD..${target.ref}`]) : Promise.resolve({ code: 0, stdout: "", stderr: "" }),+ ]);+ return {+ insideWorkTree: true,+ branch: branch.stdout,+ head: head.stdout.trim() || "unknown",+ subject: subject.stdout.trim(),+ dirty: status.stdout.trim().length > 0,+ remoteChecked,+ ahead,+ behind,+ commits: commitLog.code === 0 ? parseCommits(commitLog.stdout) : [],+ latest: latest.code === 0 ? latest.stdout.trim() : "",+ targetSha: sha.code === 0 ? sha.stdout.trim() : "",+ changedPaths: changed.code === 0 ? changed.stdout.split("\n").map((p) => p.trim()).filter(Boolean) : [],+ targetRef: target.ref,+ targetLabel: target.label,+ targetFallback: target.fallback,+ };+}diff --git a/lib/host/update-host-support.ts b/lib/host/update-host-support.tsnew file mode 100644index 00000000..0d7edf29--- /dev/null+++ b/lib/host/update-host-support.ts@@ -0,0 +1,105 @@+// Host capability probes the updater needs BOTH from inside Next (the Settings+// panel) and from the nightly timer (scripts/self-update-auto.ts, outside Next).+// No `server-only`, no `@/` alias — same reason as update-facts.ts.+import { execFile } from "node:child_process";+import { promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+import { updateBranchReason } from "./update-decision";++export const SELF_UPDATE_UNIT = "mso-self-update";+/** The timer-triggered persistent unit. Deliberately NOT `mso-self-update`: that+ * name belongs to `systemd-run --unit=`, and a unit file with the same name makes+ * every manual update from Settings fail with "unit already exists". */+export const AUTO_UPDATE_UNIT = "mso-auto-update";++export interface Ran {+ code: number;+ stdout: string;+ stderr: string;+}++export type Runner = (command: string, args: readonly string[], timeoutMs?: number, env?: NodeJS.ProcessEnv) => Promise<Ran>;++export const execRunner: Runner = (command, args, timeoutMs = 20_000, env) =>+ new Promise((resolve) => {+ execFile(+ command,+ [...args],+ { cwd: process.cwd(), timeout: timeoutMs, maxBuffer: 1024 * 1024, windowsHide: true, shell: false, ...(env ? { env } : {}) },+ (error, stdout, stderr) => {+ const code = typeof (error as { code?: number } | null)?.code === "number" ? (error as { code: number }).code : error ? 1 : 0;+ resolve({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });+ },+ );+ });++export const updateLogPath = (): string => {+ const override = process.env.MSO_UPDATE_LOG?.trim();+ return override || path.join(os.homedir(), ".mso", "self-update.log");+};++export async function readUpdateLog(): Promise<string> {+ const raw = await fs.readFile(/* turbopackIgnore: true */ updateLogPath(), "utf8").catch(() => "");+ // The panel polls this every 3s while a build runs, and the log is the biggest+ // thing in the response.+ return raw.length > 12_000 ? raw.slice(-12_000) : raw;+}++/** True only for an update already in flight. The auto unit itself is not counted:+ * the nightly pre-flight runs INSIDE it and must not refuse itself.+ * `offlineProbe` is injected because the setsid PID marker lives in a+ * `server-only` module the timer cannot import. */+export async function isUpdateRunning(+ run: Runner,+ offlineProbe: () => Promise<boolean>,+): Promise<boolean> {+ const [userUnit, legacySystemUnit] = await Promise.all([+ run("systemctl", ["--user", "is-active", `${SELF_UPDATE_UNIT}.service`], 10_000),+ run("systemctl", ["is-active", `${SELF_UPDATE_UNIT}.service`], 10_000),+ ]);+ if (userUnit.code === 0 || legacySystemUnit.code === 0) return true;+ return offlineProbe();+}++/** Restart authority must never suppress read-only version discovery. */+export async function automaticUpdateReason(run: Runner): Promise<string | null> {+ const branch = await run("git", ["branch", "--show-current"]);+ const branchReason = updateBranchReason(branch.stdout);+ if (branch.code !== 0 || branchReason) {+ return branch.code === 0 ? branchReason : "could not determine the checkout branch";+ }++ // The installer enables linger and gives mso.service XDG_RUNTIME_DIR precisely+ // so the service can reach this per-user manager. Unlike the old sudo path, this+ // is both non-interactive and non-root.+ const userManager = await run("systemctl", ["--user", "show-environment"], 10_000);+ if (userManager.code !== 0) {+ // A container/hosted runtime can legitimately have no systemd at all (PID 1+ // may be tini). The CLI already has a safe offline update path that quiesces+ // only MSO-owned runtimes under the checkout exclusion lock. `setsid -f` is+ // the missing handoff boundary: it lets that path survive the Next process it+ // intentionally stops and replaces. No sudo and no arbitrary client argv.+ const setsid = process.platform === "linux" ? await run("setsid", ["--version"], 5_000) : { code: 1, stdout: "", stderr: "" };+ if (setsid.code === 0) return null;+ return "Automatic restart is unavailable on this host. Run mso update from a terminal; version checks still work.";+ }++ const [loadState, serviceUser, restartPolicy] = await Promise.all([+ run("systemctl", ["show", "-p", "LoadState", "--value", "mso.service"], 10_000),+ run("systemctl", ["show", "-p", "User", "--value", "mso.service"], 10_000),+ run("systemctl", ["show", "-p", "Restart", "--value", "mso.service"], 10_000),+ ]);+ if (loadState.code !== 0 || loadState.stdout.trim() !== "loaded") {+ return "mso.service is not installed; run mso update from a terminal for this host.";+ }+ if (restartPolicy.code !== 0 || restartPolicy.stdout.trim() === "no") {+ return "mso.service has no automatic restart policy; refusing to stop the running process during self-update";+ }+ const owner = os.userInfo().username;+ if (serviceUser.code !== 0 || serviceUser.stdout.trim() !== owner) {+ return `mso.service runs as ${serviceUser.stdout.trim() || "an unknown user"}, not ${owner}; refusing a cross-user update`;+ }++ return null;+}diff --git a/lib/prefs/auto-update-state.test.ts b/lib/prefs/auto-update-state.test.tsnew file mode 100644index 00000000..fa9c0a5a--- /dev/null+++ b/lib/prefs/auto-update-state.test.ts@@ -0,0 +1,62 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+import { AUTO_UPDATE_STATE_DEFAULTS, clearAutoUpdatePause, readAutoUpdateState, writeAutoUpdateState } from "./auto-update-state";++let dir: string;+let file: string;++beforeEach(async () => {+ dir = await fs.mkdtemp(path.join(os.tmpdir(), "mso-auto-update-"));+ file = path.join(dir, "state.json");+ process.env.MSO_AUTO_UPDATE_STATE = file;+});++afterEach(async () => {+ delete process.env.MSO_AUTO_UPDATE_STATE;+ await fs.rm(dir, { recursive: true, force: true });+});++describe("auto-update runtime state", () => {+ it("reports an untouched host as never-attempted rather than failing", async () => {+ expect(await readAutoUpdateState()).toEqual(AUTO_UPDATE_STATE_DEFAULTS);+ await fs.writeFile(file, "{not json", "utf8");+ expect(await readAutoUpdateState()).toEqual(AUTO_UPDATE_STATE_DEFAULTS);+ });++ it("writes owner-only state and merges patches", async () => {+ await writeAutoUpdateState({ lastAttemptAt: 1_700_000_000_000, lastResult: "failed", consecutiveFailures: 1 });+ await writeAutoUpdateState({ detail: "FAILED: build" });+ const got = await readAutoUpdateState();+ expect(got).toMatchObject({ lastResult: "failed", consecutiveFailures: 1, detail: "FAILED: build" });+ expect((await fs.stat(file)).mode & 0o777).toBe(0o600);+ });++ it("refuses values it did not produce instead of rendering them", async () => {+ await fs.writeFile(file, JSON.stringify({ lastResult: "great", consecutiveFailures: "many", detail: 42 }), "utf8");+ expect(await readAutoUpdateState()).toMatchObject({ lastResult: null, consecutiveFailures: 0, detail: null });+ });++ it("clears the unattended pause so the gate's own advice can work", async () => {+ // The gate refuses at 2 failures and tells the operator to run `mso update` by+ // hand. Before this reset existed that advice was false: only a SUCCESSFUL+ // unattended run cleared the count, and the gate prevented exactly that.+ await writeAutoUpdateState({ consecutiveFailures: 2, lastResult: "failed", detail: "FAILED: build" });+ await clearAutoUpdatePause();+ const after = await readAutoUpdateState();+ expect(after.consecutiveFailures).toBe(0);+ // Evidence of what happened survives: only the streak is a gate input.+ expect(after.lastResult).toBe("failed");+ expect(after.detail).toBe("FAILED: build");+ });++ it("leaves an already-clear streak alone without rewriting the file", async () => {+ await writeAutoUpdateState({ consecutiveFailures: 0, lastResult: "ok" });+ const before = await fs.stat(file);+ await clearAutoUpdatePause();+ const after = await fs.stat(file);+ expect(after.mtimeMs).toBe(before.mtimeMs);+ expect((await readAutoUpdateState()).consecutiveFailures).toBe(0);+ });+});diff --git a/lib/prefs/auto-update-state.ts b/lib/prefs/auto-update-state.tsnew file mode 100644index 00000000..8e8e58cd--- /dev/null+++ b/lib/prefs/auto-update-state.ts@@ -0,0 +1,82 @@+// Read-only view of unattended-update state. Written ONLY by the updater+// (scripts/self-update-auto.ts) — never by an HTTP client, which is why it lives+// beside prefs.json instead of inside it. A client that could set `lastResult`+// could make a broken host read "ok".+import { promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+import type { UpdateChannel } from "./updates";++export type AutoUpdateResult = "ok" | "failed" | "skipped";++export interface AutoUpdateState {+ lastAttemptAt: number | null;+ lastResult: AutoUpdateResult | null;+ /** Grows per failed unattended run and is reset by any success. The gate pauses+ * at 2 — the update log is truncated on every attempt, so the count cannot be+ * recovered from it after the fact. */+ consecutiveFailures: number;+ /** Human sentence for the last skip/failure, shown next to the result. */+ detail: string | null;+ channel: UpdateChannel | null;+}++export const AUTO_UPDATE_STATE_DEFAULTS: AutoUpdateState = {+ lastAttemptAt: null,+ lastResult: null,+ consecutiveFailures: 0,+ detail: null,+ channel: null,+};++const statePath = (): string => {+ const override = process.env.MSO_AUTO_UPDATE_STATE?.trim();+ return override || path.join(os.homedir(), ".mso", "auto-update-state.json");+};++const RESULTS = new Set<AutoUpdateResult>(["ok", "failed", "skipped"]);++export async function readAutoUpdateState(): Promise<AutoUpdateState> {+ try {+ const raw = JSON.parse(await fs.readFile(/* turbopackIgnore: true */ statePath(), "utf8")) as Record<string, unknown>;+ const attempts = Number(raw.consecutiveFailures);+ return {+ lastAttemptAt: Number.isSafeInteger(raw.lastAttemptAt) ? (raw.lastAttemptAt as number) : null,+ lastResult: RESULTS.has(raw.lastResult as AutoUpdateResult) ? (raw.lastResult as AutoUpdateResult) : null,+ consecutiveFailures: Number.isSafeInteger(attempts) && attempts >= 0 ? attempts : 0,+ detail: typeof raw.detail === "string" ? raw.detail.slice(0, 300) : null,+ channel: raw.channel === "stable" || raw.channel === "main" ? raw.channel : null,+ };+ } catch {+ return { ...AUTO_UPDATE_STATE_DEFAULTS };+ }+}++export async function writeAutoUpdateState(patch: Partial<AutoUpdateState>): Promise<AutoUpdateState> {+ const next = { ...(await readAutoUpdateState()), ...patch };+ const file = statePath();+ await fs.mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true, mode: 0o700 });+ const tmp = `${file}.tmp`;+ await fs.writeFile(tmp, JSON.stringify(next, null, 2), { encoding: "utf8", mode: 0o600 });+ await fs.rename(tmp, file);+ return next;+}++/**+ * Clear the unattended pause when an operator starts an update by hand.+ *+ * `autoUpdateGate` stops after two consecutive failed builds and tells the operator+ * to inspect the log and run `mso update` from a terminal. Without this reset that+ * advice was false: the streak only cleared on a SUCCESSFUL unattended run, which+ * could never happen while the gate was refusing. The count is left at zero rather+ * than 1 so a single new failure does not re-pause immediately — the operator has+ * just looked at the machine.+ *+ * Deliberately does not touch `lastResult`/`detail`: those are evidence of what+ * happened, and a manual attempt that later fails will overwrite them itself.+ */+export async function clearAutoUpdatePause(): Promise<void> {+ const current = await readAutoUpdateState();+ if (current.consecutiveFailures === 0) return;+ await writeAutoUpdateState({ consecutiveFailures: 0 });+}diff --git a/lib/prefs/store.ts b/lib/prefs/store.tsindex 864e4690..42df8919 100644--- a/lib/prefs/store.ts+++ b/lib/prefs/store.ts@@ -4,11 +4,13 @@ import os from "os";import path from "path";import type { Tweaks } from "@/lib/appearance";import type { Quicklink } from "@/lib/quicklinks";+import type { PrefUpdates } from "./updates";-// Cross-device prefs (appearance tweaks + quicklinks), mirroring lib/config/store:-// a host JSON file (chmod 600) read/written server-side only, atomic tmp+rename.-// `wallpaperStyle` is computed client-side from `wallpaperImage` (parseImage →-// withWallpaperStyle), so it is never persisted — the route strips it.+// Cross-device prefs (appearance tweaks + quicklinks + update automation),+// mirroring lib/config/store: a host JSON file (chmod 600) read/written+// server-side only, atomic tmp+rename. `wallpaperStyle` is computed client-side+// from `wallpaperImage` (parseImage → withWallpaperStyle), so it is never+// persisted — the route strips it./** Persisted tweaks: everything except the computed CSS style object. */export type PrefTweaks = Omit<Tweaks, "wallpaperStyle">;@@ -16,6 +18,10 @@ export type PrefTweaks = Omit<Tweaks, "wallpaperStyle">;export interface OsPrefs {tweaks?: PrefTweaks;quicklinks?: Quicklink[];+ /** Owner-only automation settings. Runtime outcomes are NOT stored here — the+ * updater writes ~/.mso/auto-update-state.json so a client can never forge a+ * "last result", and the two writers never lose each other's section. */+ updates?: PrefUpdates;updatedAt?: number;}diff --git a/lib/prefs/updates.test.ts b/lib/prefs/updates.test.tsnew file mode 100644index 00000000..6d77a6af--- /dev/null+++ b/lib/prefs/updates.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from "vitest";+import { parseUpdateChannel, resolveUpdates, sanitizeUpdatesPatch, UPDATE_PREF_DEFAULTS } from "./updates";++describe("update preference shape", () => {+ it("defaults to opt-OUT on the stable channel", () => {+ expect(UPDATE_PREF_DEFAULTS).toEqual({ auto: false, channel: "main" });+ expect(resolveUpdates(undefined)).toEqual({ auto: false, channel: "main" });+ expect(resolveUpdates("garbage")).toEqual({ auto: false, channel: "main" });+ });++ it("tolerates a hand-edited store without letting it mean 'on'", () => {+ expect(resolveUpdates({ auto: "yes", channel: "nightly" })).toEqual({ auto: false, channel: "main" });+ expect(resolveUpdates({ auto: true, channel: "main" })).toEqual({ auto: true, channel: "main" });+ });++ it("accepts only the two documented keys with their documented types", () => {+ expect(sanitizeUpdatesPatch({ auto: true })).toEqual({ ok: true, patch: { auto: true } });+ expect(sanitizeUpdatesPatch({ channel: "main" })).toEqual({ ok: true, patch: { channel: "main" } });+ for (const bad of [+ { auto: "true" },+ { channel: "nightly" },+ { channel: "origin/main" },+ { auto: true, ref: "origin/main" },+ { auto: true, lastResult: "ok" },+ [],+ "on",+ {},+ ]) {+ expect(sanitizeUpdatesPatch(bad).ok, JSON.stringify(bad)).toBe(false);+ }+ });++ it("parses the channel enum without inventing a third value", () => {+ expect(parseUpdateChannel("stable")).toBe("stable");+ expect(parseUpdateChannel("main")).toBe("main");+ for (const bad of ["main2", "origin/main", "", null, 1, undefined]) expect(parseUpdateChannel(bad)).toBeNull();+ });++ it("defaults to main because release tags lag far behind this repo's branch", () => {+ // A tag-based default is not neutral here: v0.2.0 is an ancestor of HEAD with+ // >1000 commits between them, so `stable` would report "already up to date" and+ // hide the update action on a checkout that is far ahead of its newest tag.+ // main is also what every install followed before channels existed.+ expect(UPDATE_PREF_DEFAULTS.channel).toBe("main");+ // stable must still be reachable, as an explicit choice.+ expect(sanitizeUpdatesPatch({ channel: "stable" })).toEqual({ ok: true, patch: { channel: "stable" } });+ });++ it("does not resurrect stable from a stored record that never chose it", () => {+ // Hand-edited or pre-channel store: no channel key means "did not opt in".+ expect(resolveUpdates({ auto: true }).channel).toBe("main");+ });+});diff --git a/lib/prefs/updates.ts b/lib/prefs/updates.tsnew file mode 100644index 00000000..d17e2f60--- /dev/null+++ b/lib/prefs/updates.ts@@ -0,0 +1,74 @@+// Opt-in unattended updates: the ONE pref shape plus its strict validator.+//+// This module is pure and alias-free on purpose: `scripts/self-update-auto.ts`+// (the timer entry point, run by bun) imports it through the gate module, so an+// `@/` specifier here would need tsconfig path resolution at runtime.+//+// The channel is a FIXED enum. No ref, path, tag, or command is ever accepted+// from a request — the client picks `stable` or `main` and the updater resolves+// the actual Git target server-side (lib/host/self-update-channel.ts).++export type UpdateChannel = "stable" | "main";++export const UPDATE_CHANNELS = ["stable", "main"] as const;++/** Persisted settings only. Runtime outcomes (last attempt, failures) are+ * written by the updater to ~/.mso/auto-update-state.json, never by a client+ * and never into this file — two writers on prefs.json would lose updates. */+export interface PrefUpdates {+ auto: boolean;+ channel: UpdateChannel;+}++/**+ * `main` by default, deliberately.+ *+ * `stable` was the planned default, but this repository's release tags lag far+ * behind the branch: v0.2.0 is an ancestor of HEAD with 1127 commits in between.+ * A tag-based default therefore reports "already up to date" on a checkout that is+ * a thousand commits ahead of its newest tag, which hides the update action+ * entirely — the exact symptom this work exists to remove. Following `main` is+ * also what every existing install did before channels existed, so keeping it the+ * default changes nobody's behaviour silently. `stable` is an explicit opt-in.+ */+export const UPDATE_PREF_DEFAULTS: PrefUpdates = { auto: false, channel: "main" };++export function parseUpdateChannel(value: unknown): UpdateChannel | null {+ return value === "stable" || value === "main" ? value : null;+}++/** Strict merge patch: unknown keys, wrong types and bad enum values are errors,+ * not silently dropped, so a client cannot believe it enabled something. */+export function sanitizeUpdatesPatch(+ raw: unknown,+): { ok: true; patch: Partial<PrefUpdates> } | { ok: false; error: string } {+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {+ return { ok: false, error: "updates must be an object" };+ }+ const entries = Object.entries(raw as Record<string, unknown>);+ if (entries.length === 0) return { ok: false, error: "updates is empty" };+ const patch: Partial<PrefUpdates> = {};+ for (const [key, value] of entries) {+ if (key === "auto") {+ if (typeof value !== "boolean") return { ok: false, error: "updates.auto must be a boolean" };+ patch.auto = value;+ } else if (key === "channel") {+ const channel = parseUpdateChannel(value);+ if (!channel) return { ok: false, error: "updates.channel must be stable or main" };+ patch.channel = channel;+ } else {+ return { ok: false, error: `updates.${key} is not writable` };+ }+ }+ return { ok: true, patch };+}++/** Stored value → effective value, tolerating a hand-edited store. */+export function resolveUpdates(stored: unknown): PrefUpdates {+ if (!stored || typeof stored !== "object" || Array.isArray(stored)) return { ...UPDATE_PREF_DEFAULTS };+ const row = stored as Record<string, unknown>;+ return {+ auto: row.auto === true,+ channel: parseUpdateChannel(row.channel) ?? UPDATE_PREF_DEFAULTS.channel,+ };+}diff --git a/package.json b/package.jsonindex 00585851..6db79e34 100644--- a/package.json+++ b/package.json@@ -65,6 +65,7 @@"dependencies": {"@anthropic-ai/sdk": "^0.133.0","@imgly/background-removal": "^1.7.0",+ "@phosphor-icons/react": "^2.1.10","@radix-ui/react-alert-dialog": "^1.2.0","@radix-ui/react-dialog": "^1.3.0","@radix-ui/react-dropdown-menu": "^2.2.0",@@ -90,6 +91,7 @@"react-dom": "^19.3.0","react-konva": "^19.3.0","react-resizable-panels": "^4.14.4",+ "sharp": "^0.35.5","tailwind-merge": "^3.7.0","tw-animate-css": "^1.4.0","vaul": "^1.1.2",@@ -100,7 +102,6 @@],"overrides": {"postcss": "^8.5.10",- "sharp": "^0.35.5","nanoid": "^3.3.18","js-yaml": "^4.3.2","micromatch": "npm:[email protected]"diff --git a/proxy.ts b/proxy.tsindex 7979b571..31e81978 100644--- a/proxy.ts+++ b/proxy.ts@@ -37,6 +37,7 @@ import { applyPrivatePageCachePolicy } from "@/lib/auth/page-cache";import { gateManagedApp } from "@/lib/managed-apps/session";import { sessionAppForHost, shellAppTarget, shellAppUpstreamHeaders } from "@/lib/surfaces/session";import { gateShellApp, shellAppResponseHeaders } from "@/lib/surfaces/session-gate";+import { requestBodyLimit } from "@/scripts/server-body-policy.mjs";import { IS_DEMO } from "@/lib/demo";const MUTATING = new Set(["POST", "PUT", "PATCH", "DELETE"]);@@ -145,7 +146,7 @@ function contentSecurityPolicy(nonce: string): string {export async function proxy(request: NextRequest) {const { pathname } = request.nextUrl;const contentLength = request.headers.get("content-length");- if (contentLength && Number(contentLength) > 1024 * 1024)+ if (contentLength && Number(contentLength) > requestBodyLimit(pathname))return NextResponse.json({ error: "request_too_large" }, { status: 413 });// Which app host this is, if any. The HOST header is authoritative and@@ -352,5 +353,10 @@ export async function proxy(request: NextRequest) {// a path middleware never sees — a Traefik-level block is not available. The// cockpit short-circuits those in MATCHER_EXCLUDED above.export const config = {- matcher: ["/((?!api/v1/fs/upload$).*)"],+ // Routes that stream their own bounded body skip the clone middleware entirely.+ // Written out literally: a matcher is a compile-time string, so deriving it from+ // BODY_CLONE_BYPASS at runtime only looked equivalent while being impossible to+ // review (and the first escaped version silently failed to match). The policy test+ // asserts that this list and BODY_CLONE_BYPASS stay in sync.+ matcher: ["/((?!api/v1/fs/upload$|api/auth/account/icon$).*)"],};diff --git a/scripts/cli/commands-admin.sh b/scripts/cli/commands-admin.shindex eff275b3..9d4e4426 100755--- a/scripts/cli/commands-admin.sh+++ b/scripts/cli/commands-admin.sh@@ -87,7 +87,24 @@ case "$cmd" in# The same self-update Settings → Update MSO drives, so both surfaces get the same# preflight and the same transient-unit handoff (a build spawned from the service# would be killed by the restart it performs).- update) local_url="$(gateway_local_url)"; MSO_UPDATE_ROOT="$ROOT" MSO_UPDATE_LOCAL_URL="$local_url" "$ROOT/scripts/mso-update" "$@" ;;+ # `--auto` / `--channel` are SETTINGS, not a run: they go to the same authority the+ # Settings toggle uses. Keeping them out of scripts/mso-update means a value can+ # never be mistaken for a target ref.+ update)+ case "${1-}" in+ --auto)+ case "${2-}" in+ on|off) bun "$ROOT/scripts/mso-update-automation.ts" auto "${2}" ;;+ *) die "usage: mso update --auto on|off" ;;+ esac ;;+ --channel)+ case "${2-}" in+ stable|main) bun "$ROOT/scripts/mso-update-automation.ts" channel "${2}" ;;+ *) die "usage: mso update --channel stable|main" ;;+ esac ;;+ *)+ local_url="$(gateway_local_url)"; MSO_UPDATE_ROOT="$ROOT" MSO_UPDATE_LOCAL_URL="$local_url" "$ROOT/scripts/mso-update" "$@" ;;+ esac ;;# ── editor-document CRUD (one pattern, all editor features) ──────────────crud)diff --git a/scripts/cli/commands.sh b/scripts/cli/commands.shindex ff07236f..881b2274 100755--- a/scripts/cli/commands.sh+++ b/scripts/cli/commands.sh@@ -39,7 +39,7 @@ U_service="service status|start|stop|restart|logs [n]"U_unit="unit logs <system|user> <unit> [limit]|start|stop|restart <system|user> <unit>"U_reset="reset [--scope config|all] [--json] [--apply --confirm <preview-token>]"U_uninstall="uninstall [--purge] [--remove-code] [--service name.service] [--json] [--apply --confirm <preview-token>]"-U_update="update [--rebuild] | status | reconcile | log"+U_update="update [--rebuild] | status | reconcile | log | --auto on|off | --channel stable|main"U_cockpit="cockpit [project] | cockpit show [project] | cockpit search <query…>"U_threads="threads list|show <id>|save <json>|rename <json>|rm <id>"U_agent_sessions="agent-sessions list [limit]|show <id>|create [title]"diff --git a/scripts/lib/update-git-authority.sh b/scripts/lib/update-git-authority.shindex bb965805..b53c5a47 100755--- a/scripts/lib/update-git-authority.sh+++ b/scripts/lib/update-git-authority.sh@@ -1,14 +1,16 @@#!/usr/bin/env bash-# Classify one checkout against its fetched origin/main without mutating history.+# Classify one checkout against an update target without mutating history.# Output: <exact|behind|ahead|diverged> <ahead-count> <behind-count>-update_git_relation() {- local root="$1" head remote ahead behind relation+# Target may be origin/main (rolling channel) or a release tag resolved by the+# caller. It is always a value this repository produced, never request input.+update_git_relation_to() {+ local root="$1" target="$2" head remote ahead behind relationhead="$(git -C "$root" rev-parse HEAD 2>/dev/null || true)"- remote="$(git -C "$root" rev-parse origin/main 2>/dev/null || true)"+ remote="$(git -C "$root" rev-parse "$target" 2>/dev/null || true)"[[ "$head" =~ ^[0-9a-f]{40}$ ]] && [[ "$remote" =~ ^[0-9a-f]{40}$ ]] || return 1- ahead="$(git -C "$root" rev-list --count origin/main..HEAD 2>/dev/null || true)"- behind="$(git -C "$root" rev-list --count HEAD..origin/main 2>/dev/null || true)"+ ahead="$(git -C "$root" rev-list --count "$target"..HEAD 2>/dev/null || true)"+ behind="$(git -C "$root" rev-list --count HEAD.."$target" 2>/dev/null || true)"[[ "$ahead" =~ ^[0-9]+$ ]] && [[ "$behind" =~ ^[0-9]+$ ]] || return 1if [ "$ahead" -eq 0 ] && [ "$behind" -eq 0 ]; then relation=exactelif [ "$ahead" -eq 0 ]; then relation=behind@@ -17,3 +19,62 @@ update_git_relation() {fiprintf '%s %s %s\n' "$relation" "$ahead" "$behind"}++update_git_relation() {+ update_git_relation_to "$1" origin/main+}++# Highest release tag reachable from origin/main, or empty when none exists.+# The tag grammar is the SAME allowlist lib/host/self-update-channel.ts applies, and+# a tag that does not match is dropped rather than quoted: it would become argv.+update_git_latest_release_tag() {+ local root="$1" tags tag best best_parts parts+ tags="$(git -C "$root" tag --merged origin/main --list 'v*' 2>/dev/null || true)"+ best=""+ while IFS= read -r tag; do+ [ -n "$tag" ] || continue+ printf '%s\n' "$tag" | grep -Eq '^v?[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,4}$' || continue+ if [ -z "$best" ]; then best="$tag"; continue; fi+ if [ "$(printf '%s\n%s\n' "$best" "$tag" | sort -V | tail -1)" = "$tag" ] && [ "$tag" != "$best" ]; then+ best="$tag"+ fi+ done <<<"$tags"+ printf '%s' "$best"+}++# Resolve the channel enum into a concrete Git ref. Prints ONLY the ref on stdout+# (it is consumed by command substitution) and sets UPDATE_TARGET_FALLBACK=1 when+# stable had no release tag and is therefore tracking rolling main, so the caller+# decides where that is said out loud.+# main → origin/main (rolling, unchanged)+# stable → highest release tag on origin/main; origin/main ONLY when no tag exists+UPDATE_TARGET_FALLBACK="${UPDATE_TARGET_FALLBACK:-0}"+update_git_resolve_target() {+ local root="$1" channel="$2" tag+ UPDATE_TARGET_FALLBACK=0+ case "$channel" in+ main)+ printf 'origin/main' ;;+ stable)+ tag="$(update_git_latest_release_tag "$root")"+ if [ -n "$tag" ]; then+ printf '%s' "$tag"+ else+ UPDATE_TARGET_FALLBACK=1+ printf 'origin/main'+ fi ;;+ *)+ printf 'unknown update channel: %s\n' "$channel" >&2+ return 1 ;;+ esac+}++# Human note for a resolved target. Empty for rolling main on the main channel.+update_channel_note() {+ local channel="$1" target="$2" fallback="${3:-0}"+ if [ "$target" != origin/main ]; then+ printf ' (%s channel, release %s)' "$channel" "$target"+ elif [ "$fallback" = 1 ] || [ "$channel" = stable ]; then+ printf ' (stable channel: no release tag exists yet, tracking origin/main)'+ fi+}diff --git a/scripts/mso-auto-update b/scripts/mso-auto-updatenew file mode 100755index 00000000..8f440e4d--- /dev/null+++ b/scripts/mso-auto-update@@ -0,0 +1,55 @@+#!/usr/bin/env bash+# Entry point of the nightly timer unit (mso-auto-update.service).+#+# It asks the TypeScript pre-flight whether THIS night may run unattended. The+# pre-flight is where every refusal lives (unsupported checkout, dirty tree, an+# update already in flight, two consecutive failed builds, incoming commits that+# touch the updater) — see lib/host/update-decision.ts. This script only executes+# the decision and records the outcome for the panel.+#+# pre-flight refuses → SKIP <reason>, exit 0 (a correct decision is not a unit+# failure, and a failed unit would stop the next night too)+# pre-flight agrees → the same lifecycle Settings uses, then record ok/failed+set -uo pipefail+umask 077++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" || exit 1+cd "$ROOT" || exit 1+export PATH="$HOME/.bun/bin:$HOME/.local/bin:$PATH"+export NO_COLOR=1 TERM=dumb++preflight="$(bun "$ROOT/scripts/self-update-auto.ts" 2>&1)" || {+ printf 'auto update: pre-flight failed\n%s\n' "$preflight" >&2+ exit 1+}+printf '%s\n' "$preflight"+case "$preflight" in+ "RUN "*) ;;+ "SKIP "*) exit 0 ;;+ *) printf 'auto update: pre-flight printed no decision; refusing\n' >&2; exit 1 ;;+esac++channel="$(printf '%s\n' "$preflight" | sed -n 's/^MSO_AUTO_CHANNEL=//p' | tail -1)"+case "$channel" in+ stable|main) ;;+ *) printf 'auto update: pre-flight produced no valid channel; refusing\n' >&2; exit 1 ;;+esac+# The commit the pre-flight INSPECTED (it checked which files those commits touch).+# self-update.sh refuses when the resolved target has moved since, so a tag pushed+# between the decision and the build can never be applied unreviewed.+target="$(printf '%s\n' "$preflight" | sed -n 's/^MSO_AUTO_TARGET_SHA=//p' | tail -1)"+case "$target" in+ ????????????????????????????????????????) ;;+ *) printf 'auto update: pre-flight produced no target commit; refusing\n' >&2; exit 1 ;;+esac+export MSO_AUTO_TARGET_SHA="$target"++# A human starting an update is already refused by the pre-flight; this lock is the+# second half of the same rule, because both entry points share it.+if ! /bin/bash "$ROOT/scripts/mso-service-update" "--channel=$channel"; then+ bun "$ROOT/scripts/self-update-auto.ts" --record failed >/dev/null 2>&1 || true+ printf 'auto update: the update did not finish; see %s\n' "${MSO_UPDATE_LOG:-$HOME/.mso/self-update.log}" >&2+ exit 1+fi+bun "$ROOT/scripts/self-update-auto.ts" --record ok >/dev/null 2>&1 || true+printf 'AUTO UPDATE OK\n'diff --git a/scripts/mso-offline-update-job b/scripts/mso-offline-update-jobindex 5306a2c5..2e720c92 100755--- a/scripts/mso-offline-update-job+++ b/scripts/mso-offline-update-job@@ -20,6 +20,8 @@ trap cleanup EXIT HUP INT TERMexec >>"$LOG" 2>&1printf '[%s] == detached offline update\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"+# The wrapper receives only fixed argv; the channel comes from the same preference+# file the Settings panel wrote before it launched this job (mso-update reads it).case "${1:-}" in"") /bin/bash "$ROOT/scripts/mso-update" ;;--rebuild-only) /bin/bash "$ROOT/scripts/mso-update" --rebuild ;;diff --git a/scripts/mso-update b/scripts/mso-updateindex 177c072a..1a94315a 100755--- a/scripts/mso-update+++ b/scripts/mso-update@@ -23,13 +23,48 @@ GATEWAY="$ROOT/scripts/mso-gateway"fail() { printf 'mso update: %s\n' "$*" >&2; exit 1; }git_root() { [ "$(git -C "$ROOT" rev-parse --show-toplevel 2>/dev/null || true)" = "$ROOT" ]; }current_version() { sed -n 's/^VERSION="\([^"]*\)".*/\1/p' "$ROOT/bin/mso" | head -1; }-remote_version() { git -C "$ROOT" show origin/main:bin/mso 2>/dev/null | sed -n 's/^VERSION="\([^"]*\)".*/\1/p' | head -1; }+remote_version() { git -C "$ROOT" show "${1:-origin/main}:bin/mso" 2>/dev/null | sed -n 's/^VERSION="\([^"]*\)".*/\1/p' | head -1; }require_checkout() {git_root || fail "$ROOT is not a Git checkout; reinstall from the official repository"[ "$(git -C "$ROOT" branch --show-current)" = main ] || fail "updates require the installed checkout to be on main"[ -z "$(git -C "$ROOT" status --porcelain)" ] || fail "checkout has local changes; refusing to overwrite them"}-fetch_main() { update_git_fetch_origin "$ROOT" main || fail "could not reach origin/main"; }+fetch_main() { update_git_fetch_origin "$ROOT" main --tags || fail "could not reach origin/main"; }++# The owner's channel. Precedence: the caller's resolved enum (the detached offline+# wrapper passes the same value the API chose) → the prefs file the Settings panel+# writes → the documented default. Only the two-word enum is ever accepted.+configured_channel() {+ local raw+ raw="${MSO_UPDATE_CHANNEL:-$(jq -r '.updates.channel // "stable"' "${OS_PREFS_PATH:-$HOME/.mso/prefs.json}" 2>/dev/null || printf 'stable')}"+ case "$raw" in+ main) printf 'main' ;;+ *) printf 'stable' ;;+ esac+}++# Clear the unattended failure streak after a manual attempt. Failure is ignored: the+# state file is evidence for the panel, never a precondition for updating by hand.+clear_automation_pause() {+ local module="$ROOT/scripts/mso-update-automation.ts"+ if [ -f "$module" ] && command -v bun >/dev/null 2>&1; then+ bun "$module" resume >/dev/null 2>&1 || true+ fi+}++# Relation of HEAD to a channel target. A checkout PAST its release tag is normal,+# not "unpushed local work", so `ahead` only counts when the release has something to+# apply. Mirrors stableRelationAhead() in lib/host/self-update-channel.ts.+read_relation() {+ local target="$1" relation ahead behind+ read -r relation ahead behind < <(update_git_relation_to "$ROOT" "$target") || return 1+ if [ "$target" != origin/main ] && [ "$behind" -eq 0 ]; then+ ahead=0+ [ "$relation" = ahead ] && relation=exact+ fi+ printf '%s %s %s\n' "$relation" "$ahead" "$behind"+}+service_is_active() {# Containers/Codespaces often ship the systemctl binary without systemd as PID 1.# A read-only probe must classify that as "no active service" without leaking@@ -67,17 +102,21 @@ require_service_checkout() {|| fail "active mso.service belongs to $canonical_service, not this checkout $canonical_root; run update from the service checkout"}print_status() {- local relation ahead n local_v remote_v head receipt=''+ local relation ahead n local_v remote_v head receipt='' channel target target_note=''require_checkout; fetch_main- read -r relation ahead n < <(update_git_relation "$ROOT") || fail "could not compare HEAD with origin/main"- local_v="$(current_version)"; remote_v="$(remote_version)"; head="$(git -C "$ROOT" rev-parse HEAD)"+ channel="$(configured_channel)"+ target="$(update_git_resolve_target "$ROOT" "$channel")" || fail "could not resolve the $channel channel target"+ read -r relation ahead n < <(read_relation "$target") || fail "could not compare HEAD with $target"+ target_note="$(update_channel_note "$channel" "$target" "$UPDATE_TARGET_FALLBACK")"+ local_v="$(current_version)"; remote_v="$(remote_version "$target")"; head="$(git -C "$ROOT" rev-parse HEAD)"+ printf 'channel: %s%s\n' "$channel" "$target_note"if [ "$relation" = ahead ]; then- printf 'local main is ahead of origin/main by %s commit%s; refusing to deploy unpushed code.\n' "$ahead" "$([ "$ahead" = 1 ] || printf s)"+ printf 'local main is ahead of %s by %s commit%s; refusing to deploy unpushed code.\n' "$target" "$ahead" "$([ "$ahead" = 1 ] || printf s)"printf 'run: mso update reconcile # preserves current HEAD on a rescue branch first\n'returnfiif [ "$relation" = diverged ]; then- printf 'local main has diverged from origin/main (ahead %s, behind %s); refusing update.\n' "$ahead" "$n"+ printf 'local main has diverged from %s (ahead %s, behind %s); refusing update.\n' "$target" "$ahead" "$n"printf 'run: mso update reconcile # preserves current HEAD on a rescue branch first\n'returnfi@@ -87,7 +126,7 @@ print_status() {elseprintf 'update available: mso CLI %s -> %s (%s commit%s)\n' "${local_v:-unknown}" "${remote_v:-newer}" "$n" "$([ "$n" = 1 ] || printf s)"fi- git -C "$ROOT" log --format=' %h %s' -5 HEAD..origin/main+ git -C "$ROOT" log --format=' %h %s' -5 "HEAD..$target"printf 'run: mso update\n'returnfi@@ -195,23 +234,30 @@ notice() {}offline_build_locked() {- local rebuild_only="$1" n head receipt=''+ local rebuild_only="$1" n head receipt='' channel targetrequire_checkoutservice_is_active && fail "mso.service became active while waiting for the offline update lock; rerun mso update"init_update_stateif [ "$rebuild_only" != 1 ]; thenlocal relation ahead+ channel="$(configured_channel)"fetch_main- read -r relation ahead n < <(update_git_relation "$ROOT") || fail "could not compare HEAD with origin/main"+ target="$(update_git_resolve_target "$ROOT" "$channel")" || fail "could not resolve the $channel channel target"+ read -r relation ahead n < <(read_relation "$target") || fail "could not compare HEAD with $target"case "$relation" inexact) ;;- behind) git -C "$ROOT" merge --ff-only origin/main || fail "cannot fast-forward to origin/main" ;;- ahead) fail "local main is ahead of origin/main by $ahead commit(s); run: mso update reconcile" ;;- diverged) fail "local main has diverged from origin/main (ahead $ahead, behind $n); run: mso update reconcile" ;;+ behind)+ # A fast-forward only. A release tag that is not reachable from HEAD means+ # the checkout left that release line; reconciling is a human decision.+ git -C "$ROOT" merge-base --is-ancestor HEAD "$target" \+ || fail "HEAD is not an ancestor of $target; run: mso update reconcile"+ git -C "$ROOT" merge --ff-only "$target" || fail "cannot fast-forward to $target" ;;+ ahead) fail "local main is ahead of $target by $ahead commit(s); run: mso update reconcile" ;;+ diverged) fail "local main has diverged from $target (ahead $ahead, behind $n); run: mso update reconcile" ;;*) fail "unknown Git authority state" ;;esac- read -r relation ahead n < <(update_git_relation "$ROOT") || fail "could not re-check origin/main after fast-forward"- [ "$relation" = exact ] || fail "checkout does not exactly match origin/main after update; refusing deployment"+ read -r relation ahead n < <(read_relation "$target") || fail "could not re-check $target after fast-forward"+ [ "$relation" = exact ] || fail "checkout does not exactly match $target after update; refusing deployment"fihead="$(git -C "$ROOT" rev-parse HEAD)"if [ -e "$DEPLOY_RECEIPT" ] || [ -L "$DEPLOY_RECEIPT" ]; then receipt="$(read_receipt)"; fi@@ -249,9 +295,11 @@ offline_build() {}service_source_matches_runtime() {- local relation ahead behind head running_sha+ local relation ahead behind head running_sha channel target+ channel="$(configured_channel)"fetch_main- read -r relation ahead behind < <(update_git_relation "$ROOT") || fail "could not compare HEAD with origin/main"+ target="$(update_git_resolve_target "$ROOT" "$channel")" || fail "could not resolve the $channel channel target"+ read -r relation ahead behind < <(read_relation "$target") || fail "could not compare HEAD with $target"[ "$relation" = exact ] || return 1head="$(git -C "$ROOT" rev-parse HEAD)"running_sha="$(service_build_sha 2>/dev/null || true)"@@ -301,9 +349,14 @@ wait_for_service_update() {}run_update() {- local rebuild_only="$1" arg=""+ local rebuild_only="$1" arg="" channelrequire_checkout+ channel="$(configured_channel)"[ "$rebuild_only" != 1 ] || arg="--rebuild-only"+ # A manual run is the operator's answer to the unattended pause. Clear the streak+ # BEFORE handing off, because the transient unit replaces this process tree on+ # success — and because the gate's own refusal text tells the operator to do this.+ clear_automation_pauseif service_is_active; thenrequire_service_checkoutif [ "$rebuild_only" != 1 ] && service_source_matches_runtime; then@@ -315,8 +368,11 @@ run_update() {if update_unit_active; thenprintf 'an MSO update is already running.\n'else+ # The channel is the stored enum, never a ref: self-update.sh resolves the+ # actual target and re-validates it at the point of use.systemd-run --user --collect --unit=mso-self-update --property=TimeoutStartSec=3600 \- "--property=WorkingDirectory=$ROOT" "--setenv=MSO_UPDATE_LOG=$LOG" /bin/bash "$ROOT/scripts/mso-service-update" $arg >/dev/null+ "--property=WorkingDirectory=$ROOT" "--setenv=MSO_UPDATE_LOG=$LOG" /bin/bash "$ROOT/scripts/mso-service-update" \+ $arg "--channel=$channel" >/dev/nullfiif [ -t 1 ]; thenwait_for_service_update@@ -330,16 +386,28 @@ run_update() {else offline_build "$rebuild_only"; fi}+# Unattended-update settings, from the SAME authority the Settings toggle and the+# nightly timer use. Skipped (with one neutral line) when this checkout predates the+# automation module, so `mso update status` stays useful in older fixtures/installs.+print_automation() {+ local module="$ROOT/scripts/mso-update-automation.ts"+ if [ -f "$module" ] && command -v bun >/dev/null 2>&1; then+ bun "$module" status --brief 2>/dev/null || printf 'automatic updates state unavailable\n'+ else+ printf 'automatic updates not configured in this checkout\n'+ fi+}+case "${1:-run}" innotice) notice ;;- status|check) print_status ;;+ status|check) print_status; print_automation ;;reconcile) reconcile_checkout ;;log) [ -f "$LOG" ] && tail -n "${2:-80}" "$LOG" || printf 'no update log yet: %s\n' "$LOG" ;;run) case "${2-}" in"" ) run_update 0 ;;--rebuild|--rebuild-only) run_update 1 ;;- *) fail "usage: mso update [--rebuild] | status | reconcile | log" ;;+ *) fail "usage: mso update [--rebuild] | status | reconcile | log | --auto on|off | --channel stable|main" ;;esac ;;--rebuild|--rebuild-only) run_update 1 ;;- *) fail "usage: mso update [--rebuild] | status | reconcile | log" ;;+ *) fail "usage: mso update [--rebuild] | status | reconcile | log | --auto on|off | --channel stable|main" ;;esacdiff --git a/scripts/mso-update-automation.ts b/scripts/mso-update-automation.tsnew file mode 100644index 00000000..1163e642--- /dev/null+++ b/scripts/mso-update-automation.ts@@ -0,0 +1,85 @@+/**+ * `mso update --auto on|off` / `--channel stable|main` / the automation block of+ * `mso update status`, implemented by calling the SAME lib/host/update-automation+ * module the Settings UI calls. The CLI does not re-implement unit installation or+ * the pref file: two implementations of "enabled" is how a host ends up with a+ * timer nobody knows about.+ *+ * bun scripts/mso-update-automation.ts status [--brief]+ * bun scripts/mso-update-automation.ts auto on|off+ * bun scripts/mso-update-automation.ts channel stable|main+ * bun scripts/mso-update-automation.ts resume # clear the 2-failure pause+ */+import path from "node:path";+import { fileURLToPath } from "node:url";+import { applyAutomation, readAutomationState } from "../lib/host/update-automation";+import { clearAutoUpdatePause } from "../lib/prefs/auto-update-state";+import { parseUpdateChannel } from "../lib/prefs/updates";+import { HostError } from "../lib/host/host-error";++const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));+const brief = process.argv.includes("--brief");++const when = (at: number | null): string =>+ at ? new Date(at).toISOString().replace("T", " ").slice(0, 19) + "Z" : "never";++function print(state: Awaited<ReturnType<typeof readAutomationState>>): void {+ const { prefs, timer, active, last, drift } = state;+ if (brief) {+ console.log(`auto: ${active ? "on" : "off"} (channel ${prefs.channel}${prefs.auto && !active ? ", timer missing" : ""})`);+ console.log(`last attempt: ${when(last.lastAttemptAt)} — ${last.lastResult ?? "none"}${last.detail ? ` (${last.detail})` : ""}`);+ return;+ }+ console.log(`automatic updates ${active ? "on" : "off"}${prefs.auto && !active ? " (preference is on, timer is not)" : ""}`);+ console.log(`channel ${prefs.channel}${prefs.channel === "stable" ? " (newest release tag reachable from origin/main)" : " (rolling origin/main)"}`);+ console.log(`nightly timer ${timer.installed ? (timer.enabled ? "installed + enabled" : "installed, not enabled") : "not installed"}`);+ if (timer.nextRun) console.log(`next run ${timer.nextRun}`);+ console.log(`last attempt ${when(last.lastAttemptAt)} — ${last.lastResult ?? "none"}`);+ if (last.detail) console.log(`last detail ${last.detail}`);+ if (last.consecutiveFailures >= 2) console.log("paused after 2 consecutive failed builds; run mso update from a terminal");+ if (drift) console.log(`warning ${drift}`);+}++async function main(): Promise<number> {+ process.chdir(ROOT);+ const [action, value] = process.argv.slice(2);+ try {+ if (!action || action === "status") {+ print(await readAutomationState());+ return 0;+ }+ if (action === "auto") {+ if (value !== "on" && value !== "off") {+ console.error("usage: mso update --auto on|off");+ return 2;+ }+ print(await applyAutomation({ auto: value === "on" }, { root: ROOT }));+ return 0;+ }+ if (action === "resume") {+ // Called by `mso update` right before it applies an update by hand. The gate+ // stops after two consecutive failed builds and tells the operator to run that+ // command; without this the advice could never actually unpause the timer.+ await clearAutoUpdatePause();+ return 0;+ }+ if (action === "channel") {+ const channel = parseUpdateChannel(value);+ if (!channel) {+ console.error("usage: mso update --channel stable|main");+ return 2;+ }+ print(await applyAutomation({ channel }, { root: ROOT }));+ return 0;+ }+ console.error("usage: mso-update-automation.ts status|auto on|off|channel stable|main");+ return 2;+ } catch (cause) {+ // HostError messages are written for an operator ("the nightly update timer is+ // missing…"); anything else is a bug and must not read like advice.+ console.error(`mso update: ${cause instanceof HostError ? cause.message : String(cause).slice(0, 300)}`);+ return 1;+ }+}++process.exit(await main());diff --git a/scripts/mso-update-stable-channel.test.ts b/scripts/mso-update-stable-channel.test.tsnew file mode 100644index 00000000..fe8a707d--- /dev/null+++ b/scripts/mso-update-stable-channel.test.ts@@ -0,0 +1,105 @@+import { execFileSync, spawnSync } from "node:child_process";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterEach, describe, expect, it } from "vitest";++const ROOT = process.cwd();+const UPDATE = path.join(ROOT, "scripts/mso-update");+const LIBS = ["private-state.sh", "update-state.sh", "runtime-exclusion.sh", "update-gateway-runtimes.sh", "update-git-authority.sh", "update-remote-authority.sh"];+const roots: string[] = [];++function git(cwd: string, ...args: string[]) {+ return execFileSync("git", args, { cwd, encoding: "utf8" }).trim();+}++/**+ * Fixture: `main` is one commit PAST the release tag v0.2.0, and origin/main has+ * moved one commit further with no tag. So:+ * stable → HEAD is already the tag's commit → "up to date" (NOT main's tip)+ * main → one commit available+ */+function fixture() {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "mso-update-stable-")); roots.push(root);+ const repo = path.join(root, "repo"), remote = path.join(root, "remote.git"), home = path.join(root, "home");+ fs.mkdirSync(path.join(repo, "scripts/lib"), { recursive: true }); fs.mkdirSync(path.join(repo, "bin")); fs.mkdirSync(home);+ for (const lib of LIBS) fs.copyFileSync(path.join(ROOT, "scripts/lib", lib), path.join(repo, "scripts/lib", lib));+ fs.copyFileSync(path.join(ROOT, "scripts/self-update.sh"), path.join(repo, "scripts/self-update.sh"));+ fs.chmodSync(path.join(repo, "scripts/self-update.sh"), 0o755);+ fs.writeFileSync(path.join(repo, "bin/mso"), '#!/bin/sh\nVERSION="1.0.0"\n', { mode: 0o755 });+ fs.writeFileSync(path.join(repo, "scripts/mso-gateway"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });+ git(repo, "init", "-q", "-b", "main"); git(repo, "config", "user.name", "MSO Test"); git(repo, "config", "user.email", "[email protected]");+ git(repo, "add", "."); git(repo, "commit", "-q", "-m", "release 1.0.0");+ git(repo, "tag", "-a", "v0.2.0", "-m", "release");+ git(root, "init", "--bare", "-q", remote); git(repo, "remote", "add", "origin", remote); git(repo, "push", "-q", "-u", "origin", "main", "--tags");+ // A commit on top of the tag, already in the checkout, plus one more only on origin.+ fs.writeFileSync(path.join(repo, "after-tag.txt"), "1\n"); git(repo, "add", "."); git(repo, "commit", "-q", "-m", "after the tag");+ git(repo, "push", "-q", "origin", "main");+ fs.writeFileSync(path.join(repo, "on-origin.txt"), "2\n"); git(repo, "add", "."); git(repo, "commit", "-q", "-m", "only on origin");+ git(repo, "push", "-q", "origin", "main");+ git(repo, "reset", "-q", "--hard", "HEAD~1");+ fs.mkdirSync(path.join(home, ".mso"), { recursive: true });+ const env: NodeJS.ProcessEnv = { ...process.env, HOME: home, MSO_UPDATE_ROOT: repo,+ MSO_UPDATE_STATE_DIR: path.join(root, "update-state"), MSO_UPDATE_NOTICE_DIR: path.join(root, "notice"),+ PATH: `${path.join(root, "bin")}:${process.env.PATH}` };+ fs.mkdirSync(path.join(root, "bin"));+ fs.writeFileSync(path.join(root, "bin", "systemctl"), "#!/bin/sh\nexit 3\n", { mode: 0o755 });+ return { repo, home, env, tagCommit: git(repo, "rev-parse", "v0.2.0") };+}++function setChannel(home: string, channel: "stable" | "main") {+ fs.writeFileSync(path.join(home, ".mso/prefs.json"), JSON.stringify({ updates: { auto: false, channel } }), { mode: 0o600 });+}++afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); });++describe("mso update channel selection", () => {+ it("keeps the stable channel honest: a checkout past the newest tag is 'up to date', not main's tip", () => {+ const f = fixture();+ setChannel(f.home, "stable");+ const out = execFileSync(UPDATE, ["status"], { env: f.env, encoding: "utf8" });+ expect(out).toContain("channel: stable");+ expect(out).toContain("release v0.2.0");+ // Either exact wording is fine; what matters is that no release commit is offered.+ expect(out).toMatch(/is up to date|source is current/);+ expect(out).not.toContain("update available");+ // The commit that exists only on origin/main must NOT be offered as a release.+ expect(out).not.toContain("only on origin");+ });++ it("offers the rolling commit on the main channel", () => {+ const f = fixture();+ setChannel(f.home, "main");+ const out = execFileSync(UPDATE, ["status"], { env: f.env, encoding: "utf8" });+ expect(out).toContain("channel: main");+ expect(out).toContain("update available");+ expect(out).toContain("only on origin");+ expect(git(f.repo, "rev-parse", "HEAD")).not.toBe(git(f.repo, "rev-parse", "origin/main"));+ });++ it("says out loud when stable has no tag to follow at all", () => {+ const f = fixture();+ setChannel(f.home, "stable");+ for (const tag of ["v0.2.0"]) git(f.repo, "tag", "-d", tag);+ git(f.repo, "push", "-q", "origin", "--delete", "v0.2.0");+ const out = execFileSync(UPDATE, ["status"], { env: f.env, encoding: "utf8" });+ expect(out).toContain("no release tag exists yet");+ });++ it("refuses to fast-forward when HEAD is not an ancestor of the release tag", () => {+ const f = fixture();+ setChannel(f.home, "stable");+ // Rewrite main so the tag commit is no longer reachable from HEAD.+ git(f.repo, "checkout", "-q", "--orphan", "rewritten");+ fs.writeFileSync(path.join(f.repo, "other.txt"), "x\n"); git(f.repo, "add", "."); git(f.repo, "commit", "-q", "-m", "unrelated");+ git(f.repo, "branch", "-M", "main");+ const before = git(f.repo, "rev-parse", "HEAD");+ const out = spawnSync(path.join(f.repo, "scripts/self-update.sh"), ["--channel=stable"], {+ env: { ...f.env, MSO_UPDATE_LOG: path.join(f.repo, "log.txt") }, encoding: "utf8",+ });+ expect(out.status).not.toBe(0);+ expect(fs.existsSync(path.join(f.repo, "log.txt"))).toBe(true);+ expect(fs.readFileSync(path.join(f.repo, "log.txt"), "utf8")).toMatch(/reconcile first|diverged/);+ expect(git(f.repo, "rev-parse", "HEAD")).toBe(before);+ });+});diff --git a/scripts/proxy-body-ceiling.test.ts b/scripts/proxy-body-ceiling.test.tsnew file mode 100644index 00000000..526fe82f--- /dev/null+++ b/scripts/proxy-body-ceiling.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from "vitest";+import { NextRequest } from "next/server";+import { proxy } from "../proxy";++/** The proxy ceiling used to be a flat 1 MiB, so the owner icon upload (8 MiB route+ * cap) could never receive a phone photo: middleware returned 413 before the route+ * ran. It is now per-path from scripts/server-body-policy.mjs, and a positive list+ * means a new sibling route is not silently widened. */+function request(path: string, bytes: number) {+ return new NextRequest(new URL(`https://mso.example.com${path}`), {+ method: "POST",+ headers: { "content-length": String(bytes), host: "mso.example.com" },+ });+}++describe("proxy request body ceiling", () => {+ it("rejects an ordinary route above 1 MiB", async () => {+ expect((await proxy(request("/api/auth/account", 1025 * 1024))).status).toBe(413);+ });++ it("lets the owner icon upload reach its own 8 MiB cap", async () => {+ expect((await proxy(request("/api/auth/account/icon", 2 * 1024 * 1024))).status).not.toBe(413);+ expect((await proxy(request("/api/auth/account/icon", 9 * 1024 * 1024))).status).toBe(413);+ });++ it("does not widen a sibling path", async () => {+ expect((await proxy(request("/api/auth/account/iconx", 2 * 1024 * 1024))).status).toBe(413);+ });++ it("still allows the streaming filesystem upload", async () => {+ expect((await proxy(request("/api/v1/fs/upload", 2 * 1024 * 1024))).status).not.toBe(413);+ });+});diff --git a/scripts/self-update-auto.ts b/scripts/self-update-auto.tsnew file mode 100644index 00000000..ad14bec3--- /dev/null+++ b/scripts/self-update-auto.ts@@ -0,0 +1,130 @@+/**+ * Nightly unattended-update PRE-FLIGHT. Exits non-zero only when the run itself is+ * broken; a refusal prints `SKIP <reason>` and exits 0 so systemd does not record a+ * failed unit for a decision that was correct.+ *+ * The decision is made in lib/host/update-decision.ts, with the same facts the+ * Settings panel collects (lib/host/update-facts.ts) — an unattended run must not+ * judge a checkout differently from the button a human is looking at.+ *+ * bun scripts/self-update-auto.ts # decide, record "skipped" on refusal+ * bun scripts/self-update-auto.ts --record ok|failed [detail]+ *+ * It runs OUTSIDE Next: none of the imported modules carry `server-only`.+ */+import path from "node:path";+import { fileURLToPath } from "node:url";+import { readAutoUpdateState, writeAutoUpdateState, type AutoUpdateResult } from "../lib/prefs/auto-update-state";+import { readPrefs } from "../lib/prefs/store";+import { resolveUpdates } from "../lib/prefs/updates";+import { autoUpdateGate } from "../lib/host/update-decision";+import { collectUpdateFacts } from "../lib/host/update-facts";+import { fetchArgs } from "../lib/host/self-update-channel";+import { automaticUpdateReason, execRunner, isUpdateRunning, readUpdateLog } from "../lib/host/update-host-support";+import { prepareUpdateOrigin, updateGitEnv } from "../lib/host/update-remote-authority";++const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));+const git = (args: readonly string[], timeoutMs?: number) => execRunner("git", args, timeoutMs, updateGitEnv());++function record(result: AutoUpdateResult, detail: string | null): Promise<unknown> {+ return readAutoUpdateState().then((state) =>+ writeAutoUpdateState({+ lastAttemptAt: Date.now(),+ lastResult: result,+ detail,+ // A skip is not a failure and must not make a paused host look worse; a+ // success clears the pause so the next night runs unattended again.+ consecutiveFailures: result === "failed" ? state.consecutiveFailures + 1 : result === "ok" ? 0 : state.consecutiveFailures,+ }),+ );+}++async function decide(): Promise<number> {+ process.chdir(ROOT);+ const prefs = resolveUpdates((await readPrefs()).updates);++ // A refusal is a sentence somebody has to be able to read a day later.+ const refuse = async (reason: string): Promise<number> => {+ await record("skipped", reason);+ console.log(`SKIP ${reason}`);+ return 0;+ };++ // Cheapest possible exit, and the one that must never touch the network: a timer+ // unit that survived `--auto off` still fires every night.+ if (!prefs.auto) {+ console.log("SKIP automatic updates are turned off");+ return 0;+ }++ // The timer unit lives in the user manager, so a transient update from Settings+ // is the only other writer of the checkout. The setsid fallback is a no-systemd+ // path where this timer does not exist at all.+ const running = await isUpdateRunning(execRunner, async () => false);+ const facts = await collectUpdateFacts({+ git: (args) => git(args),+ channel: prefs.channel,+ fetch: true,+ fetchRemote: async () => {+ const ready = await prepareUpdateOrigin((args) => git(args, 45_000));+ if (!ready) return { code: 1 };+ return git(fetchArgs(prefs.channel), 45_000);+ },+ });+ if (!facts.insideWorkTree) return refuse("this deployment is not a git checkout, so there is nothing to pull");++ const reason = await automaticUpdateReason(execRunner);+ const last = await readAutoUpdateState();+ const gate = autoUpdateGate({+ auto: prefs.auto,+ supported: reason === null,+ reason,+ dirty: facts.dirty,+ running,+ ahead: facts.ahead,+ behind: facts.behind,+ // Deliberately NOT "build is pending": the panel's version of that state compares+ // the running process's baked SHA, which only Next knows. An unattended run exists+ // to pick up new commits; restarting a host every night for a rebuild nobody asked+ // for is not an update, so it waits for the panel or a human.+ pendingBuild: false,+ consecutiveFailures: last.consecutiveFailures,+ changedPaths: facts.changedPaths,+ target: facts.targetLabel,+ targetFallback: facts.targetFallback,+ });++ if (!gate.run) return refuse(gate.reason);++ // The wrapper reads these two machine lines: a decision made here must apply the+ // commit it judged, not whatever `main` moved to in the meantime.+ await writeAutoUpdateState({ channel: prefs.channel });+ console.log(`MSO_AUTO_CHANNEL=${prefs.channel}`);+ console.log(`MSO_AUTO_TARGET_SHA=${facts.targetSha}`);+ if (facts.targetSha === "") return refuse("could not read the resolved update target commit");+ console.log(`RUN ${prefs.channel} ${facts.targetLabel} behind=${facts.behind}`);+ return 0;+}++async function main(): Promise<number> {+ if (process.argv[2] === "--record") {+ const result = process.argv[3];+ if (result !== "ok" && result !== "failed" && result !== "skipped") {+ console.error("usage: self-update-auto.ts --record ok|failed|skipped [detail]");+ return 2;+ }+ if (result === "failed") {+ // The log is truncated on every attempt, so the reason is captured here or not+ // at all. Bounded: it is rendered in a settings row.+ const log = await readUpdateLog();+ const failed = log.split("\n").filter((line) => line.includes("FAILED:")).pop();+ await record("failed", (process.argv[4] || failed || "the unattended build failed; inspect the update log").slice(0, 300));+ } else {+ await record(result, process.argv[4] ?? null);+ }+ return 0;+ }+ return decide();+}++process.exit(await main());diff --git a/scripts/self-update.sh b/scripts/self-update.shindex a13ca7b8..9ebad106 100755--- a/scripts/self-update.sh+++ b/scripts/self-update.sh@@ -37,17 +37,26 @@ die() { printf '\n[%s] FAILED: %s\n' "$(date -Is)" "$*"; printf 'the running MSREBUILD_ONLY=0SHIP_FINALIZE=0-case "${1:-}" in- "") ;;- --rebuild-only) REBUILD_ONLY=1 ;;- --ship-finalize) REBUILD_ONLY=1; SHIP_FINALIZE=1 ;;- *) die "unknown mode: ${1:-}" ;;-esac+CHANNEL=main+while [ $# -gt 0 ]; do+ case "$1" in+ --rebuild-only) REBUILD_ONLY=1 ;;+ --ship-finalize) REBUILD_ONLY=1; SHIP_FINALIZE=1 ;;+ # The ONLY channel input: a two-word enum. The ref is resolved below from the+ # repository itself, so no caller can point an unattended restart elsewhere.+ --channel=stable) CHANNEL=stable ;;+ --channel=main) CHANNEL=main ;;+ *) die "unknown mode: ${1:-}" ;;+ esac+ shift+done-step "self-update starting (rebuild-only=$REBUILD_ONLY, ship-finalize=$SHIP_FINALIZE)"+step "self-update starting (rebuild-only=$REBUILD_ONLY, ship-finalize=$SHIP_FINALIZE, channel=$CHANNEL)"HEAD_SHA="$(git rev-parse HEAD 2>/dev/null || true)"[ -n "$HEAD_SHA" ] || die "could not read checkout HEAD"CURRENT_BRANCH="$(git branch --show-current 2>/dev/null || true)"+# Both channels still require the branch checkout: a tag checkout is not requested,+# and a detached HEAD cannot be fast-forwarded by the next release.[ "$CURRENT_BRANCH" = main ] || die "updates require checkout to be on main (current: ${CURRENT_BRANCH:-detached HEAD})"printf 'at %s\n' "${HEAD_SHA:0:7}"@@ -66,21 +75,53 @@ if [ "$SHIP_FINALIZE" -eq 1 ]; thenfiif [ "$REBUILD_ONLY" -eq 0 ]; then- step "fetching origin/main"- update_git_fetch_origin "$ROOT" main || die "could not reach the remote"- step "verifying remote authority / fast-forwarding"- read -r RELATION AHEAD_COUNT BEHIND_COUNT < <(update_git_relation "$ROOT") \- || die "could not compare checkout with origin/main"+ # Fetch BEFORE resolving: a release tag pushed since the last run is exactly what+ # the stable channel is supposed to notice. `--tags` also fills the tag list for a+ # later channel switch without a second network round trip.+ step "fetching origin/main and release tags"+ update_git_fetch_origin "$ROOT" main --tags || die "could not reach the remote"++ step "resolving $CHANNEL channel target"+ TARGET="$(update_git_resolve_target "$ROOT" "$CHANNEL")" \+ || die "could not resolve the $CHANNEL channel target"+ # Re-validate at the use site. The ref came from this repository, but it becomes+ # argv on the next line, so the allowlist is applied exactly where it is consumed.+ case "$TARGET" in+ origin/main) ;;+ *) printf '%s\n' "$TARGET" | grep -Eq '^v?[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,4}$' \+ || die "resolved update target is not an allowed ref: $TARGET" ;;+ esac+ # The unattended path pins the commit its pre-flight inspected, because that is+ # the only run where nobody read the incoming diff before it was applied.+ if [ -n "${MSO_AUTO_TARGET_SHA:-}" ]; then+ [[ "$MSO_AUTO_TARGET_SHA" =~ ^[0-9a-f]{40}$ ]] \+ || die "MSO_AUTO_TARGET_SHA must be a full 40-character commit sha"+ [ "$(git rev-parse "$TARGET^{commit}" 2>/dev/null || true)" = "$MSO_AUTO_TARGET_SHA" ] \+ || die "the $CHANNEL target moved after the pre-flight decision; refusing an unattended build of an unreviewed commit"+ fi++ step "verifying remote authority / fast-forwarding to $TARGET"+ read -r RELATION AHEAD_COUNT BEHIND_COUNT < <(update_git_relation_to "$ROOT" "$TARGET") \+ || die "could not compare checkout with $TARGET"case "$RELATION" inexact) ;;- behind) git merge --ff-only origin/main || die "cannot fast-forward — the checkout has diverged from origin/main" ;;- ahead) die "local main is ahead of origin/main by $AHEAD_COUNT commit(s); refusing to deploy unpushed code" ;;- diverged) die "local main has diverged from origin/main (ahead $AHEAD_COUNT, behind $BEHIND_COUNT)" ;;+ ahead) die "local main is ahead of $TARGET by $AHEAD_COUNT commit(s); refusing to deploy unpushed code" ;;+ diverged)+ # A tag that is not an ancestor of HEAD is a release line the checkout left+ # behind. Deploying it would mean force-moving history, which an unattended+ # run must never do.+ git merge-base --is-ancestor HEAD "$TARGET" \+ || die "HEAD is not an ancestor of $TARGET; reconcile first (mso update reconcile) instead of force-checking out a release"+ die "local main has diverged from $TARGET (ahead $AHEAD_COUNT, behind $BEHIND_COUNT); reconcile first" ;;+ behind)+ git merge-base --is-ancestor HEAD "$TARGET" \+ || die "HEAD is not an ancestor of $TARGET; reconcile first (mso update reconcile) instead of force-checking out a release"+ git merge --ff-only "$TARGET" || die "cannot fast-forward to $TARGET" ;;*) die "unknown Git authority state" ;;esac- read -r RELATION AHEAD_COUNT BEHIND_COUNT < <(update_git_relation "$ROOT") \- || die "could not re-check origin/main after fast-forward"- [ "$RELATION" = exact ] || die "checkout does not exactly match origin/main after update"+ read -r RELATION AHEAD_COUNT BEHIND_COUNT < <(update_git_relation_to "$ROOT" "$TARGET") \+ || die "could not re-check $TARGET after fast-forward"+ [ "$RELATION" = exact ] || die "checkout does not exactly match $TARGET after update"git log -1 --format='now at %h — %s'step "installing dependencies"diff --git a/scripts/server-body-policy.mjs b/scripts/server-body-policy.mjsindex a7be3e57..8120a0ef 100644--- a/scripts/server-body-policy.mjs+++ b/scripts/server-body-policy.mjs@@ -1,5 +1,33 @@+// Per-path request body ceilings for the public HTTP server and the Next proxy.+//+// Most cockpit traffic is JSON measured in kilobytes, so the default stays at+// 1 MiB: a public surface should not buffer more than it needs. Two routes are+// deliberately different and must be named here, not guessed from a prefix:+//+// /api/v1/fs/upload streams to disk, 200 MiB, bypasses proxy cloning+// /api/auth/account/icon owner-only image upload, 8 MiB, read with a byte+// counter inside the route+//+// Anything else gets the default. A new large-body route has to be added+// explicitly, which is the point of a positive list.export const PROXY_BODY_LIMIT = 1024 * 1024;+export const FS_UPLOAD_BODY_LIMIT = 200 * 1024 * 1024;+export const ACCOUNT_ICON_BODY_LIMIT = 8 * 1024 * 1024;++const LIMITS = new Map([+ ["/api/v1/fs/upload", FS_UPLOAD_BODY_LIMIT],+ ["/api/auth/account/icon", ACCOUNT_ICON_BODY_LIMIT],+]);+export function requestBodyLimit(url) {- try { return new URL(url, "http://localhost").pathname === "/api/v1/fs/upload" ? 200 * 1024 * 1024 : PROXY_BODY_LIMIT; }- catch { return PROXY_BODY_LIMIT; }+ try {+ return LIMITS.get(new URL(url, "http://localhost").pathname) ?? PROXY_BODY_LIMIT;+ } catch {+ return PROXY_BODY_LIMIT;+ }}++/** Routes that bypass Next's middleware body clone. They read their own bytes and+ * enforce their own cap, so cloning the body twice is wasted memory. Each one must+ * re-check the managed-app host and the same-origin rule itself. */+export const BODY_CLONE_BYPASS = ["/api/v1/fs/upload", "/api/auth/account/icon"];diff --git a/scripts/server-body-policy.test.ts b/scripts/server-body-policy.test.tsnew file mode 100644index 00000000..8072e86a--- /dev/null+++ b/scripts/server-body-policy.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from "vitest";+import {+ ACCOUNT_ICON_BODY_LIMIT,+ BODY_CLONE_BYPASS,+ FS_UPLOAD_BODY_LIMIT,+ PROXY_BODY_LIMIT,+ requestBodyLimit,+} from "../scripts/server-body-policy.mjs";++describe("request body policy", () => {+ it("keeps the default ceiling small", () => {+ expect(requestBodyLimit("/api/auth/account")).toBe(PROXY_BODY_LIMIT);+ expect(requestBodyLimit("/api/v1/exec/run")).toBe(PROXY_BODY_LIMIT);+ expect(requestBodyLimit("/")).toBe(PROXY_BODY_LIMIT);+ });++ it("names the two large-body routes explicitly", () => {+ expect(requestBodyLimit("/api/v1/fs/upload")).toBe(FS_UPLOAD_BODY_LIMIT);+ expect(requestBodyLimit("/api/auth/account/icon")).toBe(ACCOUNT_ICON_BODY_LIMIT);+ expect(ACCOUNT_ICON_BODY_LIMIT).toBe(8 * 1024 * 1024);+ });++ it("does not widen a route by prefix or by query string", () => {+ // A positive list, not a prefix match: a new sibling is NOT silently allowed.+ expect(requestBodyLimit("/api/auth/account/icon/extra")).toBe(PROXY_BODY_LIMIT);+ expect(requestBodyLimit("/api/auth/account")).toBe(PROXY_BODY_LIMIT);+ expect(requestBodyLimit("/api/v1/fs/upload/anything")).toBe(PROXY_BODY_LIMIT);+ expect(requestBodyLimit("/api/auth/account/icon?size=ico")).toBe(ACCOUNT_ICON_BODY_LIMIT);+ expect(requestBodyLimit("/api/auth/account/iconx")).toBe(PROXY_BODY_LIMIT);+ });++ it("falls back to the default for an unparseable url", () => {+ expect(requestBodyLimit("http://[::")).toBe(PROXY_BODY_LIMIT);+ });++ it("declares the clone bypass for exactly the routes that read their own bytes", () => {+ expect([...BODY_CLONE_BYPASS].sort()).toEqual(["/api/auth/account/icon", "/api/v1/fs/upload"]);+ });+});++describe("matcher synchronization", () => {+ it("keeps the proxy matcher and the bypass list in sync", async () => {+ // The matcher is a literal string (Next reads it at compile time), so the only+ // way to keep it honest is to parse it back out of the source.+ const { readFileSync } = await import("node:fs");+ const source = readFileSync(new URL("../proxy.ts", import.meta.url), "utf8");+ const match = /matcher:\s*\[("(?:[^"\\]|\\.)*")\]/.exec(source);+ expect(match?.[1]).toBeTruthy();+ const pattern = new RegExp(`^${JSON.parse(match![1]!)}$`);+ for (const path of BODY_CLONE_BYPASS) expect(pattern.test(path)).toBe(false);+ for (const path of ["/api/auth/account", "/api/auth/account/iconx", "/settings", "/api/v1/exec/run"]) {+ expect(pattern.test(path)).toBe(true);+ }+ });+});diff --git a/scripts/test-support/integrations-sc-harness.sh b/scripts/test-support/integrations-sc-harness.shindex 9fc4f1ae..782e9659 100755--- a/scripts/test-support/integrations-sc-harness.sh+++ b/scripts/test-support/integrations-sc-harness.sh@@ -21,6 +21,10 @@ fiexit 8SCchmod +x "$FAKE";ln -s "$FAKE" "$LINK"+# `chmod +x` yields 0775 under a group-writable umask (0002 on some hosts), and+# sc-installation.mjs rightly refuses a group-writable binary. The fixture must be+# an owner-private install like a real one, not a reflection of the invoking shell.+chmod 755 "$FAKE"export MSO_SC_BIN="$LINK" FAKE_SC_SOURCE="$SRC"die(){ printf '%s\n' "$*" >&2;exit 2; }tty_ok(){ return 1; }diff --git a/vitest.config.mts b/vitest.config.mtsindex 214196c9..e8cb73ae 100644--- a/vitest.config.mts+++ b/vitest.config.mts@@ -19,6 +19,20 @@ export default defineConfig({test: {// Shell/systemd lifecycle fixtures can exceed Vitest's 5s default under the full parallel gate.testTimeout: 15_000,+ // Cache transformed modules INSIDE THIS CHECKOUT, not in the shared+ // `node_modules/.vitest-cache`.+ //+ // Agent worktrees symlink `node_modules` to this canonical checkout (so every+ // worktree reuses one install). Vitest's default cache path resolves through that+ // symlink, so two gates running at once — a worktree's pre-push and this repo's —+ // share one cache directory and race on rmdir:+ //+ // Error: ENOTEMPTY: directory not empty, rmdir '.../node_modules/.vitest-cache'+ //+ // That failed a push three times with a message that looked like a code problem.+ // Keying the cache by checkout root makes concurrent gates independent; the cache+ // is still reused within one checkout.+ fsModuleCachePath: path.join(root, "node_modules", ".vitest-cache", path.basename(root)),// `zz-*` is the agreed scratch prefix: agent/debug harnesses that must never// run in CI, never be committed, and never break a push. Also excluded from// tsconfig and gitignored — three places, because a leftover has broken this