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(assistant): show explicit run state and scoped approvals
Rahman41d08713d842
diff --git a/frontend/slices/appshell/components/alfa-approval-grants.tsx b/frontend/slices/appshell/components/alfa-approval-grants.tsxnew file mode 100644index 00000000..e37e128f--- /dev/null+++ b/frontend/slices/appshell/components/alfa-approval-grants.tsx@@ -0,0 +1,17 @@+"use client";+import { Button } from "@/components/ui/button";+import { resetAlfaApprovalPolicy, revokeAlfaApproval, useAlfaApprovalGrants } from "../lib/alfa-approval-policy";++export function AlfaApprovalGrants() {+ const grants = useAlfaApprovalGrants();+ if (!grants.length) return null;+ return <details className="border-b border-border px-3 py-2 text-xs">+ <summary className="cursor-pointer py-1 [@media(pointer:coarse)]:min-h-11">Always approve: {grants.length} exact calls</summary>+ <p className="py-1 text-muted-foreground">Applies to identical arguments in the displayed conversation, project and mode. Cleared on a new or loaded chat.</p>+ {grants.map((grant) => <div key={grant.key} className="flex items-center gap-2 py-1">+ <span className="min-w-0 flex-1 break-words">{grant.tool} · {grant.scope}</span>+ <Button size="sm" variant="outline" onClick={() => revokeAlfaApproval(grant.key)} className="[@media(pointer:coarse)]:min-h-11">Revoke</Button>+ </div>)}+ <Button size="sm" variant="secondary" onClick={resetAlfaApprovalPolicy} className="[@media(pointer:coarse)]:min-h-11">Reset all approvals</Button>+ </details>;+}diff --git a/frontend/slices/appshell/components/alfa-run-progress.tsx b/frontend/slices/appshell/components/alfa-run-progress.tsxnew file mode 100644index 00000000..43e6ddab--- /dev/null+++ b/frontend/slices/appshell/components/alfa-run-progress.tsx@@ -0,0 +1,57 @@+"use client";++import { useEffect, useState } from "react";+import { Activity, Square } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet";+import { useAlfaRunState } from "../lib/alfa-run-state";+import { stopAlfa, useAlfaBusy } from "../lib/alfa";++const LABELS = { working: "Working", waiting: "Waiting for approval", done: "Done", failed: "Failed", stopped: "Stopped" };+export function AlfaRunProgress() {+ const run = useAlfaRunState();+ const busy = useAlfaBusy();+ const [now, setNow] = useState(() => Date.now());+ const active = busy && run?.status === "working";+ useEffect(() => {+ if (!active) return;+ const timer = setInterval(() => setNow(Date.now()), 1000);+ return () => clearInterval(timer);+ }, [active]);+ if (!run) return null;+ // busy is the actual single-flight lock. Never infer active work from persisted cards.+ const status = run.status === "working" && !busy ? "stopped" : run.status;+ const seconds = Math.max(0, Math.floor(((run.finishedAt ?? now) - run.startedAt) / 1000));+ return (+ <section aria-label="Assistant run" className="shrink-0 border-b border-border bg-muted/40 px-3 py-2 text-xs">+ <div className="flex flex-wrap items-center gap-2">+ <Activity aria-hidden className={active ? "size-3.5 motion-safe:animate-pulse text-primary" : "size-3.5 text-muted-foreground"} />+ <span role="status" className="font-medium">{LABELS[status]}</span>+ <span aria-label="Elapsed time" className="tabular-nums text-muted-foreground">{seconds}s elapsed</span>+ <div className="ml-auto flex items-center gap-1">+ <Sheet>+ <SheetTrigger asChild><Button variant="ghost" size="sm" className="[@media(pointer:coarse)]:min-h-11">Details</Button></SheetTrigger>+ <SheetContent className="w-full sm:max-w-md">+ <SheetHeader><SheetTitle>Run details</SheetTitle>+ <SheetDescription>{LABELS[status]} · {seconds}s elapsed. Activity contains tool status only.</SheetDescription>+ </SheetHeader>+ <ol className="overflow-y-auto px-4 pb-4">+ {run.activities.map((row) => <li key={row.id} className="border-b border-border py-2">+ <p className="break-words font-mono text-xs">{row.label}</p>+ <p className="text-xs text-muted-foreground">{row.state}</p>+ </li>)}+ </ol>+ </SheetContent>+ </Sheet>+ {busy && status !== "stopped" ? <Button variant="secondary" size="sm" onClick={stopAlfa} className="[@media(pointer:coarse)]:min-h-11"><Square className="size-3" />Stop</Button> : null}+ </div>+ </div>+ {status === "waiting" ? <p className="mt-1 break-words text-warning">Approval needed: {run.operation}. Processing is paused.</p> : null}+ {active ? <p className="mt-1 text-muted-foreground">{run.operation} · Last runner event {Math.max(0, Math.floor((now - run.heartbeatAt) / 1000))}s ago</p> : null}+ {status === "stopped" && busy ? <p className="mt-1 text-muted-foreground">Stop requested. An in-flight host operation may finish before the run closes.</p> : null}+ <ol aria-label="Recent activity" className="mt-1 space-y-0.5">+ {run.activities.slice(0, 4).map((row) => <li key={row.id} className="truncate text-muted-foreground">{row.label} · {row.state}</li>)}+ </ol>+ </section>+ );+}diff --git a/frontend/slices/appshell/components/alfa-thread.tsx b/frontend/slices/appshell/components/alfa-thread.tsxindex ccb70ad2..b0b290bf 100644--- a/frontend/slices/appshell/components/alfa-thread.tsx+++ b/frontend/slices/appshell/components/alfa-thread.tsx@@ -8,6 +8,8 @@ import { useAlfaBusy, useAlfaMessages, sendToAlfa, alfaReady, stopAlfa, type Alfimport { useApps } from "../lib/registry";import { openWindow } from "../lib/store";import { ChatComposer } from "./chat-composer";+import { AlfaRunProgress } from "./alfa-run-progress";+import { AlfaApprovalGrants } from "./alfa-approval-grants";import { ApprovalCard } from "./approval-card";import type { ToolCard } from "./message-bubble";import { resolveAlfaApproval, useAlfaApprovalCount } from "../lib/alfa-approvals";@@ -43,7 +45,7 @@ export function AlfaThread({ ctx, placeholder }: { ctx: AlfaContext; placeholderasync function submit(text: string) {const body = text.trim();if (!body || busy) return;- if (await sendToAlfa(body, ctx)) return;+ if (alfaReady()) { await sendToAlfa(body, ctx); return; }openWindow("assistant", "Alfa");// The panel registers on mount; poll briefly rather than wiring a bespoke// ready-event for a path that resolves in one or two frames.@@ -53,6 +55,8 @@ export function AlfaThread({ ctx, placeholder }: { ctx: AlfaContext; placeholderreturn (<div className="flex h-full min-h-0 flex-col">+ <AlfaRunProgress />+ <AlfaApprovalGrants />{project || approvals ? (<buttontype="button"diff --git a/frontend/slices/appshell/components/approval-card.tsx b/frontend/slices/appshell/components/approval-card.tsxindex 0d839ca7..e71deaae 100644--- a/frontend/slices/appshell/components/approval-card.tsx+++ b/frontend/slices/appshell/components/approval-card.tsx@@ -6,9 +6,7 @@ import { Button } from "@/components/ui/button";import { Switch } from "@/components/ui/switch";import { cn } from "@/lib/utils";import type { ChatMessage } from "./message-bubble";--// "Allow this exact call again" — mirrors REMEMBERABLE in use-host-commands.-const REMEMBERABLE = new Set(["fs.write", "fs.mkdir", "fs.move"]);+import { canRememberAlfaTool } from "../lib/alfa-approval-policy";// Renders a role:"tool" message — one host tool call. A pending MUTATE call shows// the full args + Approve/Deny (the agent loop is parked awaiting the click);@@ -64,18 +62,19 @@ export function ApprovalCard({)}{pending && (- <div className="mt-2 flex items-center gap-2">+ <div className="mt-2 flex flex-wrap items-center gap-2"><Button type="button" size="sm" className="h-7 px-2.5 text-xs [@media(pointer:coarse)]:min-h-[44px]" onClick={() => onResolve(message.id, true, remember)}>Approve</Button><Button type="button" size="sm" variant="outline" className="h-7 px-2.5 text-xs [@media(pointer:coarse)]:min-h-[44px]" onClick={() => onResolve(message.id, false, false)}>Deny</Button>- {REMEMBERABLE.has(t.name) && (- <label className="ml-auto flex items-center gap-1.5 text-[11px] text-muted-foreground">- <Switch checked={remember} onCheckedChange={setRemember} /> allow again+ {!t.danger && t.approvalScope && canRememberAlfaTool(t.name, t.input) && (+ <label className="flex items-center gap-1.5 text-[11px] text-muted-foreground [@media(pointer:coarse)]:min-h-11">+ <Switch checked={remember} onCheckedChange={setRemember} /> Always approve this exact call</label>)}+ {t.approvalScope ? <p className="w-full break-words text-[11px] text-muted-foreground">Scope: {t.name} + identical arguments · {t.approvalScope}</p> : null}</div>)}</div>diff --git a/frontend/slices/appshell/components/chat-composer.tsx b/frontend/slices/appshell/components/chat-composer.tsxindex c7e45e5b..765adcfe 100644--- a/frontend/slices/appshell/components/chat-composer.tsx+++ b/frontend/slices/appshell/components/chat-composer.tsx@@ -6,6 +6,7 @@ import { Button } from "@/components/ui/button";import { Textarea } from "@/components/ui/textarea";import { cn } from "@/lib/utils";import { useActiveShell } from "../registry/shells";+import { useAlfaRunState } from "../lib/alfa-run-state";import { alfaSources, subscribeAlfaSources, alfaSourcesVersion } from "../lib/alfa-sources";import { mentionAt, applyMention, rankMentions, type MentionItem } from "../lib/mentions";@@ -39,6 +40,7 @@ export function ChatComposer({const ref = useRef<HTMLTextAreaElement>(null);const canSend = value.trim().length > 0 && !streaming;const ios = useActiveShell().id === "ios";+ const run = useAlfaRunState();// Re-render when a source's data lands asynchronously: the consumer module is// imported on this component's first render, and its skills fetch starts on the// first `/`. `items` below is computed during render, so without this the new@@ -180,18 +182,18 @@ export function ChatComposer({onClick={(e) => setCaret(e.currentTarget.selectionStart ?? 0)}onKeyDown={onKeyDown}rows={1}- placeholder={streaming ? "Alfa is replying…" : (placeholder ?? "Message Alfa… @agent /skill")}+ placeholder={streaming ? (run?.status === "waiting" ? "Waiting for your approval…" : run?.status === "stopped" ? "Stopping the run…" : "Alfa is working…") : (placeholder ?? "Message Alfa… @agent /skill")}className={cn("max-h-32 min-h-9 flex-1 resize-none scrollbar-thin",ios && "min-h-8 border-0 bg-transparent px-0 py-1.5 shadow-none focus-visible:ring-0",)}/>{streaming ? (- <Button type="button" size="icon" variant="secondary" onClick={onStop} aria-label="Stop generating" className={cn("flex-none", ios ? "size-[30px] rounded-full" : "size-9")}>+ <Button type="button" size="icon" variant="secondary" onClick={onStop} aria-label="Stop generating" className={cn("flex-none [@media(pointer:coarse)]:min-h-11 [@media(pointer:coarse)]:min-w-11", ios ? "size-[30px] rounded-full" : "size-9")}><Square className={ios ? "size-3 fill-current" : "size-4 fill-current"} /></Button>) : (- <Button type="button" size="icon" onClick={submit} disabled={!canSend} aria-label="Send message" className={cn("flex-none", ios ? "size-[30px] rounded-full" : "size-9")}>+ <Button type="button" size="icon" onClick={submit} disabled={!canSend} aria-label="Send message" className={cn("flex-none [@media(pointer:coarse)]:min-h-11 [@media(pointer:coarse)]:min-w-11", ios ? "size-[30px] rounded-full" : "size-9")}>{ios ? <ArrowUp className="size-4" /> : <Send className="size-4" />}</Button>)}diff --git a/frontend/slices/appshell/components/message-bubble.tsx b/frontend/slices/appshell/components/message-bubble.tsxindex b13d7eab..3c04f4c5 100644--- a/frontend/slices/appshell/components/message-bubble.tsx+++ b/frontend/slices/appshell/components/message-bubble.tsx@@ -17,6 +17,7 @@ export type ToolCard = {status: ToolStatus;result?: string;danger?: string;+ approvalScope?: string;};export type ChatMessage = {diff --git a/frontend/slices/appshell/index.ts b/frontend/slices/appshell/index.tsindex 8e325f70..49f98204 100644--- a/frontend/slices/appshell/index.ts+++ b/frontend/slices/appshell/index.ts@@ -1,8 +1,5 @@// Public barrel — other slices/app layer import ONLY from here.export { OsDesktop } from "./components/desktop";-// Bundled single-pane cockpit shell (self-registers as ShellId "dashboard" on-// import — matching rr). Brand comes from <BrandProvider> (useBrand); the file-// is brand-free. macOS/Windows/iOS/Android register from the framework itself.export { AppIcon } from "./components/app-icon";export { QuicklinkIcon } from "./components/quicklink-icon";// Generic app mounter (lazy-loads an app by id + payload). Used by windows AND@@ -126,6 +123,10 @@ export { AlfaThread } from "./components/alfa-thread";export { ChatComposer } from "./components/chat-composer";export * from "./lib/mentions";export * from "./lib/alfa";+export * from "./lib/alfa-run-state";+export * from "./lib/alfa-approval-policy";+export { AlfaApprovalGrants } from "./components/alfa-approval-grants";+export { AlfaRunProgress } from "./components/alfa-run-progress";export * from "./lib/alfa-sources";export * from "./lib/alfa-approvals";export * from "./lib/alfa-work-context";@@ -133,9 +134,6 @@ export { MessageBubble } from "./components/message-bubble";export type { ChatMessage, ToolCard } from "./components/message-bubble";export { ApprovalCard } from "./components/approval-card";-// ── Shell registry — the pluggable multi-shell seam (macOS/Windows/iOS/…) ────-// Per-surface preference: the user picks a desktop shell AND a mobile shell; the-// active one is resolved by form factor.export {registerShell,shellList,diff --git a/frontend/slices/appshell/lib/alfa-approval-policy.test.ts b/frontend/slices/appshell/lib/alfa-approval-policy.test.tsnew file mode 100644index 00000000..dead7633--- /dev/null+++ b/frontend/slices/appshell/lib/alfa-approval-policy.test.ts@@ -0,0 +1,30 @@+import { beforeEach, expect, it } from "vitest";+import { alfaApprovalKey, alfaApprovalScope, canRememberAlfaTool, hasAlfaApproval, newAlfaApprovalSession, rememberAlfaApproval, resetAlfaApprovalPolicy, revokeAlfaApproval } from "./alfa-approval-policy";+beforeEach(resetAlfaApprovalPolicy);+it("requires exact nested arguments, tool, project and mode", () => {+ const scope = alfaApprovalScope("/project", "live");+ const args = { path: "/project/note.txt", content: "hello", metadata: { a: 1 } };+ rememberAlfaApproval("fs.write", args, scope);+ expect(hasAlfaApproval("fs.write", { metadata: { a: 1 }, content: "hello", path: args.path }, scope)).toBe(true);+ for (const input of [{ ...args, content: "changed" }, { ...args, metadata: { a: 2 } }])+ expect(hasAlfaApproval("fs.write", input, scope)).toBe(false);+ expect(hasAlfaApproval("fs.mkdir", args, scope)).toBe(false);+ expect(hasAlfaApproval("fs.write", args, alfaApprovalScope("/other", "live"))).toBe(false);+ expect(hasAlfaApproval("fs.write", args, alfaApprovalScope("/project", "mock"))).toBe(false);+});+it("refuses destructive, credential, system and traversal operations", () => {+ for (const tool of ["exec.run", "fs.delete", "fs.move", "config.set", "unknown"])+ expect(canRememberAlfaTool(tool, { path: "/project/note.txt" })).toBe(false);+ for (const path of ["/etc/file", "/project/../secret", "/project/.env.local", "~/.ssh/config", "/project/credentials.json", "/project/.mso/state"])+ expect(canRememberAlfaTool("fs.write", { path })).toBe(false);+});+it("supports revoke/reset and prevents grants crossing loaded/new conversations", () => {+ const scope = alfaApprovalScope("/project", "live"), args = { path: "/project/folder" };+ rememberAlfaApproval("fs.mkdir", args, scope);+ revokeAlfaApproval(alfaApprovalKey("fs.mkdir", args, scope));+ expect(hasAlfaApproval("fs.mkdir", args, scope)).toBe(false);+ rememberAlfaApproval("fs.mkdir", args, scope);+ newAlfaApprovalSession();+ expect(hasAlfaApproval("fs.mkdir", args, scope)).toBe(false);+ expect(alfaApprovalScope("/project", "live")).not.toBe(scope);+});diff --git a/frontend/slices/appshell/lib/alfa-approval-policy.ts b/frontend/slices/appshell/lib/alfa-approval-policy.tsnew file mode 100644index 00000000..7432c943--- /dev/null+++ b/frontend/slices/appshell/lib/alfa-approval-policy.ts@@ -0,0 +1,53 @@+"use client";++import { useSyncExternalStore } from "react";++type Grant = { key: string; tool: string; scope: string };+let grants: Grant[] = [];+let conversation = 1;+const subscribers = new Set<() => void>();+const subscribe = (fn: () => void) => { subscribers.add(fn); return () => subscribers.delete(fn); };+const emit = () => subscribers.forEach((fn) => fn());+const getGrants = () => grants;+const EMPTY: Grant[] = [];+export function useAlfaApprovalGrants() { return useSyncExternalStore(subscribe, getGrants, () => EMPTY); }++export function alfaApprovalScope(project: string | undefined, mode: string): string {+ return `Conversation ${conversation} · ${project || "no project"} · ${mode}`;+}++function canonical(value: unknown): string {+ if (Array.isArray(value)) return "[" + value.map(canonical).join(",") + "]";+ if (value && typeof value === "object") return "{" + Object.entries(value).sort(([a], [b]) => a.localeCompare(b))+ .map(([key, item]) => JSON.stringify(key) + ":" + canonical(item)).join(",") + "}";+ return JSON.stringify(value) ?? "null";+}+export function alfaApprovalKey(tool: string, input: Record<string, unknown>, scope: string): string {+ return canonical([scope, tool, input]);+}++/** Only exact reviewed file calls can be remembered. Host jail/auth remain mandatory. */+export function canRememberAlfaTool(tool: string, input: Record<string, unknown>): boolean {+ if (!["fs.write", "fs.mkdir", "fs.copy"].includes(tool)) return false;+ if (canonical(input).length > 32_768) return false;+ const paths = tool === "fs.copy" ? [input.from, input.to] : [input.path];+ return paths.every((path) => typeof path === "string" && path.length > 0+ && !/(^|[/\\])(?:\.\.?|\.env[^/\\]*|\.ssh|\.gnupg|\.mso|\.aws|\.config|etc|proc|sys|dev|boot)([/\\]|$)/i.test(path)+ && !/(credential|secret|token|password|keychain|\.pem$|\.key$)/i.test(path));+}++export function rememberAlfaApproval(tool: string, input: Record<string, unknown>, scope: string): void {+ if (!canRememberAlfaTool(tool, input)) return;+ const key = alfaApprovalKey(tool, input, scope);+ if (grants.some((grant) => grant.key === key)) return;+ grants = [...grants, { key, tool, scope }].slice(-64);+ emit();+}+export function hasAlfaApproval(tool: string, input: Record<string, unknown>, scope: string): boolean {+ return canRememberAlfaTool(tool, input) && grants.some((grant) => grant.key === alfaApprovalKey(tool, input, scope));+}+export function revokeAlfaApproval(key: string): void {+ grants = grants.filter((grant) => grant.key !== key); emit();+}+export function resetAlfaApprovalPolicy(): void { grants = []; emit(); }+export function newAlfaApprovalSession(): void { conversation++; resetAlfaApprovalPolicy(); }diff --git a/frontend/slices/appshell/lib/alfa-run-state.test.ts b/frontend/slices/appshell/lib/alfa-run-state.test.tsnew file mode 100644index 00000000..da1cd80f--- /dev/null+++ b/frontend/slices/appshell/lib/alfa-run-state.test.ts@@ -0,0 +1,58 @@+import { beforeEach, describe, expect, it } from "vitest";+import { alfaRunState, clearAlfaRunState, startAlfaRunState, setAlfaOperation, stopAlfaRunState, endAlfaRunState, recordAlfaRunActivity } from "./alfa-run-state";+import { registerAlfaRunner, registerAlfaStop, sendToAlfa, stopAlfa, unregisterAlfaRunner } from "./alfa";+beforeEach(() => { unregisterAlfaRunner(); clearAlfaRunState(); });+describe("Alfa actual run lifetime", () => {+ it("distinguishes approval waiting and freezes terminal states", () => {+ const id = startAlfaRunState();+ setAlfaOperation("fs.mkdir", true);+ expect(alfaRunState()?.status).toBe("waiting");+ setAlfaOperation("fs.mkdir");+ expect(alfaRunState()?.status).toBe("working");+ endAlfaRunState(id, "failed");+ endAlfaRunState(id, "done");+ expect(alfaRunState()?.status).toBe("failed");+ });+ it("keeps the single-flight lock until a stopped host call unwinds", async () => {+ let release!: () => void;+ registerAlfaRunner(async () => async () => new Promise<void>((resolve) => { release = resolve; }));+ registerAlfaStop(() => {});+ const pending = sendToAlfa("work");+ await Promise.resolve();+ stopAlfa();+ expect(alfaRunState()?.status).toBe("stopped");+ expect(await sendToAlfa("second")).toBe(false);+ release();+ await pending;+ expect(alfaRunState()?.status).toBe("stopped");+ registerAlfaRunner(async () => async () => {});+ await sendToAlfa("next");+ expect(alfaRunState()?.status).toBe("done");+ });+ it("does not launch a stopped lazy runner", async () => {+ let release!: (runner: () => Promise<void>) => void;+ let launched = false;+ registerAlfaRunner(() => new Promise((resolve) => { release = resolve; }));+ const pending = sendToAlfa("load");+ stopAlfa();+ release(async () => { launched = true; });+ expect(await pending).toBe(false);+ expect(launched).toBe(false);+ });+ it("records loader failure and never leaves Working after rejection", async () => {+ registerAlfaRunner(async () => { throw new Error("load"); });+ expect(await sendToAlfa("fail")).toBe(false);+ expect(alfaRunState()?.status).toBe("failed");+ });+ it("bounds activity and ignores old-run completions", () => {+ const old = startAlfaRunState();+ startAlfaRunState();+ endAlfaRunState(old, "done");+ expect(alfaRunState()?.status).toBe("working");+ for (let i = 0; i < 150; i++) recordAlfaRunActivity(String(i), "fs.read", "ok");+ expect(alfaRunState()?.activities).toHaveLength(120);+ stopAlfaRunState();+ setAlfaOperation("late tool");+ expect(alfaRunState()?.status).toBe("stopped");+ });+});diff --git a/frontend/slices/appshell/lib/alfa-run-state.ts b/frontend/slices/appshell/lib/alfa-run-state.tsnew file mode 100644index 00000000..d56c5b69--- /dev/null+++ b/frontend/slices/appshell/lib/alfa-run-state.ts@@ -0,0 +1,66 @@+"use client";++import { useSyncExternalStore } from "react";++export type AlfaRunStatus = "working" | "waiting" | "done" | "failed" | "stopped";+export type AlfaRunActivity = { id: string; label: string; state: string; at: number };+export type AlfaRunState = {+ id: number;+ status: AlfaRunStatus;+ startedAt: number;+ finishedAt?: number;+ heartbeatAt: number;+ operation?: string;+ activities: AlfaRunActivity[];+};++let sequence = 0;+let state: AlfaRunState | null = null;+const subscribers = new Set<() => void>();+const subscribe = (fn: () => void) => { subscribers.add(fn); return () => subscribers.delete(fn); };+const emit = () => subscribers.forEach((fn) => fn());+export const alfaRunState = () => state;+export function useAlfaRunState() {+ return useSyncExternalStore(subscribe, alfaRunState, () => null);+}++export function startAlfaRunState(): number {+ const now = Date.now();+ state = { id: ++sequence, status: "working", startedAt: now, heartbeatAt: now,+ operation: "Loading assistant", activities: [] };+ emit();+ return sequence;+}++export function setAlfaOperation(operation: string, waiting = false): void {+ if (!state || !["working", "waiting"].includes(state.status)) return;+ state = { ...state, status: waiting ? "waiting" : "working", operation, heartbeatAt: Date.now() };+ emit();+}++/** Heartbeats come from runner events, never from a UI animation or timer. */+export function pulseAlfaRun(): void {+ if (!state || state.status !== "working") return;+ state = { ...state, heartbeatAt: Date.now() };+ emit();+}++export function recordAlfaRunActivity(id: string, label: string, activityState: string): void {+ if (!state || !["working", "waiting"].includes(state.status)) return;+ const row = { id, label: label || state.activities.find((item) => item.id === id)?.label || id, state: activityState, at: Date.now() };+ state = { ...state, heartbeatAt: row.at,+ activities: [row, ...state.activities.filter((item) => item.id !== id)].slice(0, 120) };+ emit();+}++export function endAlfaRunState(id: number, status: "done" | "failed" | "stopped"): void {+ if (!state || state.id !== id || !["working", "waiting"].includes(state.status)) return;+ state = { ...state, status, operation: undefined, finishedAt: Date.now() };+ emit();+}++export function stopAlfaRunState(): void {+ if (state && ["working", "waiting"].includes(state.status)) endAlfaRunState(state.id, "stopped");+}++export function clearAlfaRunState(): void { state = null; emit(); }diff --git a/frontend/slices/appshell/lib/alfa.ts b/frontend/slices/appshell/lib/alfa.tsindex 0b300ff3..6ce96b7e 100644--- a/frontend/slices/appshell/lib/alfa.ts+++ b/frontend/slices/appshell/lib/alfa.ts@@ -1,6 +1,7 @@"use client";import { useSyncExternalStore } from "react";+import { alfaRunState, startAlfaRunState, endAlfaRunState, stopAlfaRunState } from "./alfa-run-state";// THE Alfa conversation. One store, one conversation, many windows onto it — the// Assistant app and the per-app Alfa sheet are two views of this, not two chats.@@ -96,8 +97,8 @@ export function registerAlfaStop(fn: () => void): void {}export function stopAlfa(): void {+ stopAlfaRunState();stopper?.();- setAlfaBusy(false);}/**@@ -123,6 +124,7 @@ export function registerAlfaRunner(loader: () => Promise<AlfaRunner>): void {* first-ever send would MEMOISE the no-op, after which every send resolved silently* and sendToAlfa still returned true. */export function unregisterAlfaRunner(): void {+ stopAlfa();runner = null;loaded = null;stopper = null;@@ -141,11 +143,17 @@ export async function sendToAlfa(text: string, ctx: AlfaContext = {}): Promise<bconst body = text.trim();if (!body || busy || !runner) return false;setAlfaBusy(true);+ const runId = startAlfaRunState();+ const loader = runner;try {- loaded = loaded ?? (await runner());+ const engine = loaded ?? (await loader());+ if (alfaRunState()?.status === "stopped" || runner !== loader) return false;+ loaded = engine;await loaded(body, ctx);+ endAlfaRunState(runId, "done");return true;} catch {+ endAlfaRunState(runId, "failed");// The engine owns its own error rows; this only guarantees the lock is freed.return false;} finally {diff --git a/frontend/slices/assistant/components/chat-panel.tsx b/frontend/slices/assistant/components/chat-panel.tsxindex 624f8095..0ad83e35 100644--- a/frontend/slices/assistant/components/chat-panel.tsx+++ b/frontend/slices/assistant/components/chat-panel.tsx@@ -22,6 +22,7 @@ import {ChatComposer,type AlfaMessage} from "@/features/appshell";+import { AlfaRunProgress, AlfaApprovalGrants, alfaRunState, setAlfaOperation, pulseAlfaRun, recordAlfaRunActivity, endAlfaRunState, stopAlfaRunState } from "@/features/appshell";import { runToolAgent, useOsApi, type AgentMsg } from "../lib/host";import type { Agent, Automation } from "../lib/types";import { activeAgent } from "../lib/store";@@ -103,9 +104,15 @@ export function ChatPanel({// Stable UI seam for the tool binding: push/patch tool cards + await approval.const pushCard = useCallback((id: string, card: ToolCard) => {+ setAlfaOperation(card.name, card.status === "pending");+ recordAlfaRunActivity(id, card.name, card.status);setMessages((prev) => [...prev, { id, role: "tool", tool: card }]);}, [setMessages]);const updateCard = useCallback((id: string, patch: Partial<ToolCard>) => {+ if (patch.status) {+ recordAlfaRunActivity(id, "", patch.status);+ setAlfaOperation(patch.status === "running" ? "Executing tool" : "Requesting response");+ }setMessages((prev) => prev.map((m) => (m.id === id && m.tool ? { ...m, tool: { ...m.tool, ...patch } } : m)));}, [setMessages]);// Shared rendezvous: any surface showing the card can answer it, including the@@ -119,13 +126,14 @@ export function ChatPanel({}, []);const stop = useCallback(() => {+ stopAlfaRunState();abortRef.current?.abort();abortRef.current = null;clearAlfaApprovals(); // unblock parked calls so the loop unwinds cleanly}, []);// Abort the in-flight run if the panel unmounts (window close / app swap).- useEffect(() => () => abortRef.current?.abort(), []);+ useEffect(() => stop, [stop]);// Thread persistence: save the conversation to a YAML thread + resume one.const { persist, loadThread, newThread } = useThreadPersistence(historyRef, setMessages, stop);@@ -162,14 +170,16 @@ export function ChatPanel({? " You are in LIVE mode on a production VPS; tool actions are real.": " You are in MOCK mode: fs, exec and sys tools are simulated (no real VPS). The skills.* and memory.* tools are NOT simulated — they read and write real host state even here.";const runId = beginAlfaRun(text);+ const stateId = alfaRunState()?.id;+ setAlfaOperation("Requesting response");let runOk = false;try {- const { history: next } = await runToolAgent(+ const { history: next, outcome } = await runToolAgent(historyRef.current,tools,invoke,{- onDelta: (c) => appendToLastAssistant((t) => t + c),+ onDelta: (c) => { pulseAlfaRun(); appendToLastAssistant((t) => t + c); },// After each tool card, open a fresh assistant bubble so the next// turn's text streams BELOW the card rather than into an earlier one.onTool: () => setMessages((prev) => [...prev, { id: nextId(), role: "assistant", text: "" }]),@@ -183,13 +193,15 @@ export function ChatPanel({ctrl.signal,);historyRef.current = next;- runOk = true;+ runOk = outcome === "completed";+ if (outcome === "limit") appendToLastAssistant((t) => t + "\n\nTurn limit reached. Execution has stopped; send a new message to continue.");} catch (err) {if (!ctrl.signal.aborted) {const note = errText(err);appendToLastAssistant((t) => (t ? `${t}\n\n⚠ ${note}` : note));}} finally {+ if (stateId !== undefined) endAlfaRunState(stateId, ctrl.signal.aborted ? "stopped" : runOk ? "done" : "failed");finishAlfaRun(runId, ctrl.signal.aborted ? "cancelled" : runOk ? "completed" : "failed");if (abortRef.current === ctrl) abortRef.current = null;// Drop the empty streaming placeholders (model ended on a tool / no text),@@ -225,6 +237,8 @@ export function ChatPanel({{switcher}</div>{cockpit}+ <AlfaRunProgress />+ <AlfaApprovalGrants /><divclassName={cn("px-3 py-1 text-center text-[11px] font-medium",diff --git a/frontend/slices/assistant/components/use-thread-persistence.ts b/frontend/slices/assistant/components/use-thread-persistence.tsindex 4c01bf36..dd02d850 100644--- a/frontend/slices/assistant/components/use-thread-persistence.ts+++ b/frontend/slices/assistant/components/use-thread-persistence.ts@@ -3,6 +3,7 @@import { useCallback, useRef, type Dispatch, type SetStateAction } from "react";import type { AgentMsg } from "../lib/host";import type { ChatMessage } from "@/features/appshell";+import { clearAlfaRunState, newAlfaApprovalSession } from "@/features/appshell";type LoadArg = { id: string; createdAt: number; messages: unknown[]; history: unknown[] };@@ -43,6 +44,8 @@ export function useThreadPersistence(const loadThread = useCallback((t: LoadArg) => {stop();+ clearAlfaRunState();+ newAlfaApprovalSession();threadIdRef.current = t.id;createdAtRef.current = t.createdAt || Date.now();historyRef.current = (t.history ?? []) as AgentMsg[];@@ -53,6 +56,8 @@ export function useThreadPersistence(const newThread = useCallback(() => {stop();+ clearAlfaRunState();+ newAlfaApprovalSession();threadIdRef.current = null;createdAtRef.current = 0;historyRef.current = [];diff --git a/frontend/slices/assistant/host-tools/use-host-commands.ts b/frontend/slices/assistant/host-tools/use-host-commands.tsindex 9b23277d..c0cafd5d 100644--- a/frontend/slices/assistant/host-tools/use-host-commands.ts+++ b/frontend/slices/assistant/host-tools/use-host-commands.ts@@ -4,6 +4,7 @@ import { useMemo, useRef } from "react";import { matchDestructive, useOsApi } from "../lib/host";import type { AiTool, ToolInvocation, ToolOutcome } from "../lib/host";import { useApps, type ToolCard } from "@/features/appshell";+import { alfaRunState, alfaProjectContext, alfaApprovalScope, alfaApprovalKey, hasAlfaApproval, rememberAlfaApproval } from "@/features/appshell";import { findHostTool, HOST_AI_TOOLS } from "./registry";import { recordAlfaTool } from "../lib/alfa-activity";@@ -16,15 +17,6 @@ export type HostToolUi = {requestApproval: (id: string) => Promise<{ approve: boolean; remember: boolean }>;};-// "Allow this exact call again" is offered only for low-blast-radius mutations —-// never exec.run (arbitrary RCE) or a delete. Exact-signature scoped, never a glob.-const REMEMBERABLE = new Set(["fs.write", "fs.mkdir", "fs.move", "fs.copy"]);--// Stable signature for the remember/auto-deny sets: name + key-sorted input.-function signature(name: string, input: Record<string, unknown>): string {- return `${name}:${JSON.stringify(input ?? {}, Object.keys(input ?? {}).sort())}`;-}-// Binds the host-tool catalog to the LIVE OsApi + the approval gate. Returns the// tool schemas (for the AI request) + `invoke`, which the agent loop calls per// tool_use. Read tools run immediately; mutate tools push a pending card and@@ -39,7 +31,6 @@ export function useHostCommands(ui: HostToolUi): {const api = useOsApi();const apps = useApps();const denied = useRef<Set<string>>(new Set());- const allowed = useRef<Set<string>>(new Set());const seq = useRef(0);return useMemo(() => ({@@ -48,6 +39,8 @@ export function useHostCommands(ui: HostToolUi): {const tool = findHostTool(name);const id = `hc${seq.current++}`;const args = input ?? {};+ const scope = alfaApprovalScope(alfaProjectContext()?.path, api.mode);+ if (alfaRunState()?.status === "stopped") return { ok: false, result: "Stopped before execution." };const startedAt = Date.now();if (!tool) {const msg = `unknown tool "${name}"`;@@ -56,6 +49,7 @@ export function useHostCommands(ui: HostToolUi): {return { ok: false, result: msg };}const execute = async (): Promise<ToolOutcome> => {+ if (alfaRunState()?.status === "stopped") return { ok: false, result: "Stopped before execution." };ui.updateCard(id, { status: "running" });recordAlfaTool(id, name, "started");try {@@ -78,15 +72,15 @@ export function useHostCommands(ui: HostToolUi): {// mutate → approval gate.const danger = name === "exec.run" ? matchDestructive(String(args.cmd ?? "")) ?? undefined : undefined;- const sig = signature(name, args);- ui.pushCard(id, { name, effect: "mutate", input: args, status: "pending", danger });+ const sig = alfaApprovalKey(name, args, scope);+ ui.pushCard(id, { name, effect: "mutate", input: args, status: "pending", danger, approvalScope: scope });recordAlfaTool(id, name, "started", "waiting for approval");if (denied.current.has(sig)) {ui.updateCard(id, { status: "denied", result: "Auto-denied (already declined this exact call)." });recordAlfaTool(id, name, "denied", "auto-denied", Date.now() - startedAt);return { ok: false, result: "Auto-denied: the user already declined this exact call. Stop retrying it — propose an alternative or ask." };}- if (allowed.current.has(sig)) return execute();+ if (!danger && hasAlfaApproval(name, args, scope)) return execute();const { approve, remember } = await ui.requestApproval(id);if (!approve) {denied.current.add(sig);@@ -94,7 +88,11 @@ export function useHostCommands(ui: HostToolUi): {recordAlfaTool(id, name, "denied", "denied by user", Date.now() - startedAt);return { ok: false, result: "Denied by the user. Do not retry this exact call; propose an alternative or ask what they'd prefer." };}- if (remember && REMEMBERABLE.has(name)) allowed.current.add(sig);+ if (scope !== alfaApprovalScope(alfaProjectContext()?.path, api.mode) || alfaRunState()?.status === "stopped") {+ ui.updateCard(id, { status: "denied", result: "Stopped or approval scope changed. Send a new request." });+ return { ok: false, result: "Stopped or approval scope changed." };+ }+ if (remember && !danger) rememberAlfaApproval(name, args, scope);return execute();},}),diff --git a/lib/ai/agent-loop.test.ts b/lib/ai/agent-loop.test.tsnew file mode 100644index 00000000..490ee1f2--- /dev/null+++ b/lib/ai/agent-loop.test.ts@@ -0,0 +1,20 @@+import { expect, it, vi } from "vitest";+import { runToolAgent } from "./agent-loop";+import { streamAgentTurn } from "./stream";+vi.mock("./stream", () => ({ streamAgentTurn: vi.fn() }));+it("stops between tool calls and retains matching tool results", async () => {+ vi.mocked(streamAgentTurn).mockResolvedValue({ text: "", stopReason: null, toolUses: [+ { id: "one", name: "fs.read", input: {} }, { id: "two", name: "fs.write", input: {} },+ ] });+ const ctrl = new AbortController();+ const invoke = vi.fn(async () => { ctrl.abort(); return { ok: true, result: "read" }; });+ const result = await runToolAgent([], [], invoke, { onDelta: vi.fn(), onTool: vi.fn() }, 8, undefined, ctrl.signal);+ expect(invoke).toHaveBeenCalledTimes(1);+ expect(result.outcome).toBe("stopped");+ expect(result.history.at(-1)).toMatchObject({ role: "tool", results: [{ id: "one" }, { id: "two", isError: true }] });+});+it("reports the turn cap as a limit instead of successful completion", async () => {+ vi.mocked(streamAgentTurn).mockResolvedValue({ text: "", stopReason: null, toolUses: [{ id: "one", name: "fs.read", input: {} }] });+ const result = await runToolAgent([], [], async () => ({ ok: true, result: "read" }), { onDelta: vi.fn(), onTool: vi.fn() }, 1);+ expect(result.outcome).toBe("limit");+});diff --git a/lib/ai/agent-loop.ts b/lib/ai/agent-loop.tsindex a00cd509..ccf65aff 100644--- a/lib/ai/agent-loop.ts+++ b/lib/ai/agent-loop.ts@@ -28,24 +28,30 @@ export async function runToolAgent(maxTurns = 8,system?: string,signal?: AbortSignal,-): Promise<{ history: AgentMsg[]; text: string }> {+): Promise<{ history: AgentMsg[]; text: string; outcome: "completed" | "stopped" | "limit" }> {const msgs = [...history];let lastText = "";+ let outcome: "completed" | "stopped" | "limit" = "limit";for (let i = 0; i < maxTurns; i++) {- if (signal?.aborted) break;+ if (signal?.aborted) { outcome = "stopped"; break; }const { text, toolUses } = await streamAgentTurn(msgs, tools, ev.onDelta, signal, system);msgs.push({ role: "assistant", text, toolUses });if (text) lastText = text;- if (toolUses.length === 0) break;+ if (toolUses.length === 0) { outcome = signal?.aborted ? "stopped" : "completed"; break; }const results = [];for (const tu of toolUses) {- const outcome = await invoke({ name: tu.name, input: tu.input });- ev.onTool(tu.name, tu.input, outcome);- results.push({ id: tu.id, content: outcome.result, isError: !outcome.ok });+ if (signal?.aborted) {+ results.push({ id: tu.id, content: "Stopped before execution.", isError: true });+ outcome = "stopped";+ continue;+ }+ const toolOutcome = await invoke({ name: tu.name, input: tu.input });+ ev.onTool(tu.name, tu.input, toolOutcome);+ results.push({ id: tu.id, content: toolOutcome.result, isError: !toolOutcome.ok });}msgs.push({ role: "tool", results });}- return { history: msgs, text: lastText };+ return { history: msgs, text: lastText, outcome: signal?.aborted ? "stopped" : outcome };}export type { AgentMsg, AiTool } from "./stream";diff --git a/scripts/e2e/assistant-chat-ux.mjs b/scripts/e2e/assistant-chat-ux.mjsnew file mode 100644index 00000000..4736222c--- /dev/null+++ b/scripts/e2e/assistant-chat-ux.mjs@@ -0,0 +1,81 @@+#!/usr/bin/env node+import { chromium, expect } from "@playwright/test";+import { releaseFixture } from "./release-fixture.mjs";++const fixture = await releaseFixture();+let browser;+try {+ const login = await fetch(fixture.base + "/api/auth/login", {+ method: "POST", headers: { "content-type": "application/json", origin: fixture.base },+ body: JSON.stringify({ password: fixture.password, deviceId: fixture.device }),+ });+ expect(login.ok).toBe(true);+ const cookie = /session=([^;]+)/.exec(login.headers.get("set-cookie") || "")?.[1];+ expect(cookie).toBeTruthy();+ browser = await chromium.launch({ headless: true });+ for (const viewport of [{ width: 1363, height: 936 }, { width: 390, height: 844 }]) {+ const context = await browser.newContext({ viewport, hasTouch: viewport.width < 768 });+ await context.addCookies([{ name: "session", value: cookie, url: fixture.base }]);+ await context.addInitScript((device) => {+ localStorage.setItem("mso.device.id", device);+ localStorage.setItem("mso:onboarding:v1", "done");+ }, fixture.device);+ const page = await context.newPage();+ const errors = [];+ page.on("pageerror", (error) => errors.push(error.message));+ let request;+ await page.route("**/api/assistant", (route) => { request = route; });+ await page.goto(fixture.base + "/assistant");+ const input = page.locator("textarea:visible").first();+ await expect(input).toBeVisible();+ const send = async (text) => {+ request = undefined;+ await input.fill(text);+ await page.getByRole("button", { name: "Send message", exact: true }).first().click();+ await expect.poll(() => Boolean(request)).toBe(true);+ };+ const run = page.getByRole("region", { name: "Assistant run" });+ const respond = async (body, status = 200) => {+ const route = request; request = undefined;+ await route.fulfill({ status, contentType: status === 200 ? "text/event-stream" : "application/json", body });+ };+ await send("Create a test folder");+ await expect(run.getByRole("status")).toHaveText("Working");+ await expect(run.getByText(/elapsed/)).toBeVisible();+ await respond('event: tool_use\ndata: {"id":"mkdir","name":"fs.mkdir","input":{"path":"~/projects/chat-ux-fixture"}}\n\nevent: done\ndata: {"stopReason":"tool_use"}\n\n');+ await expect(run.getByRole("status")).toHaveText("Waiting for approval");+ await expect(input).toHaveAttribute("placeholder", "Waiting for your approval…");+ await page.getByRole("switch").last().click();+ await page.getByRole("button", { name: "Approve", exact: true }).click();+ await expect.poll(() => Boolean(request)).toBe(true);+ await respond('event: delta\ndata: "Folder ready."\n\nevent: done\ndata: {"stopReason":"end_turn"}\n\n');+ await expect(run.getByRole("status")).toHaveText("Done");+ await expect(page.getByText("Always approve: 1 exact calls")).toBeVisible();+ await send("Create that same folder again");+ await respond('event: tool_use\ndata: {"id":"mkdir2","name":"fs.mkdir","input":{"path":"~/projects/chat-ux-fixture"}}\n\nevent: done\ndata: {"stopReason":"tool_use"}\n\n');+ await expect.poll(() => Boolean(request)).toBe(true);+ await expect(page.getByRole("button", { name: "Approve", exact: true })).toHaveCount(0);+ await respond('event: delta\ndata: "Already ready."\n\nevent: done\ndata: {"stopReason":"end_turn"}\n\n');+ await expect(run.getByRole("status")).toHaveText("Done");+ await page.getByText("Always approve: 1 exact calls").click();+ await page.getByRole("button", { name: "Reset all approvals" }).click();+ await send("Pause for approval");+ await respond('event: tool_use\ndata: {"id":"mkdir3","name":"fs.mkdir","input":{"path":"~/projects/chat-ux-fixture"}}\n\nevent: done\ndata: {"stopReason":"tool_use"}\n\n');+ await expect(run.getByRole("status")).toHaveText("Waiting for approval");+ await run.getByRole("button", { name: "Stop", exact: true }).click();+ await expect(run.getByRole("status")).toHaveText("Stopped");+ await expect(page.getByRole("button", { name: "Send message", exact: true }).first()).toBeVisible();+ await send("Simulate a provider failure");+ await respond('{"error":"provider_unavailable"}', 503);+ await expect(run.getByRole("status")).toHaveText("Failed");+ await run.getByRole("button", { name: "Details" }).click();+ await expect(page.getByRole("heading", { name: "Run details" })).toBeVisible();+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)).toBe(true);+ expect(errors).toEqual([]);+ await context.close();+ console.log(`PASS Assistant explicit states, scoped approval/reset, Stop and details ${viewport.width}x${viewport.height}`);+ }+} finally {+ await browser?.close();+ await fixture.close();+}diff --git a/scripts/verify-build.sh b/scripts/verify-build.shindex e247701b..70ba7478 100755--- a/scripts/verify-build.sh+++ b/scripts/verify-build.sh@@ -83,6 +83,12 @@ if ! node scripts/e2e/shell-status.mjs; thenexit 43fi+echo "== verify Assistant chat UX (synthetic tools and provider)"+if ! node scripts/e2e/assistant-chat-ux.mjs; then+ echo "verification failed during Assistant chat UX E2E" >&2+ exit 43+fi+echo "== verify deferred shell performance"if ! node scripts/e2e/bundle-performance.mjs; thenecho "verification failed during deferred shell performance E2E" >&2