Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions DECISIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
6 changes: 6 additions & 0 deletions core/scripts/generate_protocol_fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@
PairingCompleted,
ParseJob,
PhoneChange,
PhonePermissionLapsed,
Ping,
PlanPinned,
PlanReview,
Expand Down Expand Up @@ -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=[
Expand Down
71 changes: 71 additions & 0 deletions core/tests/test_phone_grant_lapse.py
Original file line number Diff line number Diff line change
@@ -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)
30 changes: 29 additions & 1 deletion core/tstd/daemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -383,6 +386,8 @@
PairingCompleted,
ParseJob,
PhoneChange,
PhonePermissionLapsed,
PhonePermissionState,
PolicyRules,
PresetReadiness,
PresetRoles,
Expand Down Expand Up @@ -6045,20 +6050,43 @@ 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
# window that granted would be left out as "already answered".
_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 [
Expand Down
18 changes: 18 additions & 0 deletions core/tstd/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]


Expand Down Expand Up @@ -5488,6 +5504,7 @@ class GoogleStatus(DaemonEvent):
| PairingCode
| PairingCompleted
| PhoneChange
| PhonePermissionLapsed
| McpImportPreview
| MachineList
| DrainResult
Expand Down Expand Up @@ -5762,6 +5779,7 @@ class GoogleStatus(DaemonEvent):
"pairing_code",
"pairing_completed",
"phone_change",
"phone_permission_lapsed",
"mcp_import_preview",
"machine_list",
"drain_result",
Expand Down
1 change: 1 addition & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
19 changes: 19 additions & 0 deletions docs/tst-desk-backlog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
1 change: 1 addition & 0 deletions ui/src/lib/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion ui/src/lib/notifications.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand Down
28 changes: 28 additions & 0 deletions ui/src/lib/phone-permissions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
originWords,
permissionCopy,
phoneChangeNotice,
phoneLapseNotice,
stateWords,
} from "./phone-permissions";

Expand Down Expand Up @@ -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",
Expand Down
15 changes: 14 additions & 1 deletion ui/src/lib/phone-permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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",
Expand Down
7 changes: 7 additions & 0 deletions ui/src/lib/protocol-fixtures.json
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
9 changes: 9 additions & 0 deletions ui/src/lib/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -3672,6 +3680,7 @@ export type DaemonEventUnion =
| PairingCode
| PairingCompleted
| PhoneChange
| PhonePermissionLapsed
| ScheduleProposal
| ScheduleProposalDecision
| WorkerJobs
Expand Down
Loading