From fa5ea7be73171a48567b0dfd29a98201ffd48052 Mon Sep 17 00:00:00 2001 From: Adam Crocker <77861255+captcrock@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:19:24 +0000 Subject: [PATCH] TD-5302: the computer is told when a timed phone permission runs out "Turn on for 1 hour" and a daemon-enforced expiry were already there (TD-5279): the policy reads the clock on every message. The computer was never told when a grant ran out; its Settings row just read "Off" again. The expiry timer now snapshots the grants when armed and, when it fires, sends phone_permission_lapsed (loopback windows only) for each timed grant that was on and is not live now. The window shows a banner naming the permission and where to turn it on again. A grant switched off by hand re-arms the timer first, so it is never reported. Co-Authored-By: Claude Opus 5.5 --- DECISIONS.md | 19 ++++++ core/scripts/generate_protocol_fixtures.py | 6 ++ core/tests/test_phone_grant_lapse.py | 71 ++++++++++++++++++++++ core/tstd/daemon.py | 30 ++++++++- core/tstd/protocol.py | 18 ++++++ docs/architecture.md | 1 + docs/tst-desk-backlog.md | 19 ++++++ ui/src/lib/client.ts | 1 + ui/src/lib/notifications.svelte.ts | 6 +- ui/src/lib/phone-permissions.test.ts | 28 +++++++++ ui/src/lib/phone-permissions.ts | 15 ++++- ui/src/lib/protocol-fixtures.json | 7 +++ ui/src/lib/protocol.ts | 9 +++ 13 files changed, 227 insertions(+), 3 deletions(-) create mode 100644 core/tests/test_phone_grant_lapse.py diff --git a/DECISIONS.md b/DECISIONS.md index 51f48cd8..0051e699 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -20503,3 +20503,22 @@ gives the same answer with or without a grant. **Rejected:** a sixth capability for these (the owner chose "never"); and refusing every `set_credential` with a `base_url`, which would also block saving a new key with its own host. + +## 2026-11-24 — TD-5302: a lapse event for timed phone permissions (Class B) + +**Decision:** a new loopback-only event `phone_permission_lapsed` +(`capability`, `label`, `expired_at`), sent once per grant by the existing +expiry timer, which now snapshots the grants when it is armed and, when it +fires, reports each one that was on with an expiry and is no longer live. +The window shows it as a banner, like `phone_change`. + +**Rationale:** expiry was already enforced (TD-5279: the policy reads the +clock on every message, so the timer only keeps windows current). The owner +asked that the computer *see* it lapse; a banner survives the person being +away when it happens. Re-arming on every change means a grant switched off +by hand is gone from the snapshot before the timer fires, so it is never +reported as a lapse. + +**Rejected:** telling the phone too (its pages already follow `setup_state`, +and the event names nothing a phone needs); a new shorter preset in the +dialog (one hour is the owner's own example and is already there). diff --git a/core/scripts/generate_protocol_fixtures.py b/core/scripts/generate_protocol_fixtures.py index c10c350a..431eecab 100644 --- a/core/scripts/generate_protocol_fixtures.py +++ b/core/scripts/generate_protocol_fixtures.py @@ -192,6 +192,7 @@ PairingCompleted, ParseJob, PhoneChange, + PhonePermissionLapsed, Ping, PlanPinned, PlanReview, @@ -1677,6 +1678,11 @@ capability="mcp_servers", summary="added MCP server 'files': npx files-server", ), + "phone_permission_lapsed": PhonePermissionLapsed( + capability="models_and_keys", + label="Adding models and keys", + expired_at="2026-11-20T19:00:00Z", + ), # One connected computer and one self-pair that is unreachable (TD-5015). "machine_list": MachineList( machines=[ diff --git a/core/tests/test_phone_grant_lapse.py b/core/tests/test_phone_grant_lapse.py new file mode 100644 index 00000000..2cf63ff9 --- /dev/null +++ b/core/tests/test_phone_grant_lapse.py @@ -0,0 +1,71 @@ +"""A timed phone permission runs out on the daemon's clock (owner decision #6, TD-5302). + +"Turn on for 1 hour" was already in Settings (TD-5279), and the policy +reads the clock on every message. What the computer did not get was a word +when it happened: the Settings row just read "Off" again. Now the daemon +tells the computer's windows, once per grant, and never a phone. +""" + +from __future__ import annotations + +import asyncio +import json +from pathlib import Path +from typing import Any + +from tests.test_add_model import _stop +from tests.test_mcp_peer import _drain, _fresh, _pair +from tests.test_models_on_phone import _seeded + +RENAME = {"type": "set_credential", "name": "Router", "credential": "openrouter"} + + +async def _until(ws: Any, kind: str) -> dict[str, Any]: + async with asyncio.timeout(10): + while True: + frame = dict(json.loads(await ws.recv())) + if frame["type"] == kind: + return frame + + +async def test_a_timed_grant_stops_and_the_computer_is_told(tmp_path: Path) -> None: + daemon, task, ws = await _seeded(tmp_path) + phone, _ = await _pair(daemon) + # The expiry is stored to the whole second, so a grant of n seconds + # lasts between n-1 and n: three leaves room for the first message. + grant = { + "type": "set_phone_permission", + "capability": "models_and_keys", + "enabled": True, + "expires_in_seconds": 3, + } + try: + state = await _fresh(ws, grant) + assert state["phone_permissions"]["models_and_keys"]["enabled"] is True + assert (await _fresh(phone, RENAME))["type"] == "setup_state" + + lapsed = await _until(ws, "phone_permission_lapsed") + assert lapsed["capability"] == "models_and_keys" + assert lapsed["label"] == "Adding models and keys" + assert lapsed["expired_at"] == state["phone_permissions"]["models_and_keys"]["expires_at"] + + refused = await _fresh(phone, {**RENAME, "name": "Again"}, want="error") + assert refused["code"] == "phone_permission_off" + assert daemon.config.credentials["openrouter"].name == "Router" + # The phone is not sent the lapse; only the computer's windows are. + assert all(f["type"] != "phone_permission_lapsed" for f in await _drain(phone)) + finally: + await phone.close() + await _stop(task, ws) + + +async def test_switching_off_by_hand_is_not_a_lapse(tmp_path: Path) -> None: + _daemon, task, ws = await _seeded(tmp_path) + base = {"type": "set_phone_permission", "capability": "models_and_keys"} + try: + await _fresh(ws, {**base, "enabled": True, "expires_in_seconds": 1}) + await _fresh(ws, {**base, "enabled": False}) + await asyncio.sleep(1.8) + assert all(f["type"] != "phone_permission_lapsed" for f in await _drain(ws)) + finally: + await _stop(task, ws) diff --git a/core/tstd/daemon.py b/core/tstd/daemon.py index 7117724f..9db6ce99 100644 --- a/core/tstd/daemon.py +++ b/core/tstd/daemon.py @@ -222,6 +222,9 @@ UNATTENDED_RUNS, utc_now, ) +from .phone_permissions import ( + LABELS as PHONE_LABELS, +) from .phone_store import PhoneStore, server_saved_summary, value_summary from .plan_review import answer as answer_plan from .plan_review import keep_pinned_plan_visible, restore_pinned_plan, restored_plan_mode @@ -383,6 +386,8 @@ PairingCompleted, ParseJob, PhoneChange, + PhonePermissionLapsed, + PhonePermissionState, PolicyRules, PresetReadiness, PresetRoles, @@ -6045,6 +6050,7 @@ def _arm_phone_permission_expiry(self) -> None: until = self.phone_store.next_expiry() if until is None: return + before = self.phone_store.states() async def _wait() -> None: # A task copies the context it was made in: without this the @@ -6052,13 +6058,35 @@ async def _wait() -> None: _ANSWERING.set(None) await asyncio.sleep(max(0.0, (until - utc_now()).total_seconds()) + 0.5) self._phone_expiry_task = None - log.info("phone permission expired") + await self._tell_phone_permissions_lapsed(before) await self._tell_other_windows_the_catalog() self._arm_phone_permission_expiry() self._phone_expiry_task = asyncio.create_task(_wait(), name="phone-permission-expiry") self._tasks.append(self._phone_expiry_task) + async def _tell_phone_permissions_lapsed(self, before: dict[str, PhonePermissionState]) -> None: + """TD-5302: each timed grant that was on and is off now, to the computer's windows. + + Only a lapse: a grant switched off by hand re-arms the timer first, + so it is never in *before* when this runs. + """ + live = self.phone_store.live() + for capability, state in before.items(): + if not state.enabled or state.expires_at is None or capability in live: + continue + label = PHONE_LABELS.get(capability, capability) + log.info( + "phone permission expired", + extra={"extra_fields": {"capability": capability, "expired_at": state.expires_at}}, + ) + event = PhonePermissionLapsed( + capability=capability, label=label, expired_at=state.expires_at + ) + await self.ws_server.broadcast( + scrub_wire_json(event.model_dump_json()), loopback_only=True + ) + def _servers_added_by(self, device_id: str) -> list[str]: """The MCP servers a device added or changed that are still listed.""" return [ diff --git a/core/tstd/protocol.py b/core/tstd/protocol.py index aa43fad4..10bfd8dd 100644 --- a/core/tstd/protocol.py +++ b/core/tstd/protocol.py @@ -4256,6 +4256,22 @@ class PhoneChange(DaemonEvent): summary: str +class PhonePermissionLapsed(DaemonEvent): + """A timed phone permission ran out (TD-5302). + + Broadcast to loopback clients only, once per grant, when the daemon's + expiry timer fires. The policy already refuses at the expiry instant; + this tells the person at the computer that it happened. ``label`` is + the permission's name as Settings shows it. Connection-scoped, seq 1. + """ + + type: Literal["phone_permission_lapsed"] = "phone_permission_lapsed" + seq: int = 1 + capability: str + label: str + expired_at: str + + MachineStatus = Literal["connected", "connecting", "unreachable", "refused", "locked", "outdated"] @@ -5488,6 +5504,7 @@ class GoogleStatus(DaemonEvent): | PairingCode | PairingCompleted | PhoneChange + | PhonePermissionLapsed | McpImportPreview | MachineList | DrainResult @@ -5762,6 +5779,7 @@ class GoogleStatus(DaemonEvent): "pairing_code", "pairing_completed", "phone_change", + "phone_permission_lapsed", "mcp_import_preview", "machine_list", "drain_result", diff --git a/docs/architecture.md b/docs/architecture.md index eb6f92dc..d59db615 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -809,6 +809,7 @@ are stamped by a session's event log, `connection` events fix it at 1, and `ping | `pairing_completed` | connection | A phone redeemed the code. Carries that device's summary (never its key). Sent to the computer's own loopback windows only (TD-5014). | | `mcp_import_preview` | connection | Reply to `preview_mcp_import`: per server its proposed `id`, `transport`, `command` or `url`, `off_box`, `exists`, `refused` (why it cannot be imported), `not_imported` keys, `notes`, and per value its `name`, `target` and `disposition` (`keychain`, `literal`, `needs_input`). Never a value. `error` is set when the text could not be read, with a position and not the text (TD-5253). | | `phone_change` | connection | A paired phone used a phone permission: `device_name`, `capability` and a one-sentence `summary` (for an MCP server the command or address; for a value its name, never the value). Sent to the computer's own loopback windows only, each time (TD-5279). | +| `phone_permission_lapsed` | connection | A timed phone permission ran out: `capability`, `label` (its Settings name) and `expired_at`. Sent once per grant when the daemon's expiry timer fires, to the computer's own windows only, never a phone or another computer; a grant switched off by hand sends none. The policy already refuses at the expiry instant; this is how the computer is told (TD-5302). | | `api_key_validated` | connection | The result of a key probe. `credential` echoes the request's, so Settings → API keys shows the verdict on that key's row; null when the request named none (TD-5200). Sent within 20 s (`KEY_TEST_LIMIT_S`): a server that has not answered by then is reported as no answer. Replies come in request order, and the window ties each verdict to its request by that order, which also places an older daemon's unnamed verdict. Never carries the key. | | `endpoint_models` | connection | A server's model list for "Add a model", or why it could not be read. Never carries the key. | | `local_servers` | connection | The servers on this computer that answered `scan_local_servers` with models, in config order, and every URL asked. | diff --git a/docs/tst-desk-backlog.md b/docs/tst-desk-backlog.md index ff984253..68740dec 100644 --- a/docs/tst-desk-backlog.md +++ b/docs/tst-desk-backlog.md @@ -14760,3 +14760,22 @@ daemon down. why. **Size:** 3 · **Depends on:** TD-5182, TD-5279, TD-5296, TD-5297 · **Status:** Done + +### TD-5302 — The computer is told when a timed phone permission runs out + +Owner decision #6: a phone permission can be granted for a limited time, +the daemon enforces the expiry, and the computer sees it lapse. TD-5279 +already had "Turn on for 1 hour" (up to seven days through the protocol), +kept the expiry in `phone-permissions.yaml`, and had the policy read the +clock on every message. What was missing was the last part: the Settings +row just read "Off" again. + +- [x] A grant with an expiry is honoured until then and refused from the + first message after, on the daemon's clock, with no window open + (`test_phone_grant_lapse.py`, a three-second grant over the wire). +- [x] When it runs out the computer's windows get `phone_permission_lapsed`, + once, and show a banner naming the permission and where to turn it on + again; a phone is not sent it. +- [x] Switching a timed grant off by hand sends no lapse. + +**Size:** 2 · **Depends on:** TD-5279 · **Status:** Done diff --git a/ui/src/lib/client.ts b/ui/src/lib/client.ts index 552cf3d4..a1a278da 100644 --- a/ui/src/lib/client.ts +++ b/ui/src/lib/client.ts @@ -102,6 +102,7 @@ const KNOWN_EVENT_TYPES = new Set([ "pairing_code", // TD-5014 "pairing_completed", // TD-5014 "phone_change", // TD-5279 + "phone_permission_lapsed", // TD-5302 "schedule_proposal", // TD-5263 "schedule_proposal_decision", "worker_jobs", // TD-5299 diff --git a/ui/src/lib/notifications.svelte.ts b/ui/src/lib/notifications.svelte.ts index 2f407155..2a596673 100644 --- a/ui/src/lib/notifications.svelte.ts +++ b/ui/src/lib/notifications.svelte.ts @@ -28,7 +28,7 @@ import { type NoticeSpec, } from "./error-copy"; import { claimedInline } from "./inline-errors"; -import { phoneChangeNotice } from "./phone-permissions"; +import { phoneChangeNotice, phoneLapseNotice } from "./phone-permissions"; import type { DaemonEventUnion } from "./protocol"; import { redact } from "./redact"; import { session } from "./session-status.svelte.js"; @@ -161,6 +161,10 @@ export function notifyEvent(event: DaemonEventUnion): void { // change, kept until dismissed: nobody may be watching when it lands. notify(`phone:${event.device_name}:${event.summary}`, phoneChangeNotice(event)); break; + case "phone_permission_lapsed": + // TD-5302: a timed grant ran out. Phones lost it at that moment. + notify(`phone-lapse:${event.capability}:${event.expired_at}`, phoneLapseNotice(event)); + break; case "error": // A form already showed it, in words for that flow (TD-5015). if (claimedInline(event)) break; diff --git a/ui/src/lib/phone-permissions.test.ts b/ui/src/lib/phone-permissions.test.ts index 48aaad60..7d16745d 100644 --- a/ui/src/lib/phone-permissions.test.ts +++ b/ui/src/lib/phone-permissions.test.ts @@ -30,6 +30,7 @@ import { originWords, permissionCopy, phoneChangeNotice, + phoneLapseNotice, stateWords, } from "./phone-permissions"; @@ -389,6 +390,33 @@ describe("Settings → Policy, the skip-all switch", () => { }); }); +describe("when a timed permission runs out (TD-5302)", () => { + const event = { + type: "phone_permission_lapsed", + seq: 1, + capability: "models_and_keys", + label: "Adding models and keys", + expired_at: "2026-11-20T19:00:00Z", + } as const; + + it("the computer's window keeps one banner saying which one and where to turn it on", () => { + const notice = phoneLapseNotice(event); + expect(notice.severity).toBe("banner"); + expect(notice.title).toBe("A phone permission ran out"); + expect(notice.body).toMatch(/^Adding models and keys is off again for paired phones at /); + expect(notice.body).toContain("Settings, Phones and devices"); + notifyEvent(event as DaemonEventUnion); + notifyEvent(event as DaemonEventUnion); + expect(toasts).toHaveLength(0); + expect(banners).toHaveLength(1); + }); + + it("an unreadable time still names the permission", () => { + const body = phoneLapseNotice({ ...event, expired_at: "soon" }).body; + expect(body.startsWith("Adding models and keys is off again for paired phones.")).toBe(true); + }); +}); + describe("when a phone uses a permission", () => { const event = { type: "phone_change", diff --git a/ui/src/lib/phone-permissions.ts b/ui/src/lib/phone-permissions.ts index f00756c8..6d5aee21 100644 --- a/ui/src/lib/phone-permissions.ts +++ b/ui/src/lib/phone-permissions.ts @@ -4,7 +4,7 @@ // permission on, and a softer sentence here would be a weaker warning. import type { NoticeSpec } from "./error-copy"; -import type { PhoneChange, PhonePermissionState } from "./protocol"; +import type { PhoneChange, PhonePermissionLapsed, PhonePermissionState } from "./protocol"; export interface PhonePermissionCopy { capability: string; @@ -156,6 +156,19 @@ export function originWords(device: string | undefined, at: string | undefined): * not a toast: the person may be away from the screen when it happens, and * it stays until they dismiss it. */ +/** What the computer's window shows when a timed phone permission runs out. */ +export function phoneLapseNotice(event: PhonePermissionLapsed): NoticeSpec { + const at = new Date(event.expired_at); + const time = Number.isNaN(at.getTime()) + ? "" + : ` at ${at.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}`; + return { + severity: "banner", + title: "A phone permission ran out", + body: `${event.label} is off again for paired phones${time}. Turn it on under Settings, Phones and devices if you still need it.`, + }; +} + export function phoneChangeNotice(event: PhoneChange): NoticeSpec { return { severity: "banner", diff --git a/ui/src/lib/protocol-fixtures.json b/ui/src/lib/protocol-fixtures.json index bae8a249..1a799df0 100644 --- a/ui/src/lib/protocol-fixtures.json +++ b/ui/src/lib/protocol-fixtures.json @@ -2505,6 +2505,13 @@ "capability": "mcp_servers", "summary": "added MCP server 'files': npx files-server" }, + "phone_permission_lapsed": { + "type": "phone_permission_lapsed", + "seq": 1, + "capability": "models_and_keys", + "label": "Adding models and keys", + "expired_at": "2026-11-20T19:00:00Z" + }, "machine_list": { "type": "machine_list", "seq": 1, diff --git a/ui/src/lib/protocol.ts b/ui/src/lib/protocol.ts index c9d08c22..daba98fa 100644 --- a/ui/src/lib/protocol.ts +++ b/ui/src/lib/protocol.ts @@ -2668,6 +2668,14 @@ export interface PhoneChange extends DaemonEvent { summary: string; } +/** A timed phone permission ran out (TD-5302). Loopback windows only. */ +export interface PhonePermissionLapsed extends DaemonEvent { + type: "phone_permission_lapsed"; + capability: string; + label: string; + expired_at: string; +} + export interface McpServerSummary { id: string; transport: "stdio" | "http"; @@ -3672,6 +3680,7 @@ export type DaemonEventUnion = | PairingCode | PairingCompleted | PhoneChange + | PhonePermissionLapsed | ScheduleProposal | ScheduleProposalDecision | WorkerJobs