Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(lan-webui): enforce the ask ceiling and archived-project read-only

vastsa5ad6880f72bd
diff --git a/apps/desktop/electron/main/agent-host-bridge.ts b/apps/desktop/electron/main/agent-host-bridge.ts
index 8f64bdd14..3a64a9eed 100644
--- a/apps/desktop/electron/main/agent-host-bridge.ts
+++ b/apps/desktop/electron/main/agent-host-bridge.ts
@@ -111,18 +111,9 @@ export function createAgentHostBridge(options: AgentHostBridgeOptions) {
async prompt(request: TurnStartRequest) {
try {
const summary = await sessions.get(request.sessionId);
- // A per-turn ceiling that would WIDEN the session's stored mode is a
- // real escalation attempt — e.g. a remote viewer whose principal is
- // subject to `remoteMaxPermissionMode: "ask"` should never be able to
- // run a turn at `auto`. Refuse before the sidecar sees the request.
- //
- // A NARROWER ceiling (or the same mode) is safe to accept: it can only
- // reduce what the turn is allowed to do. The runtime still uses the
- // session's stored mode when it enforces tool decisions, so a narrower
- // request is not yet honoured turn-locally — that is the R1 leftover
- // waiting on host-core to accept a `permissionMode` override on
- // `session.beginTurn`. We plumb the parameter end-to-end anyway so the
- // enforcement gate can flip on without another wire change.
+ // A per-turn mode that would WIDEN the session's stored mode is a
+ // real escalation attempt — e.g. a queued remote turn whose session
+ // was lowered after admission. Refuse before the sidecar sees it.
if (
summary &&
summary.permissionMode !== request.effectivePermissionMode &&
@@ -139,10 +130,9 @@ export function createAgentHostBridge(options: AgentHostBridgeOptions) {
},
);
}
- const permissionModeOverride =
- summary && summary.permissionMode !== request.effectivePermissionMode
- ? request.effectivePermissionMode
- : undefined;
+ // A principal bound by the remote ceiling (a paired LAN browser) has
+ // it recorded on the durable turn; host-core then applies it to every
+ // tool decision of that turn, including its delegates.
const promptRequest = {
sessionId: request.sessionId,
content: request.content,
@@ -151,7 +141,7 @@ export function createAgentHostBridge(options: AgentHostBridgeOptions) {
...(request.userMessageId ? { messageId: request.userMessageId } : {}),
...(request.voiceOrigin ? { voiceOrigin: request.voiceOrigin } : {}),
...(request.attachments ? { attachments: request.attachments } : {}),
- ...(permissionModeOverride ? { permissionMode: permissionModeOverride } : {}),
+ ...(request.permissionCeiling ? { permissionMode: request.permissionCeiling } : {}),
};
// The in-process invoke keeps object identity, so the mode run origin
// reaches the prompt handler without any serializable field.
diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.ts
index b2b269f65..7977f1d56 100644
--- a/apps/desktop/electron/main/ipc/agent-ipc.ts
+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts
@@ -10,7 +10,7 @@ import { expandSlashInvocation, visionFromModelConfig, type ComposerTemplate } f
import { appendPromptFallbackPaths, durableUserMessageId, preparePromptAttachments, type PreparedPromptAttachment } from "../prompt-attachments";
import { resolveSessionReferences } from "../session-references";
import { resolvePromptAgentMentions } from "../agent-mentions";
-import { executionFromResponse, resolveSessionMessageInput } from "@pi-desktop/host-runtime";
+import { PERMISSION_CEILING_UNAVAILABLE, assertTurnCeilingRecorded, executionFromResponse, isPermissionCeiling, resolveSessionMessageInput, turnCeilingParams } from "@pi-desktop/host-runtime";
import type { AgentExtensionBridge } from "../agent-extensions";
import type { AgentHostBridge } from "../agent-host-bridge";
import type { AgentSidecar } from "../agent-sidecar";
@@ -222,8 +222,20 @@ export function registerAgentIpc({
const startGoal = goalStartRequested(req);
if (!sidecar) throw new Error("sidecar unavailable");
const voiceOrigin = parseVoiceOrigin(req.voiceOrigin);
+ // The per-turn ceiling (spec §7.3) only ever narrows, and only host-core
+ // can enforce it. A malformed one, or one on a path host-core does not
+ // authorize, refuses the prompt instead of running under the stored mode.
+ if (req.permissionMode !== undefined && !isPermissionCeiling(req.permissionMode)) {
+ throw Object.assign(new Error("Invalid per-turn permission ceiling"), { errorCode: ErrorCodes.INVALID_ARGUMENT });
+ }
+ const permissionCeiling = req.permissionMode;
if (req.sessionId.startsWith("native-pi:")) {
if (startGoal) rejectNativeAgentOperation(req.sessionId);
+ if (permissionCeiling) {
+ throw Object.assign(new Error("Native Pi sessions cannot enforce a per-turn permission ceiling"), {
+ errorCode: PERMISSION_CEILING_UNAVAILABLE,
+ });
+ }
// Desktop-managed MCP servers are not installed in native Pi sessions.
if (/^\/mcp:\S/.test(req.content)) expandMcpInvocation(req.content, []);
if (voiceOrigin) {
@@ -246,6 +258,10 @@ export function registerAgentIpc({
if (!host) throw new Error("host unavailable");
if (background && background.host !== host) throw new Error("Background continuation belongs to an expired Host");
if (startGoal && activeTurns.has(req.sessionId)) {
+ // Re-queueing under the Desktop principal would drop the ceiling.
+ if (permissionCeiling) {
+ throw Object.assign(new Error("Session already has an active turn"), { errorCode: ErrorCodes.AGENT_BUSY });
+ }
const entry = await queueGoal({ ...req, userMessageId: req.messageId });
return { accepted: true, turnId: entry.id };
}
@@ -389,11 +405,12 @@ export function registerAgentIpc({
sidecar.setProjectInstructionRoot(req.sessionId, launch.workspaceRoot ?? launch.projectPath);
// Open a durable turn row, then persist the user message under it.
- const turn = await host.call<{ turnId?: string }>("session.beginTurn", {
+ const turn = await host.call<{ turnId?: string; permissionCeiling?: unknown }>("session.beginTurn", {
sessionId: req.sessionId,
providerId: launch.providerId,
modelId: launch.modelId,
...(sessionMessage ? { sessionMessageId: sessionMessage.origin.messageId } : {}),
+ ...turnCeilingParams(permissionCeiling),
});
const durableTurnId = String(turn?.turnId ?? "").trim();
if (!durableTurnId) {
@@ -402,6 +419,12 @@ export function registerAgentIpc({
activeTurns.set(req.sessionId, durableTurnId);
recordTurnStart(req.sessionId, durableTurnId);
activeTurnUsages.delete(req.sessionId);
+ try {
+ assertTurnCeilingRecorded(permissionCeiling, turn);
+ } catch (error) {
+ await finishTurn(req.sessionId, "error", PERMISSION_CEILING_UNAVAILABLE, { turnId: durableTurnId });
+ throw error;
+ }
// A staged mode claims its run for this durable turn before anything runs;
// the sidecar then executes the run's own definition snapshot.
@@ -695,11 +718,6 @@ export function registerAgentIpc({
})),
],
...(modeOrigin || background ? {} : { userMessageId: userMessage.id }),
- // Per-turn permission ceiling override (R1 leftover; spec §7.3). The
- // sidecar records it on the turn context; enforcement of a NARROWER
- // ceiling still routes through the session's stored mode until
- // host-core `session.beginTurn` accepts the scoped param.
- ...(req.permissionMode ? { permissionMode: req.permissionMode } : {}),
},
);
} catch (e) {
diff --git a/apps/desktop/electron/main/lan-webui/workspace.ts b/apps/desktop/electron/main/lan-webui/workspace.ts
index d0e909d9e..f487be0f0 100644
--- a/apps/desktop/electron/main/lan-webui/workspace.ts
+++ b/apps/desktop/electron/main/lan-webui/workspace.ts
@@ -12,6 +12,7 @@ import {
type LanSession,
type ProjectGroupRecord,
} from "@pi-desktop/shared";
+import { PERMISSION_CEILING_UNAVAILABLE } from "@pi-desktop/host-runtime";
import { readLanModelOptions, type ReadCachedModels } from "./models";
import type { LanMeta, LanOrganization } from "./organization";
import { normalizeProjectKey } from "./organization";
@@ -95,6 +96,8 @@ function oneOrganizeField(body: Record<string, unknown>): ["name", string] | ["p
export function createLanWorkspace(deps: LanWorkspaceDeps) {
const live = new Map<string, string>();
+ /** Sends past their archive check whose turn the Agent Host has not yet admitted. */
+ const admitting = new Map<string, number>();
const listeners = new Set<(change: LanChange) => void>();
const timers = new Map<string, ReturnType<typeof setTimeout>>();
@@ -167,7 +170,13 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {
return index.get(normalizeProjectKey(path))?.id;
}
- function sessionView(session: HostSession, projectId: string | null, meta: LanMeta, projectLabel: string | null = null): LanSession {
+ function sessionView(
+ session: HostSession,
+ projectId: string | null,
+ meta: LanMeta,
+ projectLabel: string | null = null,
+ projectArchived = false,
+ ): LanSession {
const own = meta.sessionMeta[session.id] ?? {};
const title = session.title?.trim() || "";
const pinned = own.pinned === true;
@@ -184,6 +193,8 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {
status: running ? "running" : "idle",
updatedAt: session.updatedAt ?? "",
projectLabel,
+ // The parent's flag, never folded into the session's own archive state.
+ projectArchived,
};
}
@@ -209,7 +220,7 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {
const label = projectId === null ? null : projectLabels(list, meta).get(projectId) ?? null;
const group = projectId === null ? undefined : list.find((candidate) => candidate.id === projectId);
const projectArchived = group !== undefined && projectView(group, meta).archived;
- return { session, view: sessionView(session, projectId, meta, label), projectArchived };
+ return { session, view: sessionView(session, projectId, meta, label, projectArchived), projectArchived, group };
}
function projectLabels(list: ProjectGroupRecord[], meta: LanMeta): Map<string, string> {
@@ -266,7 +277,10 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {
if (projectId === undefined) continue;
if (!everywhere && projectId !== (wantTemporary ? null : requested)) continue;
if (everywhere && !archivedOnly && projectId !== null && archivedProjects.has(projectId)) continue;
- const view = sessionView(session, projectId, meta, projectId === null ? null : labels.get(projectId) ?? null);
+ const view = sessionView(
+ session, projectId, meta, projectId === null ? null : labels.get(projectId) ?? null,
+ projectId !== null && archivedProjects.has(projectId),
+ );
if (view.archived === archivedOnly && matches(view.title, q)) items.push(view);
}
items.sort(everywhere
@@ -330,6 +344,19 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {
}
type LocalSession = Awaited<ReturnType<typeof requireLocalSession>>;
+
+ /** The session or its parent project is archived in the current record. */
+ function archivedNow({ session, group }: LocalSession): boolean {
+ const meta = deps.organization.read();
+ if (meta.sessionMeta[session.id]?.archived === true) return true;
+ return group !== undefined && projectView(group, meta).archived;
+ }
+
+ /** Running, waiting, queued, or a send still being admitted. */
+ function sessionBusy(sessionId: string): boolean {
+ return deps.activeTurns.has(sessionId) || (admitting.get(sessionId) ?? 0) > 0 ||
+ (deps.getBridge()?.queue.list(sessionId).length ?? 0) > 0;
+ }
function modelRestriction({ session, view, projectArchived }: LocalSession) {
if (view.readOnly || session.remoteWorkspace || session.scheduledRun ||
(session.providerId && trustedExtensionAgentKeyFromProviderId(session.providerId))) return "READ_ONLY";
@@ -423,8 +450,10 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {
if (field === "archived" && value === true) {
const index = rootIndex([group]);
const busy = (await hostSessions()).some(
- (session) => projectOf(session, index) === group.id && deps.activeTurns.has(session.id),
+ (session) => projectOf(session, index) === group.id && sessionBusy(session.id),
);
+ // Checked and written without an intervening await, so a send either
+ // sees this archive or is already counted as busy here.
if (busy) throw new LanError(409, "BUSY");
}
if (field === "name") {
@@ -440,10 +469,7 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {
const [field, value] = oneOrganizeField(body);
const { view } = await requireLocalSession(sessionId);
if (body.revision !== view.revision) throw new LanError(409, "CONFLICT");
- if (field === "archived" && value === true) {
- const queued = deps.getBridge()?.queue.list(sessionId).length ?? 0;
- if (deps.activeTurns.has(sessionId) || queued > 0) throw new LanError(409, "BUSY");
- }
+ if (field === "archived" && value === true && sessionBusy(sessionId)) throw new LanError(409, "BUSY");
if (field === "name") {
await deps.invoke(deps.channels.sessionRename, [sessionId, value]);
deps.organization.patch({ kind: "session", key: sessionId, patch: { manualTitle: true } });
@@ -459,10 +485,14 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {
const text = stringField(body, "text")?.trim() ?? "";
if (!text) throw new LanError(400, "INVALID_ARGUMENT");
if (Buffer.byteLength(text) > MAX_PROMPT) throw new LanError(413, "PAYLOAD_TOO_LARGE");
- const { view } = await requireLocalSession(sessionId);
- if (view.readOnly) throw new LanError(409, "READ_ONLY");
- if (view.archived) throw new LanError(409, "ARCHIVED");
+ const local = await requireLocalSession(sessionId);
+ if (local.view.readOnly) throw new LanError(409, "READ_ONLY");
+ // Re-read the organization record in the same synchronous step that
+ // counts this send as admitting: a concurrent web archive then either
+ // wins (and is seen here) or finds this session busy.
+ if (archivedNow(local)) throw new LanError(409, "ARCHIVED");
const principal: Principal = { subject: `lan:${deviceId}`, roles: ["viewer", "controller"], pairedDevice: false };
+ admitting.set(sessionId, (admitting.get(sessionId) ?? 0) + 1);
try {
const result = await bridge().agentHost.startTurn(principal, {
sessionId,
@@ -475,11 +505,19 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {
emitSoon(sessionId);
return { id: result.turn.id };
} catch (error) {
- const code = (error as { code?: unknown })?.code;
+ const failure = error as { code?: unknown; errorCode?: unknown } | null;
+ const code = failure?.code ?? failure?.errorCode;
if (code === "AGENT_BUSY") throw new LanError(409, "BUSY");
if (code === "FORBIDDEN") throw new LanError(403, "FORBIDDEN");
if (code === "AGENT_UNAVAILABLE") throw new LanError(503, "DESKTOP_UNAVAILABLE");
+ // The Host could not hold this turn to the phone's permission ceiling,
+ // so it did not run under the broader session setting either.
+ if (code === PERMISSION_CEILING_UNAVAILABLE) throw new LanError(503, "PERMISSION_CEILING_UNAVAILABLE");
throw new LanError(500, "FAILED");
+ } finally {
+ const pending = (admitting.get(sessionId) ?? 1) - 1;
+ if (pending > 0) admitting.set(sessionId, pending);
+ else admitting.delete(sessionId);
}
}
diff --git a/apps/desktop/resources/lan-webui/app.js b/apps/desktop/resources/lan-webui/app.js
index 2234a67d3..19c9be3b1 100644
--- a/apps/desktop/resources/lan-webui/app.js
+++ b/apps/desktop/resources/lan-webui/app.js
@@ -404,6 +404,18 @@
input.select();
}
+ /** Restore an archived parent project from one of its conversations. */
+ async function restoreProject(projectId) {
+ if (!state.online) return notify(errorText("NETWORK"));
+ try {
+ const project = (await loadAll("/v1/projects?q=&archived=1")).find((item) => item.id === projectId);
+ if (project) await organize("projects", project, { archived: false });
+ else await render({ refresh: true });
+ } catch (error) {
+ fail(error);
+ }
+ }
+
function organizeActions(kind, item) {
const label = kind === "projects" ? item.label : item.title || t("untitled");
return [
@@ -821,6 +833,11 @@
const notices = [];
if (conversation.waiting === "approval") notices.push(notice({ dot: "waiting", text: t("waitingApproval") }));
if (conversation.waiting === "input") notices.push(notice({ dot: "waiting", text: t("waitingInput") }));
+ // Name the record that must be restored; a parent archive is not the
+ // session's own flag, and restoring the project leaves that flag alone.
+ if (session.projectArchived) {
+ notices.push(notice({ icon: "archive", text: t("archivedProject"), action: { label: t("restoreProject"), run: () => void restoreProject(session.projectId) } }));
+ }
if (session.archived) {
notices.push(notice({ icon: "archive", text: t("archivedSession"), action: { label: t("restore"), run: () => void organize("sessions", session, { archived: false }) } }));
}
@@ -838,7 +855,7 @@
])))
: null;
- const canChat = !session.readOnly && !session.archived;
+ const canChat = !session.readOnly && !session.archived && !session.projectArchived;
if (!conversation.canSelectModel || !canChat) modelPicker.dismiss();
if (!canChat) state.syncComposer = null;
const composer = canChat ? buildComposer(sessionId, conversation) : null;
diff --git a/apps/desktop/resources/lan-webui/locale.js b/apps/desktop/resources/lan-webui/locale.js
index 88461c3d7..ab04fc79b 100644
--- a/apps/desktop/resources/lan-webui/locale.js
+++ b/apps/desktop/resources/lan-webui/locale.js
@@ -76,6 +76,8 @@ window.LAN_LOCALES = {
waitingApproval: "Waiting for approval on the computer.",
waitingInput: "Input needed on the computer.",
archivedSession: "This conversation is archived. Restore it to continue.",
+ archivedProject: "This project is archived. Restore the project to continue its conversations.",
+ restoreProject: "Restore project",
readOnlySession: "Continue this conversation on the computer.",
offline: "Connection lost. Reconnecting…",
signOut: "Disconnect this device",
@@ -86,6 +88,7 @@ window.LAN_LOCALES = {
MODEL_UNAVAILABLE: "This model is no longer available. Refresh the list and choose another.",
CONFLICT: "This changed on another device. The latest version is shown; try again.",
ARCHIVED: "Restore it first.",
+ PERMISSION_CEILING_UNAVAILABLE: "The computer could not limit this device's permissions, so nothing ran. Try again or continue on the computer.",
READ_ONLY: "Continue this conversation on the computer.",
FORBIDDEN: "This device is not allowed to do that.",
NOT_FOUND: "This is no longer available.",
@@ -173,6 +176,8 @@ window.LAN_LOCALES = {
waitingApproval: "等待电脑上审批。",
waitingInput: "需要在电脑上输入。",
archivedSession: "该会话已归档,恢复后才能继续。",
+ archivedProject: "该项目已归档,恢复项目后才能继续其中的会话。",
+ restoreProject: "恢复项目",
readOnlySession: "请在电脑上继续该会话。",
offline: "连接已断开,正在重连…",
signOut: "断开此设备",
@@ -183,6 +188,7 @@ window.LAN_LOCALES = {
MODEL_UNAVAILABLE: "此模型已不可用,请刷新列表后重新选择。",
CONFLICT: "已在其他设备上修改,已显示最新内容,请重试。",
ARCHIVED: "请先恢复。",
+ PERMISSION_CEILING_UNAVAILABLE: "电脑无法为此设备限制权限,消息未运行。请重试,或在电脑上继续。",
READ_ONLY: "请在电脑上继续该会话。",
FORBIDDEN: "此设备没有该权限。",
NOT_FOUND: "该内容已不可用。",
diff --git a/apps/desktop/test/agent-host-bridge-per-turn-ceiling.test.mjs b/apps/desktop/test/agent-host-bridge-per-turn-ceiling.test.mjs
index 54a9ff1ce..710c6660b 100644
--- a/apps/desktop/test/agent-host-bridge-per-turn-ceiling.test.mjs
+++ b/apps/desktop/test/agent-host-bridge-per-turn-ceiling.test.mjs
@@ -16,11 +16,13 @@ const { IPC } = await import("@pi-desktop/shared");
* The bridge exposes an `agentHost` whose `startTurn` runs the same runtime
* port the Electron composition wires. These tests reach through it to verify
* the per-turn permission-ceiling policy: a widening request refuses, a
- * narrower request passes through with the mode forwarded as a per-turn
- * override, and a matching request stays silent.
+ * principal bound by the remote ceiling always carries it to the prompt
+ * handler (which records it on the durable Host turn), and an exempt
+ * principal never does.
*/
-function fixture({ sessionPermissionMode }) {
+function fixture({ sessionPermissionMode, queueEntries = [] }) {
const prompts = [];
+ const pushed = [];
const host = {
async call(method, params) {
if (method === "session.get") {
@@ -35,8 +37,11 @@ function fixture({ sessionPermissionMode }) {
},
};
}
- if (method === "session.queueList") return { entries: [] };
- if (method === "session.queuePush") return {};
+ if (method === "session.queueList") return { entries: queueEntries };
+ if (method === "session.queuePush") {
+ pushed.push(params);
+ return {};
+ }
if (method === "session.queueRemove") return { removed: true };
if (method === "session.queuePrioritize") return {};
if (method === "session.queueReorder") return { moved: true };
@@ -44,10 +49,11 @@ function fixture({ sessionPermissionMode }) {
},
};
+ let busy = false;
const bridge = createAgentHostBridge({
channels: IPC.invoke,
getHost: () => host,
- isSessionBusy: () => false,
+ isSessionBusy: () => busy,
log: () => undefined,
async invoke(channel, [request]) {
prompts.push({ channel, request });
@@ -55,7 +61,7 @@ function fixture({ sessionPermissionMode }) {
return { accepted: true, turnId };
},
});
- return { bridge, prompts };
+ return { bridge, prompts, pushed, setBusy: (value) => { busy = value; } };
}
async function callStart(bridge, principal, effective) {
@@ -142,3 +148,30 @@ test("a widening per-turn ceiling refuses the turn — no sidecar call reaches t
"bridge must throw a FORBIDDEN with the widening-specific message",
);
});
+
+const lanPhone = { subject: "lan:phone", roles: ["viewer", "controller"], pairedDevice: false };
+
+test("a phone turn carries its ceiling even when the session summary already reads ask", async () => {
+ // `inherit` (global default `auto`) is summarised as `ask`, so the effective
+ // mode matches the summary. The ceiling must still reach the Host, which
+ // resolves the real session mode itself.
+ const { bridge, prompts } = fixture({ sessionPermissionMode: "inherit" });
+ const outcome = await callStart(bridge, lanPhone);
+ assert.ok(outcome?.turn, "the phone turn starts");
+ const promptCall = prompts.find((entry) => entry.channel === IPC.invoke.agentPrompt);
+ assert.equal(promptCall.request.permissionMode, "ask");
+});
+
+test("a queued phone turn keeps its ceiling in the durable queue record", async () => {
+ const { bridge, pushed, prompts, setBusy } = fixture({ sessionPermissionMode: "auto" });
+ setBusy(true);
+ const queued = await bridge.agentHost.startTurn(lanPhone, {
+ sessionId: "s1",
+ admission: "queue",
+ input: { text: "later" },
+ context: { requestId: "req-queued" },
+ });
+ assert.equal(queued.turn.status, "queued");
+ assert.equal(pushed.at(-1)?.permissionCeiling, "ask");
+ assert.equal(prompts.length, 0, "nothing runs while the session is busy");
+});
diff --git a/apps/desktop/test/lan-webui-archive-admission.test.mjs b/apps/desktop/test/lan-webui-archive-admission.test.mjs
new file mode 100644
index 000000000..dcf7203a4
--- /dev/null
+++ b/apps/desktop/test/lan-webui-archive-admission.test.mjs
@@ -0,0 +1,123 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { browser, createLanServer, desktop } from "./helpers/lan-webui-fixture.mjs";
+
+/** A paired phone against the real HTTP listener and a fake Desktop. */
+async function setup(t) {
+ const fake = desktop();
+ fake.sessions.push({ id: "s-a2", title: "Second chat", projectPath: "/work/a", mode: "agent", updatedAt: "2026-11-04" });
+ const server = createLanServer({ handler: fake.workspace, assets: new Map([["/index.html", { type: "text/html", body: "<p>ok</p>" }]]) });
+ const { port } = await server.start("127.0.0.1", 0);
+ t.after(async () => {
+ await server.stop();
+ fake.workspace.dispose();
+ });
+ const phone = browser(`http://127.0.0.1:${port}`);
+ const { value: code } = server.issueCode();
+ assert.equal((await phone.request("POST", "/pair", { code, label: "Phone" })).status, 200);
+ await phone.signIn();
+ const bridge = fake.workspaceDeps.getBridge();
+ const projectRevision = async (id, archived = false) =>
+ (await phone.request("GET", `/v1/projects?q=${archived ? "&archived=1" : ""}`)).body.items.find((p) => p.id === id).revision;
+ const sessionIn = async (projectId, id, archived = false) =>
+ (await phone.request("GET", `/v1/sessions?projectId=${projectId}${archived ? "&archived=1" : ""}`)).body.items.find((s) => s.id === id);
+ return { ...fake, phone, bridge, projectRevision, sessionIn };
+}
+
+test("an archived project keeps history readable but accepts no send or queue until restored", async (t) => {
+ const { phone, turns, meta, projectRevision, sessionIn } = await setup(t);
+ // A tab opened before the archive, and a child archived on its own.
+ const before = await phone.request("GET", "/v1/sessions/s-a1");
+ assert.equal(before.body.session.projectArchived, false);
+ const child = await sessionIn("g-a", "s-a2");
+ assert.equal((await phone.request("POST", "/v1/sessions/s-a2/organize", { revision: child.revision, archived: true })).status, 200);
+
+ assert.equal((await phone.request("POST", "/v1/projects/g-a/organize", { revision: await projectRevision("g-a"), archived: true })).status, 200);
+
+ // History stays readable; the parent's archive is not the session's own flag.
+ const archived = await phone.request("GET", "/v1/sessions/s-a1");
+ assert.equal(archived.status, 200);
+ assert.deepEqual(archived.body.messages.items.map((m) => m.text), ["hello", "hi there", "Bash"]);
+ assert.equal(archived.body.session.projectArchived, true);
+ assert.equal(archived.body.session.archived, false);
+ assert.equal(archived.body.session.revision, before.body.session.revision);
+ assert.equal(archived.body.canSelectModel, false);
+ assert.equal(meta.sessionMeta["s-a1"], undefined, "archive state is not copied to descendants");
+
+ // A stale tab cannot send or queue.
+ for (const body of [{ text: "stale send" }, { text: "stale queue", queue: true }]) {
+ assert.deepEqual(await phone.request("POST", "/v1/sessions/s-a1/turns", body), { status: 409, body: { code: "ARCHIVED" } });
+ }
+ assert.equal(turns.length, 0, "no turn was started");
+
+ // Restoring the project reopens its children, not a separately archived one.
+ assert.equal((await phone.request("POST", "/v1/projects/g-a/organize", { revision: await projectRevision("g-a", true), archived: false })).status, 200);
+ assert.equal((await phone.request("POST", "/v1/sessions/s-a1/turns", { text: "after restore" })).status, 200);
+ assert.equal(turns.at(-1).params.input.text, "after restore");
+ const stillArchived = await phone.request("GET", "/v1/sessions/s-a2");
+ assert.equal(stillArchived.body.session.archived, true);
+ assert.equal(stillArchived.body.session.projectArchived, false);
+ assert.deepEqual(await phone.request("POST", "/v1/sessions/s-a2/turns", { text: "x" }), { status: 409, body: { code: "ARCHIVED" } });
+ assert.equal(turns.length, 1);
+});
+
+test("web archive and send admission agree on order and never stop work", async (t) => {
+ const { phone, bridge, queue, activeTurns, projectRevision, sessionIn } = await setup(t);
+
+ // Queued work makes the project and the session busy.
+ queue.set("s-a1", [{ id: "queued-1", content: "next" }]);
+ assert.deepEqual(
+ await phone.request("POST", "/v1/projects/g-a/organize", { revision: await projectRevision("g-a"), archived: true }),
+ { status: 409, body: { code: "BUSY" } },
+ );
+ const own = await sessionIn("g-a", "s-a1");
+ assert.deepEqual(
+ await phone.request("POST", "/v1/sessions/s-a1/organize", { revision: own.revision, archived: true }),
+ { status: 409, body: { code: "BUSY" } },
+ );
+ assert.deepEqual(queue.get("s-a1"), [{ id: "queued-1", content: "next" }], "archive never cancels work");
+ queue.delete("s-a1");
+
+ // A send already past its archive check holds off the archive...
+ const start = bridge.agentHost.startTurn;
+ const reached = Promise.withResolvers();
+ const release = Promise.withResolvers();
+ t.after(() => release.resolve());
+ bridge.agentHost.startTurn = async (...args) => {
+ reached.resolve();
+ await release.promise;
+ return start(...args);
+ };
+ const sending = phone.request("POST", "/v1/sessions/s-a1/turns", { text: "in flight" });
+ await reached.promise;
+ assert.deepEqual(
+ await phone.request("POST", "/v1/projects/g-a/organize", { revision: await projectRevision("g-a"), archived: true }),
+ { status: 409, body: { code: "BUSY" } },
+ );
+ release.resolve();
+ assert.equal((await sending).status, 200);
+ bridge.agentHost.startTurn = start;
+
+ // ...and stays busy while the admitted turn runs.
+ assert.ok(activeTurns.has("s-a1"));
+ assert.equal(
+ (await phone.request("POST", "/v1/projects/g-a/organize", { revision: await projectRevision("g-a"), archived: true })).body.code,
+ "BUSY",
+ );
+ activeTurns.delete("s-a1");
+ assert.equal((await phone.request("POST", "/v1/projects/g-a/organize", { revision: await projectRevision("g-a"), archived: true })).status, 200);
+});
+
+test("a phone turn the Host cannot hold to its permission ceiling is refused visibly", async (t) => {
+ const { phone, bridge, activeTurns } = await setup(t);
+ bridge.agentHost.startTurn = async () => {
+ throw Object.assign(new Error("the Host could not enforce this turn's permission ceiling"), {
+ errorCode: "PERMISSION_CEILING_UNAVAILABLE",
+ });
+ };
+ assert.deepEqual(
+ await phone.request("POST", "/v1/sessions/s-a1/turns", { text: "hello" }),
+ { status: 503, body: { code: "PERMISSION_CEILING_UNAVAILABLE" } },
+ );
+ assert.equal(activeTurns.has("s-a1"), false);
+});
diff --git a/apps/desktop/test/lan-webui-browser-user-path.e2e.mjs b/apps/desktop/test/lan-webui-browser-user-path.e2e.mjs
index d1ce819ab..dac5d69f7 100644
--- a/apps/desktop/test/lan-webui-browser-user-path.e2e.mjs
+++ b/apps/desktop/test/lan-webui-browser-user-path.e2e.mjs
@@ -223,9 +223,10 @@ const journey = String.raw`(async () => {
return JSON.stringify(result);
})()`;
-async function runPhone(t, script, { scan = false, blockCookie = false } = {}) {
+async function runPhone(t, script, { scan = false, blockCookie = false, prepare } = {}) {
const { electronBinary } = resolveElectronBinary();
const fake = desktop();
+ prepare?.(fake);
const server = createLanServer({ handler: fake.workspace, assets: await assets() });
const { port } = await server.start("127.0.0.1", 0);
server.issueCode();
@@ -510,3 +511,50 @@ test("the shipped Markdown renderer keeps GFM structure and defuses unsafe input
assert.equal(result.heading, "<h2>Title</h2>");
assert.equal(result.softBreak, "<p>one\ntwo<br>three</p>");
});
+
+const archivedProjectJourney = String.raw`(async () => {
+ const wait = async (check, label) => {
+ const deadline = performance.now() + 5000;
+ while (!check()) {
+ if (performance.now() > deadline) throw new Error("Timed out waiting for " + label);
+ await new Promise(requestAnimationFrame);
+ }
+ };
+ const view = () => document.getElementById("app").dataset.view;
+ const tap = (control) => {
+ control.scrollIntoView({ block: "center" });
+ const bounds = control.getBoundingClientRect();
+ const hit = document.elementFromPoint(bounds.left + bounds.width / 2, bounds.top + bounds.height / 2);
+ if (!hit || !control.contains(hit)) throw new Error("Pointer blocked by " + (hit?.id || hit?.className || "no target"));
+ hit.click();
+ };
+ await wait(() => document.getElementById("pair-code")?.value === window.__code, "scanned code");
+ document.querySelector('.pair button[type="submit"]').click();
+ await wait(() => view() === "home", "home");
+ location.hash = "#/s/s-a1";
+ await wait(() => view() === "chat:s-a1" && document.querySelector(".msg.user"), "archived conversation");
+ const notice = [...document.querySelectorAll(".notice")].find((node) => node.querySelector("button"));
+ const result = {
+ composer: Boolean(document.getElementById("composer-input")),
+ history: document.querySelector(".msg.user").textContent.includes("hello"),
+ notice: notice?.querySelector(".notice-text")?.textContent ?? null,
+ };
+ tap(notice.querySelector("button"));
+ await wait(() => document.getElementById("composer-input"), "composer after restoring the project");
+ result.noticesAfterRestore = document.querySelectorAll(".notice").length;
+ return JSON.stringify(result);
+})()`;
+
+test("a conversation in an archived project stays readable and continues after restoring the project", { timeout: 60_000 }, async (t) => {
+ const { result, fake } = await runPhone(t, archivedProjectJourney, {
+ scan: true,
+ prepare: (fake) => { fake.meta.projectMeta["/work/a"] = { archived: true }; },
+ });
+ assert.equal(result.composer, false, "no Send or Queue while the project is archived");
+ assert.equal(result.history, true);
+ assert.match(result.notice, /project is archived|项目已归档/);
+ assert.equal(result.noticesAfterRestore, 0);
+ assert.equal(fake.meta.projectMeta["/work/a"].archived, false);
+ assert.equal(fake.meta.sessionMeta["s-a1"], undefined, "restoring the project leaves the session's own state alone");
+ assert.equal(fake.turns.length, 0);
+});
diff --git a/crates/host-core/src/background_tasks/continuations.rs b/crates/host-core/src/background_tasks/continuations.rs
index 33f7e4e07..755be145e 100644
--- a/crates/host-core/src/background_tasks/continuations.rs
+++ b/crates/host-core/src/background_tasks/continuations.rs
@@ -85,6 +85,18 @@ pub fn authorize_registration(
"The originating turn is no longer running".into(),
));
}
+ // The continuation starts a later Desktop turn under the session mode, so
+ // a turn held to a remote permission ceiling cannot arrange one.
+ if crate::turn_permissions::for_call(st.db.conn(), session_id, Some(turn_id))
+ .map_err(|e| internal(e.to_string()))?
+ .is_some()
+ {
+ return Err((
+ "PERMISSION_DENIED".into(),
+ "Automatic continuation is unavailable under a remote permission ceiling; use TaskWait instead"
+ .into(),
+ ));
+ }
if st
.background_tasks
.continuations
diff --git a/crates/host-core/src/db.rs b/crates/host-core/src/db.rs
index 944f7a1f1..d4cee4b9a 100644
--- a/crates/host-core/src/db.rs
+++ b/crates/host-core/src/db.rs
@@ -7,7 +7,7 @@ pub(crate) use serde_json::Value;
pub(crate) use std::path::{Path, PathBuf};
/// Current SQLite schema version.
-pub const SCHEMA_VERSION: i64 = 34;
+pub const SCHEMA_VERSION: i64 = 35;
/// Absolute approval deadline for a newly submitted Plan or Goal proposal.
pub const PLAN_APPROVAL_TIMEOUT_MS: i64 = 30 * 60 * 1000;
@@ -33,6 +33,7 @@ mod session_fast_mode_migration;
mod session_mode_migration;
mod session_title_source_migration;
mod tool_image_storage_migration;
+mod turn_permission_ceiling_migration;
mod worktree_migration;
pub(crate) use migrations::{
archive_legacy_db, create_migration_backup, migrate_and_validate_top_level_mode,
diff --git a/crates/host-core/src/db/completion_report_migration_tests.rs b/crates/host-core/src/db/completion_report_migration_tests.rs
index b273a0b10..cf2662f3a 100644
--- a/crates/host-core/src/db/completion_report_migration_tests.rs
+++ b/crates/host-core/src/db/completion_report_migration_tests.rs
@@ -54,6 +54,11 @@ fn populated_v30(path: &Path, preexisting_report: bool) {
tx.commit().unwrap();
}
+/// Queue columns that predate schema 35; that migration adds the ceiling.
+const LEGACY_QUEUE: &str = "SELECT id,session_id,principal,idempotency_key,input_hash,content,
+ attachments_json,session_message_id,user_message_id,permission_mode,position,priority,
+ voice_origin_json,created_at,start_goal FROM turn_queue";
+
const LEGACY_RUN: &str = "SELECT id,session_id,mode_id,snapshot_hash,input,stage_id,state,wait_reason,last_error,
revision,active_turn_id,active_origin,stage_entered,advanced_in_turn,pending_gate,retry_counts,
rounds_completed,tokens_used,max_turns,max_tokens,artifact_paths,settled_turns,created_at,updated_at,
@@ -69,7 +74,7 @@ fn completion_report_migration_populated_30_preserves_all_data_and_pre_migration
let gates = rows(&before, "SELECT * FROM mode_gate_results");
let snapshots = rows(&before, "SELECT * FROM mode_snapshots");
let sessions = rows(&before, "SELECT * FROM sessions");
- let queue = rows(&before, "SELECT * FROM turn_queue");
+ let queue = rows(&before, LEGACY_QUEUE);
let turns = rows(&before, "SELECT * FROM turns");
drop(before);
let db = Database::open(&path).unwrap();
@@ -79,7 +84,7 @@ fn completion_report_migration_populated_30_preserves_all_data_and_pre_migration
assert_eq!(rows(db.conn(), "SELECT * FROM mode_gate_results"), gates);
assert_eq!(rows(db.conn(), "SELECT * FROM mode_snapshots"), snapshots);
assert_eq!(rows(db.conn(), "SELECT * FROM sessions"), sessions);
- assert_eq!(rows(db.conn(), "SELECT * FROM turn_queue"), queue);
+ assert_eq!(rows(db.conn(), LEGACY_QUEUE), queue);
assert_eq!(rows(db.conn(), "SELECT * FROM turns"), turns);
assert_eq!(
rows(db.conn(), "SELECT completion_report_json FROM mode_runs"),
@@ -91,7 +96,7 @@ fn completion_report_migration_populated_30_preserves_all_data_and_pre_migration
assert!(!has_report(&backup));
assert_eq!(rows(&backup, LEGACY_RUN), old_run);
assert_eq!(rows(&backup, "SELECT * FROM mode_gate_results"), gates);
- assert_eq!(rows(&backup, "SELECT * FROM turn_queue"), queue);
+ assert_eq!(rows(&backup, LEGACY_QUEUE), queue);
// The old CHECK still rejects blocked; the upgraded one permits it only while waiting.
assert!(backup
.execute("UPDATE mode_runs SET wait_reason='blocked'", [])
diff --git a/crates/host-core/src/db/repositories.rs b/crates/host-core/src/db/repositories.rs
index 904b00405..4378a27cf 100644
--- a/crates/host-core/src/db/repositories.rs
+++ b/crates/host-core/src/db/repositories.rs
@@ -150,6 +150,7 @@ impl Database {
tx.execute_batch(super::MODE_RUNS_SCHEMA)?;
super::mode_run_elapsed_migration::initialize(&tx)?;
super::completion_report_migration::initialize(&tx)?;
+ super::turn_permission_ceiling_migration::initialize(&tx)?;
tx.pragma_update(None, "user_version", SCHEMA_VERSION)?;
tx.commit()?;
}
@@ -226,6 +227,7 @@ impl Database {
31 => {}
32 => {}
33 => {}
+ 34 => {}
legacy @ 1..=6 => {
let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");
drop(conn);
@@ -317,6 +319,10 @@ impl Database {
if version == 33 {
super::model_discovery_migration::migrate_reported_context_window(&conn, path)?;
}
+ let version: i64 = conn.query_row("PRAGMA user_version", [], |r| r.get(0))?;
+ if version == 34 {
+ super::turn_permission_ceiling_migration::migrate(&conn, path)?;
+ }
let db = Self { conn, data_dir };
db.boot_maintenance()?;
crate::session_collaboration::recover(&db)?;
diff --git a/crates/host-core/src/db/turn_permission_ceiling_migration.rs b/crates/host-core/src/db/turn_permission_ceiling_migration.rs
new file mode 100644
index 000000000..bb08b9c21
--- /dev/null
+++ b/crates/host-core/src/db/turn_permission_ceiling_migration.rs
@@ -0,0 +1,139 @@
+//! Schema 35: the per-turn permission ceiling (remote-control spec §7.3).
+//!
+//! `turns.permission_ceiling` holds the ceiling a turn was admitted under and
+//! `turn_queue.permission_ceiling` carries it while the turn waits. NULL means
+//! no ceiling: every turn and queued entry that predates the column keeps its
+//! existing behavior, except as noted below.
+
+use super::{create_migration_backup, Connection, Context, Path, Result};
+use rusqlite::Transaction;
+
+const CEILING_CHECK: &str = "CHECK (permission_ceiling IN ('ask', 'accept-edits', 'auto'))";
+
+/// Shared by fresh initialization and the additive v34 -> v35 migration.
+pub(super) fn initialize(tx: &Transaction<'_>) -> Result<()> {
+ for table in ["turns", "turn_queue"] {
+ let exists: bool = tx.query_row(
+ "SELECT EXISTS(SELECT 1 FROM pragma_table_info(?1) WHERE name = 'permission_ceiling')",
+ [table],
+ |row| row.get(0),
+ )?;
+ if !exists {
+ tx.execute_batch(&format!(
+ "ALTER TABLE {table} ADD COLUMN permission_ceiling TEXT {CEILING_CHECK};"
+ ))?;
+ }
+ }
+ Ok(())
+}
+
+pub(super) fn migrate(conn: &Connection, path: &Path) -> Result<()> {
+ let backup = create_migration_backup(conn, path, 34)?;
+ let tx = conn.unchecked_transaction()?;
+ initialize(&tx)?;
+ // An entry queued before this version recorded the mode it was admitted
+ // under but not whether a ceiling bound it. Treat that mode as its
+ // ceiling so a restored remote entry cannot start broader than admitted.
+ tx.execute_batch(
+ "UPDATE turn_queue SET permission_ceiling = CASE
+ WHEN permission_mode IN ('accept-edits', 'auto') THEN permission_mode
+ ELSE 'ask' END
+ WHERE permission_ceiling IS NULL;",
+ )?;
+ tx.pragma_update(None, "user_version", 35i64)?;
+ tx.commit().with_context(|| {
+ format!(
+ "commit schema v34 to v35 turn permission ceiling migration; backup {} remains",
+ backup.display()
+ )
+ })?;
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::db::{migration_backup_path, Database, SCHEMA_VERSION};
+ use rusqlite::Connection;
+
+ fn version(conn: &Connection) -> i64 {
+ conn.query_row("PRAGMA user_version", [], |row| row.get(0))
+ .unwrap()
+ }
+
+ #[test]
+ fn v34_upgrade_keeps_turns_and_bounds_restored_queue_entries() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("pi.sqlite");
+ let db = Database::open(&path).unwrap();
+ db.conn()
+ .execute_batch(
+ "ALTER TABLE turns DROP COLUMN permission_ceiling;
+ ALTER TABLE turn_queue DROP COLUMN permission_ceiling;
+ INSERT INTO sessions(id, title, mode, created_at, updated_at)
+ VALUES ('s', 'legacy', 'agent', 1, 2);
+ INSERT INTO turns(id, session_id, status, started_at, ended_at)
+ VALUES ('old-turn', 's', 'completed', 1, 2);
+ INSERT INTO turn_queue(id, session_id, principal, input_hash, content,
+ permission_mode, position, created_at)
+ VALUES ('q-ask', 's', 'lan:device', 'h1', 'from phone', 'ask', 1, 2),
+ ('q-auto', 's', 'desktop', 'h2', 'from desktop', 'auto', 2, 3),
+ ('q-odd', 's', 'other', 'h3', 'unknown mode', 'inherit', 3, 4);
+ PRAGMA user_version = 34;",
+ )
+ .unwrap();
+ drop(db);
+
+ let upgraded = Database::open(&path).unwrap();
+ assert_eq!(version(upgraded.conn()), SCHEMA_VERSION);
+ let turn: (String, Option<String>) = upgraded
+ .conn()
+ .query_row(
+ "SELECT status, permission_ceiling FROM turns WHERE id = 'old-turn'",
+ [],
+ |row| Ok((row.get(0)?, row.get(1)?)),
+ )
+ .unwrap();
+ assert_eq!(turn, ("completed".into(), None));
+ let queue: Vec<(String, String, String)> = upgraded
+ .conn()
+ .prepare(
+ "SELECT id, permission_mode, permission_ceiling FROM turn_queue ORDER BY position",
+ )
+ .unwrap()
+ .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
+ .unwrap()
+ .collect::<rusqlite::Result<_>>()
+ .unwrap();
+ assert_eq!(
+ queue,
+ vec![
+ ("q-ask".into(), "ask".into(), "ask".into()),
+ ("q-auto".into(), "auto".into(), "auto".into()),
+ ("q-odd".into(), "inherit".into(), "ask".into()),
+ ]
+ );
+ assert!(upgraded
+ .conn()
+ .execute("UPDATE turns SET permission_ceiling = 'inherit'", [])
+ .is_err());
+ let backup = Connection::open(migration_backup_path(&path, 34)).unwrap();
+ assert_eq!(version(&backup), 34);
+ }
+
+ #[test]
+ fn a_fresh_database_starts_with_the_ceiling_columns() {
+ let dir = tempfile::tempdir().unwrap();
+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
+ for table in ["turns", "turn_queue"] {
+ let exists: bool = db
+ .conn()
+ .query_row(
+ "SELECT EXISTS(SELECT 1 FROM pragma_table_info(?1) WHERE name = 'permission_ceiling')",
+ [table],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert!(exists, "{table}");
+ }
+ }
+}
diff --git a/crates/host-core/src/main.rs b/crates/host-core/src/main.rs
index dac993378..cea9a37e8 100644
--- a/crates/host-core/src/main.rs
+++ b/crates/host-core/src/main.rs
@@ -35,6 +35,7 @@ mod todos;
mod tool_budget;
mod tools;
mod transcripts;
+mod turn_permissions;
mod turn_queue;
mod user_skills;
mod user_subagents;
diff --git a/crates/host-core/src/mode_runs.rs b/crates/host-core/src/mode_runs.rs
index d6b4fdc16..07ce4105d 100644
--- a/crates/host-core/src/mode_runs.rs
+++ b/crates/host-core/src/mode_runs.rs
@@ -28,7 +28,7 @@ pub use engine::{
};
pub use gates::{complete_stage, gate_result, GateExecution, GateExecutions};
pub use model::{CompleteStageParams, GateResultParams, ModeRun, SessionParams, StartParams};
-pub use policy::{authorization, tool_policy, tool_policy_conn, ToolPolicy};
+pub use policy::{authorization, tool_policy, tool_policy_conn, Authorization, ToolPolicy};
pub use return_mode::settle_return;
/// Mode ids are `^[a-z][a-z0-9-]{0,39}$`, shared with `MODE_ID_RE` in
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index 6fc949697..72bae4d49 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -33,6 +33,8 @@ mod plugin_reviews_rpc_tests;
#[cfg(test)]
mod review_rpc_tests;
#[cfg(test)]
+mod turn_permission_tests;
+#[cfg(test)]
mod visualization_tests;
#[cfg(test)]
mod write_scope_tests;
@@ -64,6 +66,7 @@ use crate::sessions::{self, UiMessage};
use crate::state::{AppState, HOST_VERSION, PROTOCOL_VERSION};
use crate::tools::{self, ToolsExecuteParams};
use crate::transcripts::{self, CompactionRecord};
+use crate::turn_permissions;
use crate::turn_queue;
use crate::visualizations;
use crate::workspace::{self, ContainedRoots, ToolRoot};
@@ -2866,9 +2869,10 @@ async fn handle_request(
if let Some(project) = isolated_project.as_deref() {
worktree_rpc::ensure_local_project(&st.db, project)?;
}
+ // A child started during a ceiling-bound parent turn starts no broader.
let permission_mode = if let Some(parent_id) = permission_parent {
Some(
- sessions::session_permission_mode(&st.db, &parent_id)
+ turn_permissions::inherited_mode(&st.db, &parent_id)
.map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
.ok_or_else(|| rpc_err(1007, "parent session not found", "NOT_FOUND"))?,
)
@@ -3566,6 +3570,8 @@ async fn handle_request(
.get("sessionId")
.and_then(|v| v.as_str())
.ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
+ let ceiling = turn_permissions::parse_ceiling(params.get("permissionCeiling"))
+ .map_err(|message| rpc_err(1002, message, "INVALID_PARAMS"))?;
let st = state.lock().await;
let provider = params.get("providerId").and_then(Value::as_str);
let model = params.get("modelId").and_then(Value::as_str);
@@ -3576,7 +3582,26 @@ async fn handle_request(
None => sessions::begin_turn(&st.db, session_id, provider, model),
}
.map_err(session_collaboration_rpc_err)?;
- Ok(json!({ "turnId": turn_id }))
+ if let Some(ceiling) = ceiling.as_deref() {
+ // A turn that cannot hold its ceiling must not run at all.
+ if let Err(error) = turn_permissions::record(st.db.conn(), &turn_id, ceiling) {
+ let code = "PERMISSION_CEILING_UNAVAILABLE";
+ let mut message = error.to_string();
+ if let Err(end_error) = sessions::end_turn_settling(
+ &st.db,
+ &turn_id,
+ "error",
+ Some(code),
+ None,
+ false,
+ false,
+ ) {
+ message = format!("{message}; closing the turn failed: {end_error}");
+ }
+ return Err(rpc_err(1000, message, code));
+ }
+ }
+ Ok(json!({ "turnId": turn_id, "permissionCeiling": ceiling }))
}
"session.recordUsage" => {
let session_id = params
@@ -4436,39 +4461,18 @@ async fn handle_request(
if st.shutting_down {
return Err(rpc_err(1001, "host is shutting down", "HOST_SHUTTING_DOWN"));
}
- // Effective permission mode (D115): per-session override
- // unless it is `inherit`, then the global settings default,
- // then `ask`. A subagent's tool call carries its own scope
- // (ADR 0089), which resolves the call under that mode
- // instead; external-path gating and the contract modes'
- // hard deny are untouched by the override.
- let session_pm = sessions::session_permission_mode(&st.db, &p.session_id)
- .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
- .filter(|m| m != "inherit");
- let effective_pm = match session_pm {
- Some(m) => m,
- None => st
- .db
- .get_setting("app")
- .ok()
- .flatten()
- .and_then(|s| {
- s.get("defaultPermissionMode")
- .and_then(|v| v.as_str())
- .map(str::to_string)
- })
- .filter(|m| sessions::is_valid_permission_mode(m) && m != "inherit")
- .unwrap_or_else(|| "ask".to_string()),
- };
- let effective_pm = match p.permission_scope.as_deref() {
- Some(scope)
- if sessions::is_valid_permission_mode(scope) && scope != "inherit" =>
- {
- scope.to_string()
- }
- _ => effective_pm,
- };
- let effective_pm = authorization.cap_permission_mode(effective_pm);
+ // Effective permission mode (D115): the session mode, or a
+ // subagent's own scope (ADR 0089), then the ceiling of the
+ // turn the call belongs to. External-path gating and the
+ // contract modes' hard deny are untouched by either.
+ let effective_pm = turn_permissions::effective_tool_mode(
+ &st.db,
+ &p.session_id,
+ p.turn_id.as_deref(),
+ p.permission_scope.as_deref(),
+ &authorization,
+ )
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
let (ws, _) = file_batches::resolve_root(&st, &p)?;
let scratch = scratch::session_dir(&st.data_dir, &p.session_id);
let contained_roots = if workspace_only {
@@ -5252,27 +5256,14 @@ async fn handle_request(
else {
return Err(rpc_err(1007, "session not found", "SESSION_NOT_FOUND"));
};
- let session_pm = sessions::session_permission_mode(&st.db, session_id)
- .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
- .filter(|value| value != "inherit");
- let effective_pm = session_pm
- .or_else(|| {
- st.db
- .get_setting("app")
- .ok()
- .flatten()
- .and_then(|settings| {
- settings
- .get("defaultPermissionMode")
- .and_then(|value| value.as_str())
- .filter(|value| {
- sessions::is_valid_permission_mode(value) && *value != "inherit"
- })
- .map(str::to_string)
- })
- })
- .unwrap_or_else(|| "ask".into());
- let effective_pm = authorization.cap_permission_mode(effective_pm);
+ let effective_pm = turn_permissions::effective_tool_mode(
+ &st.db,
+ session_id,
+ params.get("turnId").and_then(Value::as_str),
+ None,
+ &authorization,
+ )
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
let args = params.get("args").cloned().unwrap_or_else(|| json!({}));
let workspace_path = resolve_tool_workspace_for_call(&st, session_id, &args)?;
let external_path_permission =
diff --git a/crates/host-core/src/rpc/turn_permission_tests.rs b/crates/host-core/src/rpc/turn_permission_tests.rs
new file mode 100644
index 000000000..a381f6486
--- /dev/null
+++ b/crates/host-core/src/rpc/turn_permission_tests.rs
@@ -0,0 +1,250 @@
+//! The per-turn permission ceiling through the real RPC and permission gate.
+use super::*;
+use std::fs;
+
+struct Fixture {
+ _dir: tempfile::TempDir,
+ state: Arc<Mutex<AppState>>,
+ root: PathBuf,
+ session_id: String,
+}
+
+impl Fixture {
+ /// A local Agent session whose stored mode is `auto`.
+ async fn new() -> Self {
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path().join("project");
+ fs::create_dir(&root).unwrap();
+ let mut app = AppState::open(&dir.path().join("data")).unwrap();
+ app.handshook = true;
+ let state = Arc::new(Mutex::new(app));
+ let session = handle_request(
+ state.clone(),
+ "session.create",
+ json!({ "projectPath": root, "mode": "agent" }),
+ mpsc::unbounded_channel().0,
+ )
+ .await
+ .unwrap();
+ let fixture = Self {
+ _dir: dir,
+ state,
+ root: PathBuf::from(session["session"]["projectPath"].as_str().unwrap()),
+ session_id: session["session"]["id"].as_str().unwrap().to_owned(),
+ };
+ sessions::configure_session_with_thinking(
+ &fixture.state.lock().await.db,
+ &fixture.session_id,
+ "agent",
+ None,
+ None,
+ None,
+ Some("auto"),
+ )
+ .unwrap();
+ fixture
+ }
+
+ async fn rpc(&self, method: &str, params: Value) -> Result<Value, JsonRpcError> {
+ handle_request(
+ self.state.clone(),
+ method,
+ params,
+ mpsc::unbounded_channel().0,
+ )
+ .await
+ }
+
+ async fn begin(&self, ceiling: Option<&str>) -> String {
+ let mut params = json!({ "sessionId": self.session_id });
+ if let Some(ceiling) = ceiling {
+ params["permissionCeiling"] = json!(ceiling);
+ }
+ let begun = self.rpc("session.beginTurn", params).await.unwrap();
+ assert_eq!(begun["permissionCeiling"], json!(ceiling));
+ begun["turnId"].as_str().unwrap().to_owned()
+ }
+
+ async fn end(&self, turn_id: &str) {
+ self.rpc(
+ "session.endTurn",
+ json!({ "turnId": turn_id, "createNotification": false }),
+ )
+ .await
+ .unwrap();
+ }
+
+ /// Start a Write and return the approval request it raised, if any.
+ async fn write(
+ &self,
+ turn_id: &str,
+ call: &str,
+ scope: Option<&str>,
+ ) -> (
+ tokio::task::JoinHandle<Result<Value, JsonRpcError>>,
+ Option<String>,
+ ) {
+ let mut params = json!({
+ "sessionId": self.session_id,
+ "turnId": turn_id,
+ "toolCallId": call,
+ "toolName": "Write",
+ "args": { "path": format!("{call}.txt"), "content": "fixture" },
+ "mode": "agent",
+ });
+ if let Some(scope) = scope {
+ params["permissionScope"] = json!(scope);
+ }
+ let (tx, mut rx) = mpsc::unbounded_channel();
+ let state = self.state.clone();
+ let pending =
+ tokio::spawn(async move { handle_request(state, "tools.execute", params, tx).await });
+ let request = match tokio::time::timeout(Duration::from_millis(500), rx.recv()).await {
+ Ok(Some(text)) => {
+ let notification: Value = serde_json::from_str(&text).unwrap();
+ assert_eq!(notification["method"], "permissions.request");
+ Some(
+ notification["params"]["requestId"]
+ .as_str()
+ .unwrap()
+ .to_owned(),
+ )
+ }
+ _ => None,
+ };
+ (pending, request)
+ }
+
+ /// Permission mode of a new session inheriting from this one.
+ async fn child_mode(&self) -> Value {
+ let created = self
+ .rpc(
+ "session.create",
+ json!({ "projectPath": self.root, "inheritPermissionFromSessionId": self.session_id }),
+ )
+ .await
+ .unwrap();
+ created["session"]["permissionMode"].clone()
+ }
+
+ async fn resolve(&self, request_id: &str, decision: &str) {
+ self.rpc(
+ "permissions.resolve",
+ json!({ "requestId": request_id, "decision": decision }),
+ )
+ .await
+ .unwrap();
+ }
+}
+
+#[tokio::test]
+async fn a_phone_turn_asks_desktop_in_an_auto_session_and_leaves_the_session_unchanged() {
+ let fixture = Fixture::new().await;
+ let phone = fixture.begin(Some("ask")).await;
+
+ // Denied: the gated write has no side effect.
+ let (pending, request) = fixture.write(&phone, "denied", None).await;
+ fixture
+ .resolve(
+ request.as_deref().expect("the ceiling requires approval"),
+ "deny",
+ )
+ .await;
+ let denied = pending.await.unwrap().unwrap();
+ assert_eq!(denied["errorCode"], "TOOL_DENIED");
+ assert!(!fixture.root.join("denied.txt").exists());
+
+ // A delegate's own broader scope cannot lift the turn's ceiling.
+ let (pending, request) = fixture.write(&phone, "delegated", Some("auto")).await;
+ fixture
+ .resolve(
+ request.as_deref().expect("a delegate still asks"),
+ "allow-once",
+ )
+ .await;
+ assert_eq!(pending.await.unwrap().unwrap()["ok"], true);
+ assert!(fixture.root.join("delegated.txt").exists());
+
+ // Delegated work that outlives the phone turn keeps answering to it.
+ fixture.end(&phone).await;
+ let desktop = fixture.begin(None).await;
+ let (pending, request) = fixture.write(&phone, "late-delegate", None).await;
+ fixture
+ .resolve(
+ request.as_deref().expect("the ended phone turn still asks"),
+ "deny",
+ )
+ .await;
+ assert_eq!(pending.await.unwrap().unwrap()["errorCode"], "TOOL_DENIED");
+
+ // The next Desktop turn runs under the unchanged session setting.
+ let (pending, request) = fixture.write(&desktop, "desktop", None).await;
+ assert!(request.is_none(), "an auto Desktop turn must not prompt");
+ assert_eq!(pending.await.unwrap().unwrap()["ok"], true);
+ let stored =
+ sessions::session_permission_mode(&fixture.state.lock().await.db, &fixture.session_id)
+ .unwrap();
+ assert_eq!(stored.as_deref(), Some("auto"));
+ let evaluated = fixture
+ .rpc(
+ "permissions.evaluate",
+ json!({ "sessionId": fixture.session_id, "turnId": phone, "toolName": "Write" }),
+ )
+ .await
+ .unwrap();
+ assert!(evaluated["decision"].is_null(), "{evaluated}");
+}
+
+#[tokio::test]
+async fn an_unusable_ceiling_starts_no_turn() {
+ let fixture = Fixture::new().await;
+ let error = fixture
+ .rpc(
+ "session.beginTurn",
+ json!({ "sessionId": fixture.session_id, "permissionCeiling": "inherit" }),
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(error.data.unwrap()["errorCode"], "INVALID_PARAMS");
+ // No running turn was left behind: the session can still begin one.
+ fixture.begin(Some("ask")).await;
+}
+
+#[tokio::test]
+async fn a_session_created_during_a_phone_turn_starts_no_broader() {
+ let fixture = Fixture::new().await;
+ assert_eq!(fixture.child_mode().await, "auto");
+ let phone = fixture.begin(Some("ask")).await;
+ assert_eq!(fixture.child_mode().await, "ask");
+ fixture.end(&phone).await;
+ assert_eq!(fixture.child_mode().await, "auto");
+}
+
+#[tokio::test]
+async fn a_phone_turn_cannot_arrange_an_automatic_desktop_continuation() {
+ let fixture = Fixture::new().await;
+ fixture
+ .state
+ .lock()
+ .await
+ .db
+ .set_setting("app", &json!({ "backgroundJobContinuationEnabled": true }))
+ .unwrap();
+ let phone = fixture.begin(Some("ask")).await;
+ let error = fixture
+ .rpc(
+ "tools.execute",
+ json!({
+ "sessionId": fixture.session_id,
+ "turnId": phone,
+ "toolCallId": "background",
+ "toolName": "Bash",
+ "args": { "command": "true", "runInBackground": true, "notifyOnExit": true },
+ "runInBackground": true,
+ "mode": "agent",
+ }),
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(error.data.unwrap()["errorCode"], "PERMISSION_DENIED");
+}
diff --git a/crates/host-core/src/session_collaboration/mod.rs b/crates/host-core/src/session_collaboration/mod.rs
index a72fd3cad..227870a2b 100644
--- a/crates/host-core/src/session_collaboration/mod.rs
+++ b/crates/host-core/src/session_collaboration/mod.rs
@@ -65,7 +65,11 @@ fn send_record(db: &Database, input: &Value, target: &str, kind: &str) -> Result
"PERMISSION_DENIED: session communication requires Agent mode"
));
}
- let permission_ceiling = permissions::effective_mode(db, source)?;
+ // A message sent during a ceiling-bound turn carries that turn's ceiling.
+ let permission_ceiling = crate::turn_permissions::clamp(
+ permissions::effective_mode(db, source)?,
+ crate::turn_permissions::for_call(db.conn(), source, None)?.as_deref(),
+ );
permissions::check_target(db, target, &permission_ceiling)?;
let pending: i64 = db.conn().query_row(
"SELECT COUNT(*) FROM session_collaboration_messages
diff --git a/crates/host-core/src/turn_permissions.rs b/crates/host-core/src/turn_permissions.rs
new file mode 100644
index 000000000..8609fe8a3
--- /dev/null
+++ b/crates/host-core/src/turn_permissions.rs
@@ -0,0 +1,287 @@
+//! Per-turn permission ceiling (remote-control spec §7.3, LAN WebUI W06).
+//!
+//! A turn admitted for a principal under the remote ceiling (a paired LAN
+//! browser or a Gateway-routed client) records that ceiling on its durable
+//! turn row when it begins. Tool authorization resolves the session mode as
+//! before and then applies the stricter of that mode and the ceiling of the
+//! turn the call belongs to. A ceiling never widens a mode, never rewrites the
+//! session setting and does not apply to any other turn.
+
+use anyhow::{anyhow, Result};
+use rusqlite::{params, Connection, OptionalExtension};
+use serde_json::Value;
+
+use crate::db::Database;
+use crate::mode_runs::Authorization;
+use crate::sessions;
+
+/// Modes a turn ceiling may name, from most to least restrictive.
+pub const CEILING_MODES: [&str; 3] = ["ask", "accept-edits", "auto"];
+
+pub fn is_ceiling_mode(mode: &str) -> bool {
+ CEILING_MODES.contains(&mode)
+}
+
+/// Permissiveness rank. Anything unrecognized ranks as the most restrictive.
+fn rank(mode: &str) -> u8 {
+ match mode {
+ "auto" => 2,
+ "accept-edits" => 1,
+ _ => 0,
+ }
+}
+
+/// The stricter of an effective mode and an optional ceiling.
+pub fn clamp(effective: String, ceiling: Option<&str>) -> String {
+ match ceiling {
+ Some(ceiling) if rank(ceiling) < rank(&effective) => ceiling.to_string(),
+ _ => effective,
+ }
+}
+
+/// Parse the optional `permissionCeiling` of `session.beginTurn`. Absent or
+/// `null` means the turn has no ceiling; anything else must be a known mode.
+pub fn parse_ceiling(value: Option<&Value>) -> std::result::Result<Option<String>, String> {
+ match value {
+ None | Some(Value::Null) => Ok(None),
+ Some(Value::String(mode)) if is_ceiling_mode(mode) => Ok(Some(mode.clone())),
+ Some(_) => Err("permissionCeiling must be ask, accept-edits or auto".into()),
+ }
+}
+
+/// Record the ceiling of a turn that has just begun.
+pub fn record(conn: &Connection, turn_id: &str, ceiling: &str) -> Result<()> {
+ if !is_ceiling_mode(ceiling) {
+ return Err(anyhow!("invalid permission ceiling {ceiling}"));
+ }
+ let updated = conn
+ .prepare_cached(
+ "UPDATE turns SET permission_ceiling = ?2 WHERE id = ?1 AND status = 'running'",
+ )?
+ .execute(params![turn_id, ceiling])?;
+ if updated != 1 {
+ return Err(anyhow!("turn {turn_id} is not running"));
+ }
+ Ok(())
+}
+
+/// Ceiling governing one tool call. A call that names a turn of this session
+/// answers to that turn, so delegated work keeps its originating turn's
+/// policy after the turn ends. A call that names no known turn answers to the
+/// session's running turn.
+pub fn for_call(
+ conn: &Connection,
+ session_id: &str,
+ turn_id: Option<&str>,
+) -> Result<Option<String>> {
+ if let Some(turn_id) = turn_id.map(str::trim).filter(|id| !id.is_empty()) {
+ let named: Option<Option<String>> = conn
+ .prepare_cached(
+ "SELECT permission_ceiling FROM turns WHERE id = ?1 AND session_id = ?2",
+ )?
+ .query_row(params![turn_id, session_id], |row| row.get(0))
+ .optional()?;
+ if let Some(ceiling) = named {
+ return Ok(ceiling);
+ }
+ }
+ Ok(conn
+ .prepare_cached(
+ "SELECT permission_ceiling FROM turns WHERE session_id = ?1 AND status = 'running'",
+ )?
+ .query_row(params![session_id], |row| row.get::<_, Option<String>>(0))
+ .optional()?
+ .flatten())
+}
+
+/// The session's own mode: its override unless `inherit`, then the global
+/// default, then `ask`.
+fn session_mode(db: &Database, session_id: &str) -> Result<String> {
+ let own = sessions::session_permission_mode(db, session_id)?.filter(|mode| mode != "inherit");
+ Ok(own.unwrap_or_else(|| {
+ db.get_setting("app")
+ .ok()
+ .flatten()
+ .and_then(|settings| {
+ settings
+ .get("defaultPermissionMode")
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ })
+ .filter(|mode| sessions::is_valid_permission_mode(mode) && mode != "inherit")
+ .unwrap_or_else(|| "ask".to_string())
+ }))
+}
+
+/// Effective permission mode for one tool call (D115): the session mode, or a
+/// subagent's own scope (ADR 0089), capped for unattended staged modes and
+/// then by the ceiling of the turn the call belongs to.
+pub fn effective_tool_mode(
+ db: &Database,
+ session_id: &str,
+ turn_id: Option<&str>,
+ permission_scope: Option<&str>,
+ authorization: &Authorization,
+) -> Result<String> {
+ let mode = match permission_scope {
+ Some(scope) if sessions::is_valid_permission_mode(scope) && scope != "inherit" => {
+ scope.to_string()
+ }
+ _ => session_mode(db, session_id)?,
+ };
+ let mode = authorization.cap_permission_mode(mode);
+ Ok(clamp(
+ mode,
+ for_call(db.conn(), session_id, turn_id)?.as_deref(),
+ ))
+}
+
+/// Permission mode a new session inherits from `parent_id`. While the parent
+/// runs a ceiling-bound turn, the child cannot start broader than that turn.
+pub fn inherited_mode(db: &Database, parent_id: &str) -> Result<Option<String>> {
+ let Some(stored) = sessions::session_permission_mode(db, parent_id)? else {
+ return Ok(None);
+ };
+ let Some(ceiling) = for_call(db.conn(), parent_id, None)? else {
+ return Ok(Some(stored));
+ };
+ Ok(Some(clamp(session_mode(db, parent_id)?, Some(&ceiling))))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::mode_runs;
+
+ fn session(db: &Database, mode: &str) -> String {
+ let created =
+ sessions::create_session(db, None, Some("agent".into()), None, None, None).unwrap();
+ sessions::configure_session_with_thinking(
+ db,
+ &created.id,
+ "agent",
+ None,
+ None,
+ None,
+ Some(mode),
+ )
+ .unwrap();
+ created.id
+ }
+
+ fn authorization(db: &Database, session_id: &str) -> Authorization {
+ mode_runs::authorization(db, session_id).unwrap().unwrap()
+ }
+
+ #[test]
+ fn clamp_only_narrows() {
+ assert_eq!(clamp("auto".into(), Some("ask")), "ask");
+ assert_eq!(clamp("accept-edits".into(), Some("auto")), "accept-edits");
+ assert_eq!(clamp("ask".into(), Some("auto")), "ask");
+ assert_eq!(clamp("auto".into(), None), "auto");
+ // An unknown ceiling is the most restrictive, never a widening.
+ assert_eq!(clamp("ask".into(), Some("unknown")), "ask");
+ }
+
+ #[test]
+ fn parse_ceiling_accepts_only_known_modes() {
+ assert_eq!(parse_ceiling(None), Ok(None));
+ assert_eq!(parse_ceiling(Some(&Value::Null)), Ok(None));
+ assert_eq!(
+ parse_ceiling(Some(&Value::from("ask"))),
+ Ok(Some("ask".into()))
+ );
+ assert!(parse_ceiling(Some(&Value::from("inherit"))).is_err());
+ assert!(parse_ceiling(Some(&Value::from(1))).is_err());
+ }
+
+ #[test]
+ fn a_ceiling_governs_its_own_turn_and_outlives_it_only_for_that_turn() {
+ let dir = tempfile::tempdir().unwrap();
+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
+ let session_id = session(&db, "auto");
+ let phone_turn = sessions::begin_turn(&db, &session_id, None, None).unwrap();
+ record(db.conn(), &phone_turn, "ask").unwrap();
+
+ let auth = authorization(&db, &session_id);
+ let mode = |turn: Option<&str>, scope: Option<&str>| {
+ effective_tool_mode(&db, &session_id, turn, scope, &auth).unwrap()
+ };
+ assert_eq!(mode(Some(&phone_turn), None), "ask");
+ // A call without a turn, or with a foreign one, answers to the running turn.
+ assert_eq!(mode(None, None), "ask");
+ assert_eq!(mode(Some("unknown-turn"), None), "ask");
+ // A subagent's own scope cannot lift the turn above its ceiling.
+ assert_eq!(mode(Some(&phone_turn), Some("auto")), "ask");
+ // Neither can a later session setting change.
+ sessions::configure_session_with_thinking(
+ &db,
+ &session_id,
+ "agent",
+ None,
+ None,
+ None,
+ Some("auto"),
+ )
+ .unwrap();
+ assert_eq!(mode(Some(&phone_turn), None), "ask");
+
+ sessions::end_turn(&db, &phone_turn, "completed", None, None, false).unwrap();
+ // Delegated work of the finished phone turn keeps its ceiling...
+ assert_eq!(mode(Some(&phone_turn), None), "ask");
+ // ...while the next Desktop turn uses the unchanged session setting.
+ let desktop_turn = sessions::begin_turn(&db, &session_id, None, None).unwrap();
+ assert_eq!(mode(Some(&desktop_turn), None), "auto");
+ assert_eq!(mode(None, None), "auto");
+ assert_eq!(
+ sessions::session_permission_mode(&db, &session_id)
+ .unwrap()
+ .as_deref(),
+ Some("auto")
+ );
+ }
+
+ #[test]
+ fn an_inherited_session_default_is_resolved_before_the_ceiling_applies() {
+ let dir = tempfile::tempdir().unwrap();
+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
+ db.set_setting(
+ "app",
+ &serde_json::json!({ "defaultPermissionMode": "auto" }),
+ )
+ .unwrap();
+ let session_id = session(&db, "inherit");
+ let auth = authorization(&db, &session_id);
+ assert_eq!(
+ effective_tool_mode(&db, &session_id, None, None, &auth).unwrap(),
+ "auto"
+ );
+ let turn = sessions::begin_turn(&db, &session_id, None, None).unwrap();
+ record(db.conn(), &turn, "ask").unwrap();
+ assert_eq!(
+ effective_tool_mode(&db, &session_id, Some(&turn), None, &auth).unwrap(),
+ "ask"
+ );
+ // A child session created during the phone turn starts no broader.
+ assert_eq!(
+ inherited_mode(&db, &session_id).unwrap().as_deref(),
+ Some("ask")
+ );
+ sessions::end_turn(&db, &turn, "completed", None, None, false).unwrap();
+ assert_eq!(
+ inherited_mode(&db, &session_id).unwrap().as_deref(),
+ Some("inherit")
+ );
+ }
+
+ #[test]
+ fn record_refuses_a_turn_that_is_not_running() {
+ let dir = tempfile::tempdir().unwrap();
+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
+ let session_id = session(&db, "auto");
+ let turn = sessions::begin_turn(&db, &session_id, None, None).unwrap();
+ sessions::end_turn(&db, &turn, "completed", None, None, false).unwrap();
+ assert!(record(db.conn(), &turn, "ask").is_err());
+ assert!(record(db.conn(), "missing", "ask").is_err());
+ }
+}
diff --git a/crates/host-core/src/turn_queue.rs b/crates/host-core/src/turn_queue.rs
index 9b392fbf9..5d8a1ab1e 100644
--- a/crates/host-core/src/turn_queue.rs
+++ b/crates/host-core/src/turn_queue.rs
@@ -41,6 +41,10 @@ pub struct QueuedTurnInput {
pub voice_origin: Option<VoiceOrigin>,
pub attachments: Option<Value>,
pub permission_mode: String,
+ /// Host-enforced ceiling of the turn this entry starts (spec §7.3);
+ /// absent when no ceiling binds the admitting principal.
+ #[serde(default)]
+ pub permission_ceiling: Option<String>,
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
@@ -63,6 +67,8 @@ pub struct QueuedTurn {
#[serde(skip_serializing_if = "Option::is_none")]
pub attachments: Option<Value>,
pub permission_mode: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub permission_ceiling: Option<String>,
pub position: i64,
/// Set once the entry is promoted ("send now"). The value is the entry's
/// place inside the session's priority block, so promotions leave in the
@@ -97,6 +103,7 @@ fn row_to_entry(row: &rusqlite::Row<'_>) -> rusqlite::Result<QueuedTurn> {
session_message_id: row.get(10)?,
attachments: attachments.and_then(|text| serde_json::from_str(&text).ok()),
permission_mode: row.get(7)?,
+ permission_ceiling: row.get(15)?,
position: row.get(8)?,
priority: row.get(11)?,
user_message_id: row.get(12)?,
@@ -107,7 +114,7 @@ fn row_to_entry(row: &rusqlite::Row<'_>) -> rusqlite::Result<QueuedTurn> {
const SELECT: &str = "SELECT id, session_id, principal, idempotency_key, input_hash, content,
attachments_json, permission_mode, position, created_at, session_message_id, priority,
- user_message_id, voice_origin_json, start_goal
+ user_message_id, voice_origin_json, start_goal, permission_ceiling
FROM turn_queue";
/// Delivery order: promoted entries first in click order (ascending
@@ -133,6 +140,11 @@ pub fn push(db: &Database, input: QueuedTurnInput) -> Result<QueuedTurn> {
));
}
}
+ if let Some(ceiling) = input.permission_ceiling.as_deref() {
+ if !crate::turn_permissions::is_ceiling_mode(ceiling) {
+ return Err(anyhow!("INVALID_ARGUMENT: invalid permission ceiling"));
+ }
+ }
let conn = db.conn();
let session_exists: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM sessions WHERE id = ?1)",
@@ -187,8 +199,8 @@ pub fn push(db: &Database, input: QueuedTurnInput) -> Result<QueuedTurn> {
"INSERT INTO turn_queue (
id, session_id, principal, idempotency_key, input_hash, content,
attachments_json, permission_mode, position, created_at, session_message_id,
- user_message_id, voice_origin_json, start_goal
- ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)",
+ user_message_id, voice_origin_json, start_goal, permission_ceiling
+ ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)",
params![
id,
input.session_id,
@@ -203,7 +215,8 @@ pub fn push(db: &Database, input: QueuedTurnInput) -> Result<QueuedTurn> {
input.session_message_id,
input.user_message_id,
voice_origin_json,
- input.start_goal
+ input.start_goal,
+ input.permission_ceiling
],
)?;
tx.commit()?;
@@ -220,6 +233,7 @@ pub fn push(db: &Database, input: QueuedTurnInput) -> Result<QueuedTurn> {
voice_origin: input.voice_origin,
attachments: input.attachments,
permission_mode: input.permission_mode,
+ permission_ceiling: input.permission_ceiling,
position: max_position + 1,
priority: None,
created_at: ms_to_ts(created_at),
@@ -393,10 +407,43 @@ mod tests {
voice_origin: None,
attachments: None,
permission_mode: "ask".into(),
+ permission_ceiling: None,
start_goal: false,
}
}
+ #[test]
+ fn a_permission_ceiling_survives_restart_and_is_validated() {
+ let (dir, db, session) = open_with_session();
+ let mut phone = input(&session, "from phone", Some("phone-key"));
+ phone.principal = "lan:device".into();
+ phone.permission_ceiling = Some("ask".into());
+ push(&db, phone).unwrap();
+ push(&db, input(&session, "from desktop", None)).unwrap();
+ let mut invalid = input(&session, "bad", None);
+ invalid.permission_ceiling = Some("inherit".into());
+ assert!(push(&db, invalid)
+ .unwrap_err()
+ .to_string()
+ .starts_with("INVALID_ARGUMENT"));
+ drop(db);
+ let db = Database::open_in_dir(dir.path()).unwrap();
+ let restored = list(&db, Some(&session)).unwrap();
+ assert_eq!(
+ restored
+ .iter()
+ .map(|entry| entry.permission_ceiling.as_deref())
+ .collect::<Vec<_>>(),
+ vec![Some("ask"), None]
+ );
+ let json = serde_json::to_value(&restored[0]).unwrap();
+ assert_eq!(json["permissionCeiling"], "ask");
+ assert!(serde_json::to_value(&restored[1])
+ .unwrap()
+ .get("permissionCeiling")
+ .is_none());
+ }
+
#[test]
fn explicit_goal_identity_survives_restart_and_idempotency() {
let (dir, db, session) = open_with_session();
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 6796724c3..0196e8d84 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -29,6 +29,7 @@ git history.
| lan-webui-code-pairing | [A one-time code pairs a LAN WebUI device directly](lan-webui-code-pairing.md) | Accepted |
| lan-webui-project-access | [Device confirmation grants access to all local LAN WebUI projects](lan-webui-project-access.md) | Superseded |
| lan-webui-session-model-selection | [Paired LAN WebUI devices can select a session model](lan-webui-session-model-selection.md) | Accepted |
+| turn-permission-ceiling | [Host-core enforces the remote permission ceiling per turn](turn-permission-ceiling.md) | Accepted |
| codemode-sandbox-boundary | [Codemode sandbox execution boundary](codemode-sandbox-boundary.md) | Accepted |
| mode-definitions | [User-definable modes as staged workflows](mode-definitions.md) | Proposed |
| sidebar-layout-recovery | [Recover sidebar layout independently of Chromium storage](sidebar-layout-recovery.md) | Accepted |
diff --git a/docs/adr/turn-permission-ceiling.md b/docs/adr/turn-permission-ceiling.md
new file mode 100644
index 000000000..a1ec194ec
--- /dev/null
+++ b/docs/adr/turn-permission-ceiling.md
@@ -0,0 +1,52 @@
+# ADR: Host-core enforces the remote permission ceiling per turn
+
+- Status: Accepted
+- Date: 2026-11-28
+- Related: [Remote-control security §4.3](../spec/05-security/02-remote-control-security.md#43-remote-permission-ceiling), [LAN WebUI MVP](../spec/01-product/03-lan-webui-mvp.md), [LAN WebUI pairing](lan-webui-code-pairing.md)
+
+## Context
+
+The Agent Host computed the remote `ask` ceiling for a paired LAN browser and
+other non-exempt principals, but only as admission metadata. The runtime
+accepted a per-turn `permissionMode` without using it, and host-core
+authorized tools from the session's stored mode. The bridge forwarded the
+value only when it differed from the summarized session mode, so a session
+using `inherit` (summarized as `ask`) with an `auto` default sent nothing at
+all. A phone turn in an `auto` session therefore ran tools without Desktop
+approval. Delegates that outlive their turn also identified themselves by the
+runtime's current turn, not the turn that started them.
+
+## Decision
+
+The ceiling is a property of the durable turn, owned by host-core.
+
+- The Agent Host attaches `permissionCeiling` to every turn admitted for a
+ principal bound by the ceiling, derived from the authenticated principal and
+ Host policy. Exempt principals, including the local Desktop, attach none.
+- `session.beginTurn` records it in `turns.permission_ceiling`; queued turns
+ carry it in `turn_queue.permission_ceiling` (schema v35). Every tool
+ authorization applies the stricter of the session mode current at that
+ decision and the ceiling of the turn the call names, or of the running turn
+ when it names none. Subagent permission scopes, session creation from that
+ turn and session messages sent during it are bounded the same way; it cannot
+ register an automatic background-job continuation, which would start a later
+ Desktop turn.
+- A delegate keeps the turn that started it on its Host calls.
+- A Host that does not confirm the ceiling gets no turn; the WebUI reports
+ `PERMISSION_CEILING_UNAVAILABLE`. The runtime keeps no copy of the ceiling.
+
+## Consequences
+
+Remote turns ask Desktop for approval wherever an `ask` session would, without
+changing the session setting or other turns. Queue entries persisted before
+v35 use their admitted mode as their ceiling, so a restored remote entry cannot
+start broader than it was admitted; a restored Desktop entry may prompt where
+the session has since been raised. Older apps refuse the v35 database, as for
+every schema step; rollback uses the v34 backup.
+
+## Alternatives
+
+- Keep the ceiling in Host memory: lost on host-core restart while the sidecar
+ can still issue calls, so it would fail open.
+- Rewrite the session's stored mode for the turn: changes Desktop's setting
+ and leaks into concurrent and later Desktop turns.
diff --git a/docs/spec/01-product/03-lan-webui-mvp.md b/docs/spec/01-product/03-lan-webui-mvp.md
index 447eef3bd..d2428e862 100644
--- a/docs/spec/01-product/03-lan-webui-mvp.md
+++ b/docs/spec/01-product/03-lan-webui-mvp.md
@@ -92,7 +92,7 @@ already-established cookie for older browser tabs; there is no pending state.
| Project sessions | Enter a project to see its sessions; search by title, open history, rename, pin/unpin, archive/restore. Show running, waiting, interrupted or failed status from the Host. Stable IDs, not names or list positions, distinguish equally named records. Use bounded pages; search is not limited to the first loaded page. |
| New in project | A project's **New session** targets that explicit project, even if the desktop or a second tab is viewing another. Use desktop defaults and the normal local Agent. Only reuse an existing empty conversation if it meets Desktop's pristine, same-scope reuse rule; never attach to a running session or another pending submission. Double-tapping one intent cannot create two sessions. |
| Temporary | Any paired device can list, organize and continue ordinary temporary conversations and create one through the Temporary conversations entry. A temporary conversation has no project and uses normal temporary workspace isolation. It never inherits the last Desktop project. |
-| Archive | Archiving is reversible organization, not deletion, cancellation, folder movement or transcript modification. Inspect archived items via an explicit filter without restoring them. Restore an archived parent project before creating or sending; restore an archived session before sending. Restoring a project preserves each session's own archive/pin state. Decline a web archive if the target session, or a project descendant, is running, queued or waiting for input. Never stop work to make archive succeed. |
+| Archive | Archiving is reversible organization, not deletion, cancellation, folder movement or transcript modification. Inspect archived items via an explicit filter without restoring them. Restore an archived parent project before creating or sending; restore an archived session before sending. A conversation whose project is archived stays readable, names the project as the record to restore, and offers no Send or Queue; the parent's archive is reported separately from the session's own flag. Send and queue check the current archive state at admission, so a stale tab starts no turn. Restoring a project preserves each session's own archive/pin state. Decline a web archive if the target session, or a project descendant, is running, queued, waiting for input or still being admitted from the WebUI; whichever of archive and send is decided first wins. Never stop work to make archive succeed; cancel and stop stay available for already admitted work. |
Only existing locally owned, local-workspace projects and ordinary local Agent
sessions are writable in P0. Local-Agent projects backed by an SSH workspace,
@@ -234,7 +234,10 @@ running work follows the Host incident policy; never silently replay or undo
it. Clear protected views on authorization loss; already seen text cannot be
remotely erased. A web turn never gets the SSH-paired-owner exemption: apply
the lower of session policy and the WebUI `ask` ceiling without changing the
-desktop session setting. A browser cannot approve its own escalation.
+desktop session setting. Host-core enforces that ceiling on every tool decision
+of the turn, including after queueing and for its delegated work; a turn whose
+ceiling cannot be recorded is refused with `PERMISSION_CEILING_UNAVAILABLE` and
+keeps the draft. A browser cannot approve its own escalation.
Session archive is **owner-only** in RACP. The LAN WebUI does not reuse RACP
`session/archive` and never grants a phone the owner role. The WebUI checks
@@ -350,16 +353,18 @@ settings) and `apps/desktop/src/features/lan-webui/lan-catalog-sync.ts`
| Area | Delivered | Not yet |
|---|---|---|
| W01 | Off by default; remembers opt-in, binding and unexpired pairings across launches; one-time-code pairing with copy and QR; explicit disable revokes access | HTTPS (deliberately deferred) |
-| W02/W03 | Local projects and temporary conversations; search; archived filter; rename, pin, archive/restore with revision conflicts; new session in the explicit project | Reuse of an existing empty session |
+| W02/W03 | Local projects and temporary conversations; search; archived filter; rename, pin, archive/restore with revision conflicts; new session in the explicit project; conversations of an archived project read-only until the project is restored | Reuse of an existing empty session |
| W04 | Paged history; live assistant text; send; queue; cancel queued; stop the named turn; “waiting on Desktop” for approvals and input | Answering ordinary questions from the browser; model label is the raw model id |
| W05 | Idempotency keys for every mutation; SSE change notices with refetch; reconnect banner | Cursor-based replay (refetch is used instead) |
-| W06 | Device revocation; non-owner principal under the remote `ask` ceiling; plan/goal and remote sessions read-only or hidden | Idle (30 min) session expiry; canceling already queued work on device revocation |
+| W06 | Device revocation; non-owner principal under the remote `ask` ceiling, enforced per turn by host-core (including queued and delegated work); plan/goal and remote sessions read-only or hidden | Idle (30 min) session expiry; canceling already queued work on device revocation |
| W07 | Phone-first layout, 44 px targets, English and Simplified Chinese, IME-safe Enter | Screen-reader and large-catalog qualification |
| W08 | Existing names, pins and archives keep working; browser edits survive stale sidebar writes | — |
Automated coverage: `apps/desktop/test/lan-webui-organization.test.mjs`,
`lan-webui-restart.test.mjs` (saved startup and pairing lifecycle),
-`lan-webui-user-path.test.mjs` (real HTTP listener, fake Desktop), and
+`lan-webui-user-path.test.mjs` (real HTTP listener, fake Desktop),
+`lan-webui-archive-admission.test.mjs` (archived-parent read-only, archive/send
+ordering, refused ceiling), and
`lan-webui-settings-user-path.test.mjs` (isolated Desktop System settings).
The phone-size Electron Chromium journey runs separately with
`pnpm test:e2e:lan-webui` on the Electron-equipped CI runner.
diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.md
index 029e5c824..deb4811e9 100644
--- a/docs/spec/03-runtime/04-data-storage.md
+++ b/docs/spec/03-runtime/04-data-storage.md
@@ -1,4 +1,4 @@
-# 04. Data Storage (Schema v34)
+# 04. Data Storage (Schema v35)
### Project path aliases (#2148)
@@ -887,12 +887,22 @@ CREATE TABLE turns (
output_tokens INTEGER NOT NULL DEFAULT 0,
usage_json TEXT, -- full provider usage (cached breakdown, …)
started_at INTEGER NOT NULL,
- ended_at INTEGER
+ ended_at INTEGER,
+ permission_ceiling TEXT CHECK (permission_ceiling IN ('ask', 'accept-edits', 'auto'))
);
CREATE INDEX idx_turns_session ON turns(session_id, started_at DESC);
CREATE INDEX idx_turns_ended_at ON turns(ended_at DESC);
```
+`permission_ceiling` (schema v35) is the remote permission ceiling a turn was
+admitted under (remote-control security §4.3), written by `session.beginTurn`
+when its caller passes `permissionCeiling`. Every tool decision that names the
+turn, or that names none while the turn is the session's running turn, uses the
+stricter of the current session mode and this ceiling. The row keeps it after
+the turn ends so delegated work started by the turn stays bound. NULL means no
+ceiling. A ceiling that cannot be recorded ends the new turn with
+`PERMISSION_CEILING_UNAVAILABLE` and the turn never runs.
+
### 4.6a plan_approvals — immutable checkpoint and execution fields (schema v11)
The host writes each submitted Markdown snapshot to a new unique file under the
@@ -994,7 +1004,9 @@ CREATE TABLE turn_queue (
position INTEGER NOT NULL,
priority INTEGER,
voice_origin_json TEXT,
- created_at INTEGER NOT NULL
+ created_at INTEGER NOT NULL,
+ start_goal INTEGER NOT NULL DEFAULT 0 CHECK (start_goal IN (0, 1)),
+ permission_ceiling TEXT CHECK (permission_ceiling IN ('ask', 'accept-edits', 'auto'))
);
CREATE INDEX idx_turn_queue_session ON turn_queue(session_id, position);
CREATE UNIQUE INDEX idx_turn_queue_idempotency
@@ -1829,6 +1841,12 @@ truncating at a guessed position.
session `/fast` switch, defaulting to `0` for every existing session. Forks
copy it; scheduled runs and delegated workers start at `0`. The migration
keeps a v26 backup.
+- **Schema v35 is additive.** It adds nullable `turns.permission_ceiling` and
+ `turn_queue.permission_ceiling` (ADR turn-permission-ceiling). Existing turns
+ keep NULL. A queue entry persisted before v35 recorded its admitted mode but
+ not whether a ceiling bound it, so the migration uses that mode (`ask` for an
+ unrecognized value) as its ceiling: a restored remote entry cannot start
+ broader than it was admitted. The migration keeps a v34 backup.
- **Schema v14 is additive.** It adds nullable `sessions.deleted_at`, the
partial deletion index, and `session_import_origins`. Existing sessions stay
active and have no origin rows. The migration runs in the same guarded
diff --git a/docs/spec/05-security/02-remote-control-security.md b/docs/spec/05-security/02-remote-control-security.md
index fb83d0c0e..a1c9196ca 100644
--- a/docs/spec/05-security/02-remote-control-security.md
+++ b/docs/spec/05-security/02-remote-control-security.md
@@ -323,6 +323,22 @@ holds `approver` and Host policy allows approvers to use the session's own
mode. The applied value is reported as `effectivePermissionMode` and never
changes the durable session mode.
+The Agent Host derives the ceiling from the authenticated principal, never
+from client input, and host-core enforces it. `session.beginTurn` records the
+ceiling on the durable turn, and a queued turn carries it in its queue record,
+including across a restart. Every tool authorization takes the stricter of the
+session mode current at that decision and the ceiling of the turn the call
+belongs to, so a later session change, a subagent's own permission scope, or
+delegated work that outlives the turn cannot broaden it. A session created
+while a ceiling-bound turn of its parent is running inherits no broader mode,
+and a session message sent during that turn carries no broader ceiling. Such a
+turn cannot arrange an automatic background-job continuation, which would
+start a later Desktop turn under the session mode. A turn
+whose ceiling the Host cannot record does not run, and the client receives
+`PERMISSION_CEILING_UNAVAILABLE`. Existing approvals, workspace and path checks
+are unchanged; anything that needs a decision under `ask` uses the existing
+local approval flow.
+
The ceiling applies to Gateway-routed principals. A desktop device paired
through the SSH bootstrap (§3.4) holds `owner` on that Host and is exempt:
an SSH login already grants shell access to the machine, so a ceiling would
diff --git a/docs/spec/06-delivery/07-remote-control-rollout.md b/docs/spec/06-delivery/07-remote-control-rollout.md
index e59d2ea9f..f46ad0ce2 100644
--- a/docs/spec/06-delivery/07-remote-control-rollout.md
+++ b/docs/spec/06-delivery/07-remote-control-rollout.md
@@ -465,6 +465,13 @@ Recorded on the `feat/remote-agent-host` branch, 2026-09-10:
sidecar as a documented stub. Turn-scoped enforcement in host-core
(`session.beginTurn` accepting an override) is the remaining piece, so a
narrower ceiling on a local turn does not yet clamp tool decisions.
+- R1 ceiling enforcement (2026-11-28, ADR turn-permission-ceiling): a turn
+ admitted for a principal bound by the remote ceiling carries
+ `permissionCeiling` to `session.beginTurn`, which records it on the durable
+ turn (schema v35); queued turns carry it in `turn_queue`. host-core applies
+ the stricter of the current session mode and that ceiling to every tool
+ decision of the turn, including its delegates. The sidecar stub is removed,
+ and a Host that does not confirm the ceiling starts no turn.
- R2 started (2026-09-18, D447 / ADR 0284): `packages/host-runtime` holds the
Electron-independent runtime layer — the host-core and sidecar stdio
transports, the restart supervisor, `RuntimeService` (the module's
diff --git a/docs/spec/06-delivery/e2e/live-and-remote.md b/docs/spec/06-delivery/e2e/live-and-remote.md
index 5199cf5e9..3094c7791 100644
--- a/docs/spec/06-delivery/e2e/live-and-remote.md
+++ b/docs/spec/06-delivery/e2e/live-and-remote.md
@@ -788,7 +788,10 @@ fixtures; do not use a user's running instance.
- **Steps:** Search for B and tap its row. Open a session's action menu, close it,
then tap that session to read its history. Pin and rename B and rename, pin,
archive and restore an idle session. Archive and restore B through the
- Archived view. Make a competing Desktop rename and submit the stale edit.
+ Archived view. With B archived, send and queue from a B conversation in a
+ second tab that loaded before the archive; restore B and send again. Archive
+ B while a send to one of its sessions is still being admitted, and while
+ work is queued. Make a competing Desktop rename and submit the stale edit.
- **Expected:** One row per group, stable IDs, correct filtered/recent/pinned
lists; both clients show committed changes without reloading. Archive is not
deletion and does not cascade; restoring B preserves the separately archived
@@ -796,7 +799,12 @@ fixtures; do not use a user's running instance.
A closed action menu does not cover the page or intercept taps; test row and
menu actions with browser hit testing, not direct calls to the controls.
Desktop stays in A with draft, focus and scroll intact. Repeating the archive
- against a busy target fails without stopping work.
+ against a busy target fails without stopping work. While B is archived its
+ history stays readable, the conversation names B as the record to restore
+ and shows no composer after refresh, and the stale send or queue starts no
+ turn and keeps its text. After restoring B a send in an unarchived session
+ runs, while the separately archived session stays read-only. An archive that
+ races an admitted send reports busy; one decided first refuses the send.
- **Acceptance:** C, D; W02, W03, W05.
### E2E-271: Create and continue the same session on phone and desktop
@@ -842,11 +850,18 @@ fixtures; do not use a user's running instance.
- **Steps:** Submit an ordinary answer, race a second answer from Desktop, then
trigger a gated action. Reload the phone while pending; try a browser approval
and permission change, then deny locally. Repeat with local approval and with
- expiry/cancellation. Inspect the special session on the phone.
+ expiry/cancellation. Repeat the gated action with the session stored as
+ `auto` (and as `inherit` with an `auto` default) from a phone send, a queued
+ phone send and a subagent the phone turn delegated, then send the next turn
+ from Desktop. Inspect the special session on the phone.
- **Expected:** One ordinary answer is accepted. The phone reports the pending
request and actual outcome; only Desktop can approve, including on a session
configured for a higher local permission mode. Deny/expiry never executes the
gated action, local allow executes the fixture once, and reload grants nothing.
+ Under the stored `auto` mode every phone-originated path still waits for
+ Desktop approval, the saved mode is unchanged, and the next Desktop turn runs
+ under `auto` without a prompt. A Host that cannot record the ceiling refuses
+ the phone send with a visible reason and keeps the draft.
Unsupported sessions do not gain writable controls or change mode.
- **Acceptance:** C, E; W04, W06.
diff --git a/packages/agent-host/src/agent-host.test.ts b/packages/agent-host/src/agent-host.test.ts
index 45dc43902..4c2933407 100644
--- a/packages/agent-host/src/agent-host.test.ts
+++ b/packages/agent-host/src/agent-host.test.ts
@@ -436,6 +436,8 @@ describe("AgentHost turns", () => {
expect(started.turn.status).toBe("running");
expect(started.turn.effectivePermissionMode).toBe("ask");
expect(runtime.prompts[0]!.effectivePermissionMode).toBe("ask");
+ // The Host, not the runtime's session read, enforces this bound.
+ expect(runtime.prompts[0]!.permissionCeiling).toBe("ask");
const again = await host.startTurn(controller, {
sessionId: "s1",
idempotencyKey: "k1",
@@ -456,6 +458,7 @@ describe("AgentHost turns", () => {
).rejects.toMatchObject({ code: "CONFLICT" });
const started = await host.startTurn(owner, { sessionId: "s1", input: { text: "x" }, context: { requestId: "r", expectedRevision: 0 } });
expect(started.turn.effectivePermissionMode).toBe("auto");
+ expect(runtime.prompts[0]!.permissionCeiling).toBeUndefined();
expect(runtime.prompts[0]!.principal.subject).toBe("desktop");
await expect(host.startTurn(viewer, { sessionId: "s1", input: { text: "x" }, context: { requestId: "r" } })).rejects.toMatchObject({
code: "FORBIDDEN",
@@ -641,6 +644,35 @@ describe("AgentHost turns", () => {
host.endTurn("s1", "rt_1", "completed");
await vi.waitFor(() => expect(runtime.prompts).toHaveLength(2));
expect(runtime.prompts[1]?.effectivePermissionMode).toBe("ask");
+ expect(runtime.prompts[0]?.permissionCeiling).toBeUndefined();
+ expect(runtime.prompts[1]?.permissionCeiling).toBe("ask");
+ });
+
+ it("does not fold a ceiling-bound promoted row into an exempt turn even when the modes match", async () => {
+ const store = new MemoryQueueStore();
+ const { host, runtime } = build({ permissionMode: "ask", queueStore: store });
+ runtime.refuseSteers = true;
+ const first = await host.startTurn(owner, { sessionId: "s1", input: { text: "one" }, context: { requestId: "r1" } });
+ host.ingest(envelope("s1", first.turn.id, { type: "agent_start" }));
+ const desktop = await host.startTurn(owner, { sessionId: "s1", admission: "queue", input: { text: "desktop follow-up" }, context: { requestId: "r2" } });
+ const phone = await host.startTurn(controller, { sessionId: "s1", admission: "queue", input: { text: "phone input" }, context: { requestId: "r3" } });
+ // The ceiling survives the durable queue record.
+ expect((await store.listAll()).map((record) => record.permissionCeiling)).toEqual([undefined, "ask"]);
+ await host.prioritizeTurn(owner, desktop.turn.id);
+ await host.prioritizeTurn(controller, phone.turn.id);
+
+ runtime.refuseSteers = false;
+ host.ingest(envelope("s1", first.turn.id, { type: "agent_end", messageIds: [] }));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ // Equal modes no longer suffice: the Desktop turn has no Host ceiling.
+ expect(runtime.prompts.map((prompt) => prompt.content)).toEqual(["one", "desktop follow-up"]);
+ expect(runtime.steers).toEqual([]);
+ expect(host.queueEntries("s1").map((entry) => entry.turn.id)).toEqual([phone.turn.id]);
+ host.endTurn("s1", "rt_2", "completed");
+ await vi.waitFor(() => expect(runtime.prompts).toHaveLength(3));
+ expect(runtime.prompts[2]).toMatchObject({ content: "phone input", permissionCeiling: "ask" });
});
it("delivers into an externally started Desktop turn using the stored session mode", async () => {
diff --git a/packages/agent-host/src/agent-host.ts b/packages/agent-host/src/agent-host.ts
index 75232bd48..f073d0dce 100644
--- a/packages/agent-host/src/agent-host.ts
+++ b/packages/agent-host/src/agent-host.ts
@@ -37,6 +37,7 @@ import {
deltaStreamPayloadFits,
effectiveRemotePermissionMode,
racpKindForAgentEvent,
+ remotePermissionCeiling,
rolesAllowOperation,
} from "@pi-desktop/shared";
@@ -150,6 +151,8 @@ type TurnRecord = RacpTurn & {
/** The runtime's own turn id when it differs from the RACP id (queued turns). */
runtimeTurnId?: string;
principalSubject?: string;
+ /** Host-enforced ceiling of the admitting principal (spec §7.3). */
+ permissionCeiling?: RacpPermissionMode;
};
type SessionState = {
@@ -519,12 +522,13 @@ export class AgentHost {
details: { expectedRevision: expected, revision: state.revision },
});
}
- const effectivePermissionMode = effectiveRemotePermissionMode({
- sessionMode: summary.permissionMode,
+ const ceilingInput = {
policy: this.policy,
pairedDevice: principal.pairedDevice ?? false,
approverOverride: principal.approverOverride ?? false,
- });
+ };
+ const effectivePermissionMode = effectiveRemotePermissionMode({ ...ceilingInput, sessionMode: summary.permissionMode });
+ const permissionCeiling = remotePermissionCeiling(ceilingInput);
const admission: RacpTurnAdmission = forceQueue ? "queue" : params.admission ?? "reject_if_busy";
const busy = this.isBusy(state);
const modeOrigin = params[TRUSTED_MODE_ORIGIN];
@@ -549,6 +553,7 @@ export class AgentHost {
...(params.input.voiceOrigin ? { voiceOrigin: params.input.voiceOrigin } : {}),
...(params.input.attachments ? { attachments: params.input.attachments } : {}),
effectivePermissionMode,
+ ...(permissionCeiling ? { permissionCeiling } : {}),
...(idempotencyKey ? { idempotencyKey } : {}),
inputHash,
createdAt: this.clock.now(),
@@ -559,6 +564,7 @@ export class AgentHost {
turn.admission = "queue";
turn.queuePosition = position;
turn.effectivePermissionMode = effectivePermissionMode;
+ turn.permissionCeiling = permissionCeiling;
turn.idempotencyKey = idempotencyKey;
turn.principalSubject = principal.subject;
this.emit(state, "turn.queued", { turn: this.toRacpTurn(state, turn) }, { turnId: turn.id });
@@ -577,6 +583,7 @@ export class AgentHost {
...(params.input.voiceOrigin ? { voiceOrigin: params.input.voiceOrigin } : {}),
...(params.input.attachments ? { attachments: params.input.attachments } : {}),
effectivePermissionMode,
+ ...(permissionCeiling ? { permissionCeiling } : {}),
...(idempotencyKey ? { idempotencyKey } : {}),
principal,
});
@@ -584,6 +591,7 @@ export class AgentHost {
if (!isTerminal(turn.status) && !isActive(turn.status)) turn.status = "running";
turn.admission = admission;
turn.effectivePermissionMode = effectivePermissionMode;
+ turn.permissionCeiling = permissionCeiling;
turn.idempotencyKey = idempotencyKey;
turn.principalSubject = principal.subject;
state.activeTurnId = turn.id;
@@ -1014,10 +1022,12 @@ export class AgentHost {
...(record.voiceOrigin ? { voiceOrigin: record.voiceOrigin } : {}),
...(record.attachments ? { attachments: record.attachments } : {}),
effectivePermissionMode: record.effectivePermissionMode,
+ ...(record.permissionCeiling ? { permissionCeiling: record.permissionCeiling } : {}),
...(record.idempotencyKey ? { idempotencyKey: record.idempotencyKey } : {}),
principal: { subject: record.principalSubject, roles: ["controller"] },
});
turn.runtimeTurnId = started.turnId;
+ turn.permissionCeiling = record.permissionCeiling;
this.runtimeAliases.set(started.turnId, turn.id);
if (!isActive(turn.status)) turn.status = "running";
turn.queuePosition = undefined;
@@ -1095,6 +1105,8 @@ export class AgentHost {
? state.permissionMode
: active?.effectivePermissionMode;
if (activePermissionMode !== record.effectivePermissionMode) return undefined;
+ // Input joins only a turn held to the same Host ceiling.
+ if (active?.permissionCeiling !== record.permissionCeiling) return undefined;
const turn = this.ensureTurn(state, record.id);
if (turn.deliveryPending || turn.deliveredIntoTurnId) return undefined;
turn.deliveryPending = true;
diff --git a/packages/agent-host/src/ports.ts b/packages/agent-host/src/ports.ts
index ffb53068d..974f8668f 100644
--- a/packages/agent-host/src/ports.ts
+++ b/packages/agent-host/src/ports.ts
@@ -55,6 +55,12 @@ export type TurnStartRequest = {
voiceOrigin?: VoiceOrigin;
attachments?: AgentPromptAttachment[];
effectivePermissionMode: RacpPermissionMode;
+ /**
+ * Ceiling the Host must enforce on every tool decision of this turn
+ * (spec §7.3). Present exactly when the admitting principal is bound by
+ * the remote ceiling; a runtime that cannot enforce it must refuse the turn.
+ */
+ permissionCeiling?: RacpPermissionMode;
idempotencyKey?: string;
principal: Principal;
};
@@ -102,6 +108,8 @@ export type QueuedTurnRecord = {
voiceOrigin?: VoiceOrigin;
attachments?: AgentPromptAttachment[];
effectivePermissionMode: RacpPermissionMode;
+ /** The admitting principal's ceiling, carried until the turn starts. */
+ permissionCeiling?: RacpPermissionMode;
idempotencyKey?: string;
/** Stable hash of the input, so a reused key with different input is a conflict. */
inputHash: string;
diff --git a/packages/agent-runtime/src/delegation-runtime.test.ts b/packages/agent-runtime/src/delegation-runtime.test.ts
index 6a19b4dbe..3da9f7283 100644
--- a/packages/agent-runtime/src/delegation-runtime.test.ts
+++ b/packages/agent-runtime/src/delegation-runtime.test.ts
@@ -181,6 +181,30 @@ describe("Task delegation on the real child loop", () => {
expect(calls).toEqual([expect.objectContaining({ toolName: "Write", permissionScope: "ask", writeScope: ["src/parser"] })]);
});
+ it("keeps the starting turn on a delegate's Host calls after the parent moves on", async () => {
+ // The Host applies the permission ceiling of the turn a call names, so a
+ // delegate started by a phone turn must keep naming that turn.
+ const calls: Array<Record<string, unknown>> = [];
+ const gate = deferred();
+ const f = await modelServer(async (req, res) => {
+ if (req.messages.some((m) => m.role === "tool")) return reply(res, req.model, "Done.");
+ await gate.promise;
+ reply(res, req.model, "", [{ name: "Write", args: { path: "out.txt", content: "x" } }]);
+ });
+ const { runtime } = session(f.provider("fixture"), (method, params) => {
+ if (method !== "tools.execute") return undefined;
+ calls.push(params as Record<string, unknown>);
+ return { ok: true, content: "written" };
+ });
+ const turn = runtime as unknown as { turnId?: string };
+ turn.turnId = "phone-turn";
+ const id = resultId(await tool(runtime, "Task").execute("task", { agent: "fixer", task: "Write the file." }));
+ turn.turnId = "desktop-turn";
+ gate.resolve();
+ await waitForTask(runtime, id);
+ expect(calls).toEqual([expect.objectContaining({ toolName: "Write", turnId: "phone-turn" })]);
+ });
+
it.each(["fabricated", "substitute", "omitted", "other expert", "truncated"])("blocks a %s quote or role before launching a child", async (kind) => {
const first = "@fixer Only review `src/parser`. Do not edit.\n";
const second = "@reviewer Verify `docs/`.";
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index eab1b602d..668217d9a 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -1940,6 +1940,8 @@ export class DesktopAgentRuntime {
* authorization metadata local to the executor, never keyed by such ids. */
private readonly delegateExecution = new AsyncLocalStorage<{
owner: string; permission: SubagentPermission; worktreeKey?: string; writeScope?: readonly string[];
+ /** The turn that started the delegate; its Host permission ceiling governs the delegate's calls. */
+ turnId?: string;
}>();
/** Serializes same-path mutations across the parent and its delegates. */
private writeLocks = new PathMutex();
@@ -3821,7 +3823,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
denied?: boolean;
}>("tools.execute", {
sessionId: this.sessionId,
- turnId: this.turnId,
+ turnId: delegate?.turnId ?? this.turnId,
toolCallId,
toolName,
args: params,
@@ -5600,10 +5602,12 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
const worktreeKey = typeof worktreeKeyOrApply === "string" ? worktreeKeyOrApply : undefined;
const apply = typeof worktreeKeyOrApply === "function" ? worktreeKeyOrApply : applyInstructions;
const scope = definition.permission ?? DEFAULT_SUBAGENT_PERMISSION;
+ // A delegate outlives the turn that started it; keep that turn's identity.
+ const turnId = this.delegateExecution.getStore()?.turnId ?? this.turnId;
return tools.map((tool) => ({
...tool,
execute: (toolCallId, args, signal, onUpdate) => this.delegateExecution.run(
- { owner: mutationOwner, permission: scope, worktreeKey, writeScope },
+ { owner: mutationOwner, permission: scope, worktreeKey, writeScope, turnId },
() => this.instructionExecution.run(apply ?? (() => undefined), () => tool.execute(toolCallId, args, signal, onUpdate)),
),
}));
diff --git a/packages/agent-runtime/src/sidecar.ts b/packages/agent-runtime/src/sidecar.ts
index 13c3d8128..a2ed0c981 100644
--- a/packages/agent-runtime/src/sidecar.ts
+++ b/packages/agent-runtime/src/sidecar.ts
@@ -504,17 +504,9 @@ async function handle(method: string, params: any): Promise<unknown> {
typeof params.userMessageId === "string" && params.userMessageId
? params.userMessageId
: undefined;
- // A `permissionMode` override on `agent.prompt` is the per-turn ceiling
- // from spec §7.3 (R1 leftover). The sidecar accepts it so callers do not
- // have to guard the field, but tool-approval enforcement still consults
- // the session's stored mode inside host-core. Once host-core
- // `session.beginTurn` accepts a per-turn override, this record will drive
- // the enforcement gate; until then it stays a documented stub.
- if (typeof params.permissionMode === "string" && params.permissionMode) {
- // Log-only stub: observable in the sidecar log without affecting
- // execution. Deliberately omitted from user-visible events.
- void params.permissionMode;
- }
+ // The per-turn permission ceiling (spec §7.3) is recorded on the
+ // durable turn by host-core and enforced on every `tools.execute`; the
+ // runtime carries no copy of it.
const prompt: RuntimePrompt = {
text: content,
...(params.backgroundCompletion ? { backgroundCompletion: params.backgroundCompletion } : {}),
diff --git a/packages/host-runtime/src/host-ports.test.ts b/packages/host-runtime/src/host-ports.test.ts
index 55cf50bfe..a1c9e9b0a 100644
--- a/packages/host-runtime/src/host-ports.test.ts
+++ b/packages/host-runtime/src/host-ports.test.ts
@@ -241,6 +241,30 @@ describe("host ports", () => {
});
});
+ it("carries the per-turn permission ceiling through the durable queue", async () => {
+ const calls: Array<{ method: string; params: Record<string, unknown> }> = [];
+ const entry = (permissionCeiling?: string) => ({
+ id: "q", sessionId: "s", principal: "lan:phone", inputHash: "h", content: "c",
+ permissionMode: "ask", position: 1, createdAt: "2026-09-18T00:00:00.000Z",
+ ...(permissionCeiling === undefined ? {} : { permissionCeiling }),
+ });
+ const store = createHostQueueStore(() => ({
+ async call<T>(method: string, params: Record<string, unknown> = {}) {
+ calls.push({ method, params });
+ return {} as T;
+ },
+ }));
+ const record = fromHostQueueEntry(entry("ask"));
+ expect(record.permissionCeiling).toBe("ask");
+ await store.push(record);
+ expect(calls.at(-1)?.params.permissionCeiling).toBe("ask");
+ // No ceiling stays no ceiling; an unreadable one fails closed to `ask`.
+ expect(fromHostQueueEntry(entry())).not.toHaveProperty("permissionCeiling");
+ expect(fromHostQueueEntry(entry("bogus")).permissionCeiling).toBe("ask");
+ await store.push(fromHostQueueEntry(entry()));
+ expect(calls.at(-1)?.params).not.toHaveProperty("permissionCeiling");
+ });
+
it("fails closed when the host is gone", async () => {
const store = createHostQueueStore(() => null);
expect(await store.listAll()).toEqual([]);
diff --git a/packages/host-runtime/src/host-ports.ts b/packages/host-runtime/src/host-ports.ts
index b85a2e144..16926432b 100644
--- a/packages/host-runtime/src/host-ports.ts
+++ b/packages/host-runtime/src/host-ports.ts
@@ -16,6 +16,8 @@ import type {
VoiceOrigin,
} from "@pi-desktop/shared";
+import { isPermissionCeiling } from "./turn-permission-ceiling.js";
+
/** Rust host-core over stdio JSON-RPC, as the ports below need it. */
export type HostRpc = {
call<T = unknown>(
@@ -213,6 +215,7 @@ export type HostQueueEntry = {
voiceOrigin?: VoiceOrigin;
attachments?: unknown;
permissionMode: string;
+ permissionCeiling?: string;
position: number;
priority?: number;
createdAt: string;
@@ -238,6 +241,9 @@ export function fromHostQueueEntry(entry: HostQueueEntry): QueuedTurnRecord {
? { attachments: entry.attachments as QueuedTurnRecord["attachments"] }
: {}),
effectivePermissionMode: permissionMode,
+ ...(entry.permissionCeiling !== undefined
+ ? { permissionCeiling: isPermissionCeiling(entry.permissionCeiling) ? entry.permissionCeiling : "ask" }
+ : {}),
...(entry.idempotencyKey ? { idempotencyKey: entry.idempotencyKey } : {}),
inputHash: entry.inputHash,
...(entry.priority !== undefined ? { priority: entry.priority } : {}),
@@ -279,6 +285,7 @@ export function createHostQueueStore(
...(record.voiceOrigin ? { voiceOrigin: record.voiceOrigin } : {}),
...(record.attachments ? { attachments: record.attachments } : {}),
permissionMode: record.effectivePermissionMode,
+ ...(record.permissionCeiling ? { permissionCeiling: record.permissionCeiling } : {}),
});
},
async remove(id) {
diff --git a/packages/host-runtime/src/index.ts b/packages/host-runtime/src/index.ts
index 8f2e645a8..96211c261 100644
--- a/packages/host-runtime/src/index.ts
+++ b/packages/host-runtime/src/index.ts
@@ -9,6 +9,7 @@ export * from "./plan-execution.js";
export * from "./turn-persistence.js";
export * from "./turn-events.js";
export * from "./runtime-service.js";
+export * from "./turn-permission-ceiling.js";
export * from "./plan-dispatch.js";
export * from "./workspace-files.js";
export * from "./external-files.js";
diff --git a/packages/host-runtime/src/runtime-service.test.ts b/packages/host-runtime/src/runtime-service.test.ts
index c4a2d76c7..3fdb94de3 100644
--- a/packages/host-runtime/src/runtime-service.test.ts
+++ b/packages/host-runtime/src/runtime-service.test.ts
@@ -15,6 +15,8 @@ class FakeHost implements RuntimeHostLink {
private turnCounter = 0;
messages = new Map<string, UiMessage[]>();
failAppend = false;
+ /** Answer `session.beginTurn` like a Host that predates the turn ceiling. */
+ ignoreCeiling = false;
session: Record<string, unknown> = { id: "s1", mode: "agent", permissionMode: "ask", providerId: "p1", modelId: "m1" };
async call<T = unknown>(method: string, params: Record<string, unknown> = {}): Promise<T> {
@@ -27,7 +29,10 @@ class FakeHost implements RuntimeHostLink {
return { session: { ...this.session, id: params.id, messages: this.messages.get(String(params.id)) ?? [] } } as T;
case "session.beginTurn":
this.turnCounter += 1;
- return { turnId: `turn-${this.turnCounter}` } as T;
+ return {
+ turnId: `turn-${this.turnCounter}`,
+ ...(params.permissionCeiling && !this.ignoreCeiling ? { permissionCeiling: params.permissionCeiling } : {}),
+ } as T;
case "session.appendMessage": {
if (this.failAppend) throw Object.assign(new Error("disk full"), { errorCode: "INTERNAL" });
const list = this.messages.get(String(params.sessionId)) ?? [];
@@ -229,6 +234,35 @@ function holdNextCall(link: FakeHost | FakeSidecar, method: string) {
return { reached, release };
}
+describe("RuntimeService per-turn permission ceiling", () => {
+ const phone = { subject: "lan:phone", roles: ["controller" as const], pairedDevice: false };
+
+ it("records the ceiling on the durable Host turn instead of the runtime prompt", async () => {
+ const { host, sidecar, service } = build();
+ host.session = { ...host.session, permissionMode: "auto" };
+ await service.prompt({ sessionId: "s1", content: "from phone", effectivePermissionMode: "ask", permissionCeiling: "ask", principal: phone });
+ expect(host.calls.find((call) => call.method === "session.beginTurn")?.params.permissionCeiling).toBe("ask");
+ expect(sidecar.calls.find((call) => call.method === "agent.prompt")?.params).not.toHaveProperty("permissionMode");
+ await service.prompt({ sessionId: "s2", content: "from desktop", effectivePermissionMode: "auto", principal: owner });
+ expect(host.calls.filter((call) => call.method === "session.beginTurn")[1]?.params).not.toHaveProperty("permissionCeiling");
+ await service.dispose();
+ });
+
+ it("starts nothing when the Host does not confirm the ceiling", async () => {
+ const { host, sidecar, service, ended } = build();
+ host.ignoreCeiling = true;
+ await expect(service.prompt({ sessionId: "s1", content: "from phone", effectivePermissionMode: "ask", permissionCeiling: "ask", principal: phone }))
+ .rejects.toMatchObject({ errorCode: "PERMISSION_CEILING_UNAVAILABLE" });
+ expect(sidecar.calls.some((call) => call.method === "agent.prompt")).toBe(false);
+ expect(host.calls.some((call) => call.method === "session.appendMessage")).toBe(false);
+ expect(host.calls.find((call) => call.method === "session.endTurn")?.params)
+ .toMatchObject({ turnId: "turn-1", status: "error", errorCode: "PERMISSION_CEILING_UNAVAILABLE" });
+ expect(ended).toEqual([expect.objectContaining({ turnId: "turn-1" })]);
+ expect(service.isBusy("s1")).toBe(false);
+ await service.dispose();
+ });
+});
+
describe("RuntimeService startup cancellation", () => {
for (const targeted of [false, true]) {
it.each([
diff --git a/packages/host-runtime/src/runtime-service.ts b/packages/host-runtime/src/runtime-service.ts
index 3bd8907a0..775ebe72a 100644
--- a/packages/host-runtime/src/runtime-service.ts
+++ b/packages/host-runtime/src/runtime-service.ts
@@ -15,6 +15,11 @@ import {
import type { LaunchResolver } from "./launch-resolver.js";
import { resolveSessionMessageInput } from "./session-message-input.js";
import { TurnEventPipeline } from "./turn-events.js";
+import {
+ PERMISSION_CEILING_UNAVAILABLE,
+ assertTurnCeilingRecorded,
+ turnCeilingParams,
+} from "./turn-permission-ceiling.js";
/** host-core as the turn lifecycle drives it. `HostProcess` satisfies it. */
export type RuntimeHostLink = {
@@ -281,18 +286,6 @@ export class RuntimeService implements RuntimePort {
}
}
- /** True when the effective per-turn mode narrows or otherwise differs from
- * the session's stored `permissionMode`; used to decide whether to forward a
- * per-turn override to the sidecar. A widening request has already been
- * refused by the agent-host bridge before reaching here. */
- private sessionModeDiffers(
- session: Record<string, unknown> | null | undefined,
- effective: string,
- ): boolean {
- const stored = session && typeof session.permissionMode === "string" ? session.permissionMode : undefined;
- return stored !== undefined && stored !== effective;
- }
-
private async startTurn(sessionId: string, request: TurnStartRequest): Promise<{ turnId: string }> {
const host = this.requireHost();
const sidecar = this.requireSidecar();
@@ -313,7 +306,9 @@ export class RuntimeService implements RuntimePort {
const launch = await this.options.launch.resolve(sessionId, session, settings ?? {});
sidecar.setProjectInstructionRoot(sessionId, launch.projectPath);
- const turnId = await this.beginTurn(sessionId, launch.providerId, launch.modelId, sessionMessage?.origin.messageId);
+ const turnId = await this.beginTurn(
+ sessionId, launch.providerId, launch.modelId, sessionMessage?.origin.messageId, request.permissionCeiling,
+ );
let content = sessionMessage?.content ?? request.content;
let command: string | undefined;
@@ -360,13 +355,6 @@ export class RuntimeService implements RuntimePort {
...(sessionMessage ? { sessionMessage: sessionMessage.origin } : {}),
attachments: [],
userMessageId: userMessage.id,
- // Per-turn permission ceiling override (R1 leftover; spec §7.3). Only
- // forwarded when the effective mode differs from the session's stored
- // mode — a widening request has already been refused upstream so any
- // override that reaches here is narrower than or equal to session.
- ...(request.effectivePermissionMode && this.sessionModeDiffers(session, request.effectivePermissionMode)
- ? { permissionMode: request.effectivePermissionMode }
- : {}),
});
} catch (error) {
await this.finishTurn(sessionId, "error", errorCodeOf(error), { turnId });
@@ -528,18 +516,35 @@ export class RuntimeService implements RuntimePort {
}
}
- /** Open a durable turn row and take ownership of the session for it. */
- async beginTurn(sessionId: string, providerId: string, modelId: string, sessionMessageId?: string): Promise<string> {
- const turn = await this.requireHost().call<{ turnId?: string }>("session.beginTurn", {
+ /**
+ * Open a durable turn row and take ownership of the session for it. A
+ * `permissionCeiling` is recorded on the row and bounds every tool decision
+ * of the turn; a Host that does not confirm it gets no turn.
+ */
+ async beginTurn(
+ sessionId: string,
+ providerId: string,
+ modelId: string,
+ sessionMessageId?: string,
+ permissionCeiling?: TurnStartRequest["permissionCeiling"],
+ ): Promise<string> {
+ const turn = await this.requireHost().call<{ turnId?: string; permissionCeiling?: unknown }>("session.beginTurn", {
sessionId,
providerId,
modelId,
...(sessionMessageId ? { sessionMessageId } : {}),
+ ...turnCeilingParams(permissionCeiling),
});
const turnId = String(turn?.turnId ?? "").trim();
if (!turnId) throw new Error("session.beginTurn returned no turn");
this.activeTurns.set(sessionId, turnId);
this.events.resetTurnUsage(sessionId);
+ try {
+ assertTurnCeilingRecorded(permissionCeiling, turn);
+ } catch (error) {
+ await this.finishTurn(sessionId, "error", PERMISSION_CEILING_UNAVAILABLE, { turnId });
+ throw error;
+ }
return turnId;
}
diff --git a/packages/host-runtime/src/turn-permission-ceiling.ts b/packages/host-runtime/src/turn-permission-ceiling.ts
new file mode 100644
index 000000000..e3fb6290e
--- /dev/null
+++ b/packages/host-runtime/src/turn-permission-ceiling.ts
@@ -0,0 +1,34 @@
+import type { RacpPermissionMode } from "@pi-desktop/shared";
+
+/** A ceiling-bound turn whose ceiling the Host did not accept never runs. */
+export const PERMISSION_CEILING_UNAVAILABLE = "PERMISSION_CEILING_UNAVAILABLE";
+
+const CEILINGS: ReadonlySet<string> = new Set<RacpPermissionMode>(["ask", "accept-edits", "auto"]);
+
+export function isPermissionCeiling(value: unknown): value is RacpPermissionMode {
+ return typeof value === "string" && CEILINGS.has(value);
+}
+
+/**
+ * `session.beginTurn` parameters for a turn held to `ceiling` (spec §7.3).
+ * Host-core records the ceiling on the durable turn and applies it to every
+ * tool decision of that turn.
+ */
+export function turnCeilingParams(ceiling: RacpPermissionMode | undefined): { permissionCeiling?: RacpPermissionMode } {
+ return ceiling ? { permissionCeiling: ceiling } : {};
+}
+
+/**
+ * Throw unless the Host confirmed the requested ceiling. A Host that ignored
+ * it would run the turn under the stored session mode, so the caller ends the
+ * turn instead of starting it.
+ */
+export function assertTurnCeilingRecorded(
+ requested: RacpPermissionMode | undefined,
+ response: { permissionCeiling?: unknown } | null | undefined,
+): void {
+ if (!requested || response?.permissionCeiling === requested) return;
+ throw Object.assign(new Error("the Host could not enforce this turn's permission ceiling"), {
+ errorCode: PERMISSION_CEILING_UNAVAILABLE,
+ });
+}
diff --git a/packages/shared/src/lan-webui.ts b/packages/shared/src/lan-webui.ts
index d0a4a7627..9d75bb85c 100644
--- a/packages/shared/src/lan-webui.ts
+++ b/packages/shared/src/lan-webui.ts
@@ -28,6 +28,12 @@ export interface LanSession {
* from responses of builds that predate it.
*/
projectLabel?: string | null;
+ /**
+ * The parent project is archived. History stays readable, but nothing can
+ * be sent or queued until the project is restored. Independent of the
+ * session's own `archived` flag. Optional: absent from older builds.
+ */
+ projectArchived?: boolean;
}
export interface LanPage<T> {
items: T[];
diff --git a/packages/shared/src/racp.ts b/packages/shared/src/racp.ts
index 2731e3e40..2d657b118 100644
--- a/packages/shared/src/racp.ts
+++ b/packages/shared/src/racp.ts
@@ -825,15 +825,26 @@ export type RacpCeilingInput = {
approverOverride: boolean;
};
+/**
+ * The ceiling the Host must hold a remote-initiated turn to, or `undefined`
+ * when the principal is exempt. Host-core applies it to every tool decision
+ * of that turn, against the session mode current at the decision.
+ */
+export function remotePermissionCeiling(
+ input: Omit<RacpCeilingInput, "sessionMode">,
+): RacpPermissionMode | undefined {
+ const exempt =
+ (input.pairedDevice && !input.policy.applyCeilingToPairedDevices) || input.approverOverride;
+ return exempt ? undefined : input.policy.remoteMaxPermissionMode;
+}
+
/**
* The mode a remote-initiated turn actually runs under: the lower of the
* session mode and the ceiling, unless the principal is exempt.
*/
export function effectiveRemotePermissionMode(input: RacpCeilingInput): RacpPermissionMode {
- const exempt =
- (input.pairedDevice && !input.policy.applyCeilingToPairedDevices) || input.approverOverride;
- if (exempt) return input.sessionMode;
- const ceiling = input.policy.remoteMaxPermissionMode;
+ const ceiling = remotePermissionCeiling(input);
+ if (!ceiling) return input.sessionMode;
return PERMISSION_MODE_RANK[input.sessionMode] <= PERMISSION_MODE_RANK[ceiling]
? input.sessionMode
: ceiling;
diff --git a/packages/shared/src/types/agent.ts b/packages/shared/src/types/agent.ts
index 7f301c8d2..b43c1b64b 100644
--- a/packages/shared/src/types/agent.ts
+++ b/packages/shared/src/types/agent.ts
@@ -49,14 +49,11 @@ export type AgentPromptRequest = {
*/
viewingSessionId?: string | null;
/**
- * Per-turn permission ceiling override (spec §7.3): the effective mode the
- * remote layer computed for this specific turn, which the runtime must apply
- * for tool decisions instead of the session's stored mode. Absent means the
- * session's stored mode is used. Accepted only when the requested mode is
- * narrower than or equal to the session's mode; a wider request is refused
- * before the turn starts. The bridge forwards this end-to-end so the
- * host-core scoping (still pending, R1 leftover) can enforce it turn-locally
- * once it lands.
+ * Per-turn permission ceiling (spec §7.3). Host-core records it on the
+ * durable turn and applies the stricter of it and the current session mode
+ * to every tool decision of that turn, including delegated work. It never
+ * widens or rewrites the session setting. Absent means no ceiling; a value
+ * the Host cannot record refuses the prompt.
*/
permissionMode?: RacpPermissionMode;
};