Skip to content
TypeScript

fix(web): keep usage-limit wake action visible (#23803)

Julius Marmingef41617580439
diff --git a/apps/web/src/components/chat/UsageLimitRecoveryBanner.tsx b/apps/web/src/components/chat/UsageLimitRecoveryBanner.tsx
index dc7ea2de2d5..3d0a1d4ffc1 100644
--- a/apps/web/src/components/chat/UsageLimitRecoveryBanner.tsx
+++ b/apps/web/src/components/chat/UsageLimitRecoveryBanner.tsx
@@ -46,13 +46,17 @@ function RecoveryActions({ runId, resetAt, recovery, snoozedUntil, onChange }: R
const scheduled =
recovery?.runId === runId && recovery.resetAt === resetAt && recovery.autoResume;
+ // The server leaves snoozedUntil in place after the timer wakes the thread,
+ // so a snooze whose reset has passed is no longer active.
+ const resetPassed = Date.parse(resetAt ?? "") <= nowMs;
const snoozed =
recovery?.snooze === true &&
recovery.runId === runId &&
recovery.resetAt === resetAt &&
resetAt !== null &&
snoozedUntil !== null &&
- Date.parse(snoozedUntil) === Date.parse(resetAt);
+ Date.parse(snoozedUntil) === Date.parse(resetAt) &&
+ !resetPassed;
async function toggle(action: "resume" | "snooze") {
if (resetAt === null) return;
if (action === "snooze" && !snoozed && Date.parse(resetAt) <= Date.now()) {
@@ -87,16 +91,14 @@ function RecoveryActions({ runId, resetAt, recovery, snoozedUntil, onChange }: R
<Button size="xs" variant="ghost" disabled={pending} onClick={() => void toggle("resume")}>
{pending ? "Saving..." : scheduled ? "Cancel auto-resume" : "Resume at reset"}
</Button>
- {!snoozed ? (
- <Button
- size="xs"
- variant="ghost"
- disabled={pending || Date.parse(resetAt!) <= nowMs}
- onClick={() => void toggle("snooze")}
- >
- {pending ? "Saving..." : "Snooze until reset"}
- </Button>
- ) : null}
+ <Button
+ size="xs"
+ variant="ghost"
+ disabled={pending || (!snoozed && resetPassed)}
+ onClick={() => void toggle("snooze")}
+ >
+ {pending ? "Saving..." : snoozed ? "Wake now" : "Snooze until reset"}
+ </Button>
</>
);
}
diff --git a/scripts/fixtures/issue-21397.json b/scripts/fixtures/issue-21397.json
new file mode 100644
index 00000000000..0d725992817
--- /dev/null
+++ b/scripts/fixtures/issue-21397.json
@@ -0,0 +1,141 @@
+{
+ "orchestration_v2_projection_threads": [
+ {
+ "thread_id": "issue-21397-thread",
+ "project_id": "issue-21397-project",
+ "title": "Usage limit banner reproduction",
+ "default_provider": "claudeAgent",
+ "runtime_mode": "full-access",
+ "interaction_mode": "default",
+ "active_provider_thread_id": "issue-21397-provider_threads-1",
+ "created_at": "2026-10-22T13:06:24.657Z",
+ "updated_at": "2026-10-22T13:39:08.247Z",
+ "archived_at": null,
+ "deleted_at": null,
+ "payload_json": "{\"createdBy\": \"user\", \"creationSource\": \"web\", \"id\": \"issue-21397-thread\", \"projectId\": \"issue-21397-project\", \"title\": \"Usage limit banner reproduction\", \"providerInstanceId\": \"claudeAgent\", \"modelSelection\": {\"instanceId\": \"claudeAgent\", \"model\": \"claude-opus-5-5\"}, \"runtimeMode\": \"full-access\", \"interactionMode\": \"default\", \"branch\": null, \"worktreePath\": null, \"pullRequests\": [], \"activeProviderThreadId\": \"issue-21397-provider_threads-1\", \"linkOrigin\": null, \"delegatedFrom\": null, \"lineage\": {\"parentThreadId\": null, \"relationshipToParent\": null, \"rootThreadId\": \"issue-21397-thread\"}, \"forkedFrom\": null, \"createdAt\": \"2026-10-22T13:06:24.657Z\", \"updatedAt\": \"2026-10-22T13:39:08.247Z\", \"archivedAt\": null, \"settledOverride\": null, \"settledAt\": null, \"snoozedUntil\": \"2026-10-23T08:50:00.000Z\", \"snoozedAt\": \"2026-10-22T19:00:00.000Z\", \"lastVisitedAt\": \"2026-10-22T13:06:24.675Z\", \"deletedAt\": null, \"limitRecovery\": {\"runId\": \"issue-21397-runs-1\", \"resetAt\": \"2026-10-23T08:50:00.000Z\", \"autoResume\": false, \"snooze\": true}}",
+ "provider_instance_id": "claudeAgent"
+ }
+ ],
+ "orchestration_v2_projection_runs": [
+ {
+ "run_id": "issue-21397-runs-1",
+ "thread_id": "issue-21397-thread",
+ "ordinal": 1,
+ "provider": "claudeAgent",
+ "provider_thread_id": "issue-21397-provider_threads-1",
+ "status": "failed",
+ "requested_at": "2026-10-22T13:06:24.676Z",
+ "completed_at": "2026-10-22T19:00:00.000Z",
+ "payload_json": "{\"id\":\"issue-21397-runs-1\",\"threadId\":\"issue-21397-thread\",\"ordinal\":1,\"providerInstanceId\":\"claudeAgent\",\"modelSelection\":{\"instanceId\":\"claudeAgent\",\"model\":\"claude-opus-5-5\"},\"providerThreadId\":\"issue-21397-provider_threads-1\",\"userMessageId\":\"issue-21397-thread\",\"rootNodeId\":\"issue-21397-nodes-1\",\"activeAttemptId\":\"issue-21397-run_attempts-1\",\"status\":\"failed\",\"queuePosition\":null,\"requestedAt\":\"2026-10-22T13:06:24.676Z\",\"startedAt\":\"2026-10-22T13:06:24.761Z\",\"completedAt\":\"2026-10-22T19:00:00.000Z\",\"checkpointId\":null,\"contextHandoffId\":null,\"workspacePreparation\":{\"type\":\"root\"}}",
+ "provider_instance_id": "claudeAgent"
+ }
+ ],
+ "orchestration_v2_projection_run_attempts": [
+ {
+ "attempt_id": "issue-21397-run_attempts-1",
+ "thread_id": "issue-21397-thread",
+ "run_id": "issue-21397-runs-1",
+ "attempt_ordinal": 1,
+ "root_node_id": "issue-21397-nodes-1",
+ "provider": "claudeAgent",
+ "provider_thread_id": "issue-21397-provider_threads-1",
+ "provider_turn_id": null,
+ "status": "completed",
+ "payload_json": "{\"id\":\"issue-21397-run_attempts-1\",\"nativeThreadId\":\"issue-21397-native\",\"runId\":\"issue-21397-runs-1\",\"attemptOrdinal\":1,\"rootNodeId\":\"issue-21397-nodes-1\",\"providerInstanceId\":\"claudeAgent\",\"providerThreadId\":\"issue-21397-provider_threads-1\",\"providerTurnId\":null,\"reason\":\"initial\",\"status\":\"completed\",\"startedAt\":\"2026-10-22T13:06:24.761Z\",\"completedAt\":\"2026-10-22T13:09:08.234Z\"}",
+ "provider_instance_id": "claudeAgent"
+ }
+ ],
+ "orchestration_v2_projection_nodes": [
+ {
+ "node_id": "issue-21397-nodes-1",
+ "thread_id": "issue-21397-thread",
+ "run_id": "issue-21397-runs-1",
+ "parent_node_id": null,
+ "root_node_id": "issue-21397-nodes-1",
+ "kind": "root_turn",
+ "status": "completed",
+ "provider_thread_id": "issue-21397-provider_threads-1",
+ "provider_turn_id": null,
+ "runtime_request_id": null,
+ "checkpoint_scope_id": null,
+ "started_at": "2026-10-22T13:06:24.761Z",
+ "completed_at": "2026-10-22T13:09:08.253Z",
+ "payload_json": "{\"id\":\"issue-21397-nodes-1\",\"threadId\":\"issue-21397-thread\",\"runId\":\"issue-21397-runs-1\",\"parentNodeId\":null,\"rootNodeId\":\"issue-21397-nodes-1\",\"kind\":\"root_turn\",\"status\":\"completed\",\"countsForRun\":true,\"providerThreadId\":\"issue-21397-provider_threads-1\",\"providerTurnId\":null,\"nativeItemRef\":null,\"runtimeRequestId\":null,\"checkpointScopeId\":null,\"startedAt\":\"2026-10-22T13:06:24.761Z\",\"completedAt\":\"2026-10-22T13:09:08.253Z\"}"
+ }
+ ],
+ "orchestration_v2_projection_provider_threads": [
+ {
+ "provider_thread_id": "issue-21397-provider_threads-1",
+ "thread_id": "issue-21397-thread",
+ "owner_node_id": null,
+ "provider": "claudeAgent",
+ "provider_session_id": null,
+ "status": "idle",
+ "first_run_ordinal": 1,
+ "last_run_ordinal": 1,
+ "updated_at": "2026-10-22T13:09:08.234Z",
+ "payload_json": "{\"id\": \"issue-21397-provider_threads-1\", \"driver\": \"claudeAgent\", \"providerInstanceId\": \"claudeAgent\", \"providerSessionId\": null, \"appThreadId\": \"issue-21397-thread\", \"ownerNodeId\": null, \"nativeConversationHeadRef\": null, \"status\": \"idle\", \"firstRunOrdinal\": 1, \"lastRunOrdinal\": 1, \"handoffIds\": [], \"forkedFrom\": null, \"pendingBackgroundTasks\": [], \"contextUsage\": null, \"nativeMetadata\": null, \"goal\": null, \"createdAt\": \"2026-10-22T13:06:24.676Z\", \"updatedAt\": \"2026-10-22T13:09:08.234Z\", \"nativeThreadRef\": {\"driver\": \"claudeAgent\", \"nativeId\": \"issue-21397-native\", \"strength\": \"strong\"}}",
+ "driver": "claudeAgent",
+ "provider_instance_id": "claudeAgent"
+ }
+ ],
+ "orchestration_v2_projection_provider_turns": [
+ {
+ "provider_turn_id": "issue-21397-provider_turns-1",
+ "thread_id": "issue-21397-thread",
+ "provider_thread_id": "issue-21397-provider_threads-1",
+ "node_id": "issue-21397-nodes-1",
+ "run_attempt_id": "issue-21397-run_attempts-1",
+ "ordinal": 1,
+ "status": "completed",
+ "started_at": "2026-10-22T13:06:25.539Z",
+ "completed_at": "2026-10-22T13:09:08.225Z",
+ "payload_json": "{\"id\": \"issue-21397-provider_turns-1\", \"providerThreadId\": \"issue-21397-provider_threads-1\", \"nodeId\": \"issue-21397-nodes-1\", \"runAttemptId\": \"issue-21397-run_attempts-1\", \"nativeTurnRef\": null, \"ordinal\": 1, \"status\": \"completed\", \"startedAt\": \"2026-10-22T13:06:25.539Z\", \"completedAt\": \"2026-10-22T13:09:08.225Z\"}"
+ }
+ ],
+ "orchestration_v2_projection_messages": [
+ {
+ "message_id": "issue-21397-thread",
+ "thread_id": "issue-21397-thread",
+ "run_id": "issue-21397-runs-1",
+ "node_id": "issue-21397-nodes-1",
+ "role": "user",
+ "streaming": 0,
+ "created_at": "2026-10-22T13:06:24.676Z",
+ "updated_at": "2026-10-22T13:06:24.676Z",
+ "payload_json": "{\"createdBy\":\"agent\",\"creationSource\":\"mcp\",\"id\":\"issue-21397-thread\",\"threadId\":\"issue-21397-thread\",\"runId\":\"issue-21397-runs-1\",\"nodeId\":\"issue-21397-nodes-1\",\"role\":\"user\",\"text\":\"Please summarize this sample project.\",\"attachments\":[],\"streaming\":false,\"createdAt\":\"2026-10-22T13:06:24.676Z\",\"updatedAt\":\"2026-10-22T13:06:24.676Z\"}"
+ }
+ ],
+ "orchestration_v2_projection_turn_items": [
+ {
+ "turn_item_id": "issue-21397-turn_items-1",
+ "thread_id": "issue-21397-thread",
+ "run_id": "issue-21397-runs-1",
+ "node_id": "issue-21397-nodes-1",
+ "provider_thread_id": null,
+ "provider_turn_id": null,
+ "parent_item_id": null,
+ "ordinal": 9999999,
+ "type": "error",
+ "status": "failed",
+ "updated_at": "2026-10-22T19:00:00.000Z",
+ "payload_json": "{\"id\":\"issue-21397-turn_items-1\",\"threadId\":\"issue-21397-thread\",\"runId\":\"issue-21397-runs-1\",\"nodeId\":\"issue-21397-nodes-1\",\"providerThreadId\":null,\"providerTurnId\":null,\"nativeItemRef\":null,\"parentItemId\":null,\"ordinal\":9999999,\"type\":\"error\",\"status\":\"failed\",\"title\":\"Usage limit reached\",\"startedAt\":\"2026-10-22T19:00:00.000Z\",\"completedAt\":\"2026-10-22T19:00:00.000Z\",\"updatedAt\":\"2026-10-22T19:00:00.000Z\",\"failure\":{\"class\":\"usage_limit\",\"message\":\"Usage limit reached\",\"code\":\"usageLimitExceeded\",\"retryable\":null,\"resetAt\":\"2026-10-23T08:50:00.000Z\"}}"
+ }
+ ],
+ "projection_projects": [
+ {
+ "project_id": "issue-21397-project",
+ "title": "Sample project",
+ "workspace_root": "__WORKTREE__",
+ "scripts_json": "[]",
+ "created_at": "2026-10-19T00:39:38.662Z",
+ "updated_at": "2026-10-19T00:39:38.662Z",
+ "deleted_at": null,
+ "default_model_selection_json": null,
+ "default_thread_env_mode": null,
+ "favicon_path": null,
+ "auto_pull": 0,
+ "project_icon_json": null
+ }
+ ]
+}
diff --git a/scripts/seed-issue-21397.py b/scripts/seed-issue-21397.py
new file mode 100644
index 00000000000..86c6e8ce461
--- /dev/null
+++ b/scripts/seed-issue-21397.py
@@ -0,0 +1,112 @@
+#!/usr/bin/env python3
+"""python3 scripts/seed-issue-21397.py --home NEW_DIR [matching|absent|unrelated] [--now [ISO]] [--source DB].
+
+Copies a migrated statev2.sqlite (default: this worktree's .t3, with dev stopped;
+run dev once first to migrate it) into NEW_DIR/userdata, then replaces every
+thread/project projection in that copy with a synthetic stopped usage-limit run.
+The source is only read as bytes, never opened by SQLite, so it stays unchanged.
+NEW_DIR must not exist and must not be under the live ~/.t3. Then run the printed
+`vp run dev --home-dir NEW_DIR`.
+
+Fixture times are frozen around the evidence clock, 2026-10-22T19:00:00Z (usage
+limit hit; reset and matching snooze at 2026-10-23T08:50:00Z). By default they
+are seeded unchanged, reproducing the PR captures. After that reset, pass --now
+(current time) or --now ISO to shift every timestamp so the failure happens then.
+"""
+import argparse
+import contextlib
+import datetime
+import json
+import pathlib
+import re
+import shlex
+import shutil
+import sqlite3
+
+EVIDENCE_CLOCK = datetime.datetime(2026, 10, 22, 19, tzinfo=datetime.timezone.utc)
+ISO = re.compile(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$')
+
+
+def parse_iso(value):
+ parsed = datetime.datetime.fromisoformat(value.replace('Z', '+00:00'))
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=datetime.timezone.utc)
+
+
+def shift(value, delta):
+ if isinstance(value, dict):
+ return {k: shift(v, delta) for k, v in value.items()}
+ if isinstance(value, str) and ISO.match(value):
+ moved = parse_iso(value) + delta
+ return moved.strftime('%Y-%m-%dT%H:%M:%S.') + f'{moved.microsecond // 1000:03d}Z'
+ return value
+
+
+root = pathlib.Path(__file__).resolve().parent.parent
+parser = argparse.ArgumentParser()
+parser.add_argument('mode', nargs='?', default='matching', choices=('matching', 'absent', 'unrelated'))
+parser.add_argument('--home', required=True, type=pathlib.Path, help='new T3 home to create; must not exist')
+parser.add_argument('--source', type=pathlib.Path, default=root / '.t3/userdata/statev2.sqlite')
+parser.add_argument('--now', nargs='?', const='now', help='shift fixture times so the limit is hit at this ISO time')
+args = parser.parse_args()
+mode = args.mode
+now = None if args.now is None else datetime.datetime.now(datetime.timezone.utc) if args.now == 'now' else parse_iso(args.now)
+delta = datetime.timedelta() if now is None else now - EVIDENCE_CLOCK
+
+source = args.source.absolute()
+if source.is_symlink() or not source.is_file():
+ raise SystemExit(f'Expected a migrated statev2.sqlite regular file at {source}')
+# Resolve the parent, not the home itself, so a symlink at the home path is refused below.
+home = args.home.absolute().parent.resolve() / args.home.name
+live = (pathlib.Path.home() / '.t3').resolve()
+if not args.home.name or home == live or live in home.parents:
+ raise SystemExit(f'Refusing fixture home {home}: pick a new directory outside {live}')
+home.parent.mkdir(parents=True, exist_ok=True)
+try:
+ home.mkdir() # Atomic: fails on any existing file, directory, or symlink.
+except FileExistsError:
+ raise SystemExit(f'Refusing existing fixture home {home}: pick a new directory')
+
+try:
+ userdata = home / 'userdata'
+ userdata.mkdir()
+ path = userdata / 'statev2.sqlite'
+ shutil.copyfile(source, path)
+ wal = source.with_name(source.name + '-wal')
+ if wal.is_file() and not wal.is_symlink():
+ shutil.copyfile(wal, path.with_name(path.name + '-wal'))
+ fixture = json.loads((root / 'scripts/fixtures/issue-21397.json').read_text())
+ # closing() outlives the transaction so cleanup below never deletes an open database.
+ with contextlib.closing(sqlite3.connect(path)) as db, db:
+ # Drop copied conversations, including V1 tables the server could re-import.
+ tables = [r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type='table'")]
+ for table in tables:
+ if table.startswith('orchestration_v2_projection_') and table != 'orchestration_v2_projection_metadata':
+ db.execute(f'DELETE FROM "{table}"')
+ elif table.startswith('projection_thread') or table == 'projection_projects':
+ db.execute(f'DELETE FROM "{table}"')
+ db.execute("UPDATE orchestration_v2_effect_outbox SET status='cancelled' WHERE status IN ('pending','running')")
+ for table, rows in fixture.items():
+ for row in rows:
+ row = shift(dict(row), delta)
+ if table == 'projection_projects':
+ row['workspace_root'] = str(root)
+ if table == 'orchestration_v2_projection_threads':
+ payload = json.loads(row['payload_json'])
+ if mode == 'absent':
+ payload['snoozedUntil'] = None
+ elif mode == 'unrelated':
+ payload['snoozedUntil'] = '2026-10-24T08:50:00.000Z'
+ row['payload_json'] = json.dumps(shift(payload, delta))
+ elif delta and 'payload_json' in row:
+ row['payload_json'] = json.dumps(shift(json.loads(row['payload_json']), delta))
+ columns = ','.join(f'"{k}"' for k in row)
+ placeholders = ','.join('?' for _ in row)
+ db.execute(f'INSERT INTO "{table}" ({columns}) VALUES ({placeholders})', list(row.values()))
+ settings = dict(snoozeLimitedThreads=False, autoResumeLimitedThreads=False)
+ (userdata / 'settings.json').write_text(json.dumps(settings, indent=2) + '\n')
+except BaseException:
+ shutil.rmtree(home) # Created above by this run, so it holds nothing else.
+ raise
+hit = (now or EVIDENCE_CLOCK).astimezone(datetime.timezone.utc)
+print(f'Seeded synthetic {mode} fixture in {path} (limit hit at {hit:%Y-%m-%dT%H:%M:%SZ})')
+print(f'Run: vp run dev --home-dir {shlex.quote(str(home))}')
diff --git a/scripts/seed-issue-21397.test.py b/scripts/seed-issue-21397.test.py
new file mode 100644
index 00000000000..436eedd6593
--- /dev/null
+++ b/scripts/seed-issue-21397.test.py
@@ -0,0 +1,181 @@
+#!/usr/bin/env python3
+"""python3 scripts/seed-issue-21397.test.py — runs the seeder against synthetic SQLite files only."""
+import datetime
+import hashlib
+import json
+import os
+import pathlib
+import sqlite3
+import subprocess
+import sys
+import tempfile
+import unittest
+
+SCRIPT = pathlib.Path(__file__).resolve().with_name('seed-issue-21397.py')
+FIXTURE = json.loads(SCRIPT.with_name('fixtures').joinpath('issue-21397.json').read_text())
+# Windows cannot delete a file SQLite still holds open, so cleanup must close connections first.
+OPEN_DB_PROBE = '''
+import runpy, shutil, sqlite3, sys
+opened, connect, rmtree = [], sqlite3.connect, shutil.rmtree
+def tracked(*args, **kwargs):
+ opened.append(connect(*args, **kwargs))
+ return opened[-1]
+def checked(*args, **kwargs):
+ for db in opened:
+ try:
+ db.total_changes
+ except sqlite3.ProgrammingError:
+ continue
+ sys.exit('rmtree ran while a SQLite connection was open')
+ return rmtree(*args, **kwargs)
+sqlite3.connect, shutil.rmtree = tracked, checked
+sys.argv = sys.argv[1:]
+runpy.run_path(sys.argv[0], run_name='__main__')
+'''
+
+
+def snapshot(directory):
+ return {
+ str(p.relative_to(directory)): hashlib.sha256(p.read_bytes()).hexdigest() if p.is_file() else 'dir'
+ for p in sorted(directory.rglob('*'))
+ }
+
+
+class SeederTest(unittest.TestCase):
+ def setUp(self):
+ temp = tempfile.TemporaryDirectory()
+ self.addCleanup(temp.cleanup)
+ self.tmp = pathlib.Path(temp.name)
+ self.fake_home = self.tmp / 'user'
+ (self.fake_home / '.t3/userdata').mkdir(parents=True)
+ self.source_home = self.tmp / 'worktree/.t3/userdata'
+ self.source_home.mkdir(parents=True)
+ self.source = self.source_home / 'statev2.sqlite'
+ db = sqlite3.connect(self.source)
+ db.execute('PRAGMA journal_mode=WAL')
+ for table, rows in FIXTURE.items():
+ db.execute(f'CREATE TABLE "{table}" ({",".join(sorted({k for r in rows for k in r}))})')
+ db.execute(f'INSERT INTO "{table}" (thread_id) VALUES (?)' if table != 'projection_projects'
+ else f'INSERT INTO "{table}" (project_id) VALUES (?)', ['sentinel'])
+ db.execute('CREATE TABLE orchestration_v2_projection_metadata (key)')
+ db.execute("INSERT INTO orchestration_v2_projection_metadata VALUES ('kept')")
+ db.execute('CREATE TABLE projection_thread_messages (id)')
+ db.execute("INSERT INTO projection_thread_messages VALUES ('sentinel')")
+ db.execute('CREATE TABLE orchestration_v2_effect_outbox (status)')
+ db.executemany('INSERT INTO orchestration_v2_effect_outbox VALUES (?)', [('pending',), ('done',)])
+ db.commit()
+ db.close()
+ (self.source_home / 'settings.json').write_text('{"sentinel": true}\n')
+ self.before = snapshot(self.source_home)
+
+ def run_seeder(self, *args, probe=()):
+ env = {**os.environ, 'HOME': str(self.fake_home)}
+ return subprocess.run([sys.executable, '-I', *probe, str(SCRIPT), '--source', str(self.source), *args],
+ env=env, capture_output=True, text=True)
+
+ def assertSourceUnchanged(self):
+ self.assertEqual(snapshot(self.source_home), self.before)
+
+ def thread_payload(self, home):
+ with sqlite3.connect(home / 'userdata/statev2.sqlite') as db:
+ self.assertEqual(db.execute('SELECT count(*) FROM projection_thread_messages').fetchone(), (0,))
+ self.assertEqual(db.execute('SELECT key FROM orchestration_v2_projection_metadata').fetchall(), [('kept',)])
+ self.assertEqual(db.execute('SELECT status FROM orchestration_v2_effect_outbox ORDER BY 1').fetchall(),
+ [('cancelled',), ('done',)])
+ rows = db.execute('SELECT thread_id, payload_json FROM orchestration_v2_projection_threads').fetchall()
+ self.assertEqual(len(rows), 1)
+ self.assertNotEqual(rows[0][0], 'sentinel')
+ return json.loads(rows[0][1])
+
+ def test_seeds_a_fresh_copy_for_every_mode_and_clock(self):
+ snooze = json.loads(FIXTURE['orchestration_v2_projection_threads'][0]['payload_json'])['snoozedUntil']
+ clocks = [([], datetime.timedelta(), '2026-10-22T19:00:00Z'),
+ (['--now', '2026-11-01T12:30:00+02:00'], datetime.timedelta(days=9, hours=15, minutes=30),
+ '2026-11-01T10:30:00Z'),
+ (['--now'], None, None)]
+ for mode in ('matching', 'absent', 'unrelated'):
+ for clock_args, delta, logged in clocks:
+ with self.subTest(mode=mode, clock=clock_args):
+ home = self.tmp / 'fixtures' / f'{mode}-{len(clock_args)}'
+ started = datetime.datetime.now(datetime.timezone.utc)
+ result = self.run_seeder('--home', str(home), mode, *clock_args)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertSourceUnchanged()
+ if delta is None:
+ delta = started.replace(microsecond=0) - datetime.datetime(
+ 2026, 10, 22, 19, tzinfo=datetime.timezone.utc)
+ logged = None
+ if logged:
+ self.assertIn(f'(limit hit at {logged})', result.stdout)
+ self.assertIn(f'Run: vp run dev --home-dir {home}', result.stdout)
+ expected = {'matching': snooze, 'absent': None, 'unrelated': '2026-10-24T08:50:00.000Z'}[mode]
+ actual = self.thread_payload(home)['snoozedUntil']
+ if expected is None:
+ self.assertIsNone(actual)
+ else:
+ moved = datetime.datetime.fromisoformat(actual.replace('Z', '+00:00')) - delta
+ original = datetime.datetime.fromisoformat(expected.replace('Z', '+00:00'))
+ self.assertLess(abs(moved - original), datetime.timedelta(seconds=2))
+ self.assertEqual(json.loads((home / 'userdata/settings.json').read_text()),
+ {'snoozeLimitedThreads': False, 'autoResumeLimitedThreads': False})
+
+ def test_refuses_unsafe_destinations_without_touching_anything(self):
+ existing_dir = self.tmp / 'existing'
+ existing_dir.mkdir()
+ (existing_dir / 'keep').write_text('keep')
+ existing_file = self.tmp / 'file'
+ existing_file.write_text('keep')
+ link_to_dir = self.tmp / 'link-dir'
+ link_to_dir.symlink_to(existing_dir)
+ dangling = self.tmp / 'dangling'
+ dangling.symlink_to(self.tmp / 'missing')
+ live_link = self.tmp / 'live-link'
+ live_link.symlink_to(self.fake_home / '.t3')
+ cases = {
+ 'existing directory': existing_dir,
+ 'existing file': existing_file,
+ 'symlink to directory': link_to_dir,
+ 'dangling symlink': dangling,
+ 'source home': self.source_home.parent,
+ 'live home': self.fake_home / '.t3',
+ 'inside live home': self.fake_home / '.t3/fixture',
+ 'through symlink into live home': live_link / 'fixture',
+ }
+ for name, home in cases.items():
+ with self.subTest(name):
+ listing = sorted(str(p) for p in self.tmp.rglob('*'))
+ result = self.run_seeder('--home', str(home))
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn('Refusing', result.stderr)
+ self.assertSourceUnchanged()
+ self.assertEqual(sorted(str(p) for p in self.tmp.rglob('*')), listing)
+ self.assertEqual((existing_dir / 'keep').read_text(), 'keep')
+ self.assertFalse((self.tmp / 'missing').exists())
+
+ def test_refuses_missing_or_symlinked_source(self):
+ link = self.tmp / 'linked.sqlite'
+ link.symlink_to(self.source)
+ for source in (self.tmp / 'absent.sqlite', link):
+ with self.subTest(str(source)):
+ env = {**os.environ, 'HOME': str(self.fake_home)}
+ result = subprocess.run([sys.executable, '-I', str(SCRIPT), '--source', str(source),
+ '--home', str(self.tmp / 'new')], env=env, capture_output=True, text=True)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertFalse((self.tmp / 'new').exists())
+ self.assertSourceUnchanged()
+
+ def test_failed_seed_removes_only_its_new_home(self):
+ with sqlite3.connect(self.source) as db:
+ db.execute('DROP TABLE orchestration_v2_effect_outbox')
+ db.close()
+ self.before = snapshot(self.source_home)
+ home = self.tmp / 'broken'
+ result = self.run_seeder('--home', str(home), probe=('-c', OPEN_DB_PROBE))
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn('orchestration_v2_effect_outbox', result.stderr)
+ self.assertFalse(home.exists(), result.stderr)
+ self.assertSourceUnchanged()
+
+
+if __name__ == '__main__':
+ unittest.main()