@devries-cameron20 / t3code Mirror · read-only / commits / f416175804
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 18:15 UTC

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 23, 2026 at 20:17 UTC f41617580439f33ab55fa1ba100437a5b4c7d516
4 files changed +447 -11
apps/web/src/components/chat/UsageLimitRecoveryBanner.tsx
+13 -11
@@ -46,13 +46,17 @@ function RecoveryActions({ runId, resetAt, recovery, snoozedUntil, onChange }: R
46
47 const scheduled =
48 recovery?.runId === runId && recovery.resetAt === resetAt && recovery.autoResume;
49 + // The server leaves snoozedUntil in place after the timer wakes the thread,
50 + // so a snooze whose reset has passed is no longer active.
51 + const resetPassed = Date.parse(resetAt ?? "") <= nowMs;
52 const snoozed =
53 recovery?.snooze === true &&
54 recovery.runId === runId &&
55 recovery.resetAt === resetAt &&
56 resetAt !== null &&
57 snoozedUntil !== null &&
55 - Date.parse(snoozedUntil) === Date.parse(resetAt);
58 + Date.parse(snoozedUntil) === Date.parse(resetAt) &&
59 + !resetPassed;
60 async function toggle(action: "resume" | "snooze") {
61 if (resetAt === null) return;
62 if (action === "snooze" && !snoozed && Date.parse(resetAt) <= Date.now()) {
@@ -87,16 +91,14 @@ function RecoveryActions({ runId, resetAt, recovery, snoozedUntil, onChange }: R
91 <Button size="xs" variant="ghost" disabled={pending} onClick={() => void toggle("resume")}>
92 {pending ? "Saving..." : scheduled ? "Cancel auto-resume" : "Resume at reset"}
93 </Button>
90 - {!snoozed ? (
91 - <Button
92 - size="xs"
93 - variant="ghost"
94 - disabled={pending || Date.parse(resetAt!) <= nowMs}
95 - onClick={() => void toggle("snooze")}
96 - >
97 - {pending ? "Saving..." : "Snooze until reset"}
98 - </Button>
99 - ) : null}
94 + <Button
95 + size="xs"
96 + variant="ghost"
97 + disabled={pending || (!snoozed && resetPassed)}
98 + onClick={() => void toggle("snooze")}
99 + >
100 + {pending ? "Saving..." : snoozed ? "Wake now" : "Snooze until reset"}
101 + </Button>
102 </>
103 );
104 }
scripts/fixtures/issue-21397.json new
+141
@@ -0,0 +1,141 @@
1 +{
2 + "orchestration_v2_projection_threads": [
3 + {
4 + "thread_id": "issue-21397-thread",
5 + "project_id": "issue-21397-project",
6 + "title": "Usage limit banner reproduction",
7 + "default_provider": "claudeAgent",
8 + "runtime_mode": "full-access",
9 + "interaction_mode": "default",
10 + "active_provider_thread_id": "issue-21397-provider_threads-1",
11 + "created_at": "2026-10-22T13:06:24.657Z",
12 + "updated_at": "2026-10-22T13:39:08.247Z",
13 + "archived_at": null,
14 + "deleted_at": null,
15 + "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}}",
16 + "provider_instance_id": "claudeAgent"
17 + }
18 + ],
19 + "orchestration_v2_projection_runs": [
20 + {
21 + "run_id": "issue-21397-runs-1",
22 + "thread_id": "issue-21397-thread",
23 + "ordinal": 1,
24 + "provider": "claudeAgent",
25 + "provider_thread_id": "issue-21397-provider_threads-1",
26 + "status": "failed",
27 + "requested_at": "2026-10-22T13:06:24.676Z",
28 + "completed_at": "2026-10-22T19:00:00.000Z",
29 + "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\"}}",
30 + "provider_instance_id": "claudeAgent"
31 + }
32 + ],
33 + "orchestration_v2_projection_run_attempts": [
34 + {
35 + "attempt_id": "issue-21397-run_attempts-1",
36 + "thread_id": "issue-21397-thread",
37 + "run_id": "issue-21397-runs-1",
38 + "attempt_ordinal": 1,
39 + "root_node_id": "issue-21397-nodes-1",
40 + "provider": "claudeAgent",
41 + "provider_thread_id": "issue-21397-provider_threads-1",
42 + "provider_turn_id": null,
43 + "status": "completed",
44 + "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\"}",
45 + "provider_instance_id": "claudeAgent"
46 + }
47 + ],
48 + "orchestration_v2_projection_nodes": [
49 + {
50 + "node_id": "issue-21397-nodes-1",
51 + "thread_id": "issue-21397-thread",
52 + "run_id": "issue-21397-runs-1",
53 + "parent_node_id": null,
54 + "root_node_id": "issue-21397-nodes-1",
55 + "kind": "root_turn",
56 + "status": "completed",
57 + "provider_thread_id": "issue-21397-provider_threads-1",
58 + "provider_turn_id": null,
59 + "runtime_request_id": null,
60 + "checkpoint_scope_id": null,
61 + "started_at": "2026-10-22T13:06:24.761Z",
62 + "completed_at": "2026-10-22T13:09:08.253Z",
63 + "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\"}"
64 + }
65 + ],
66 + "orchestration_v2_projection_provider_threads": [
67 + {
68 + "provider_thread_id": "issue-21397-provider_threads-1",
69 + "thread_id": "issue-21397-thread",
70 + "owner_node_id": null,
71 + "provider": "claudeAgent",
72 + "provider_session_id": null,
73 + "status": "idle",
74 + "first_run_ordinal": 1,
75 + "last_run_ordinal": 1,
76 + "updated_at": "2026-10-22T13:09:08.234Z",
77 + "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\"}}",
78 + "driver": "claudeAgent",
79 + "provider_instance_id": "claudeAgent"
80 + }
81 + ],
82 + "orchestration_v2_projection_provider_turns": [
83 + {
84 + "provider_turn_id": "issue-21397-provider_turns-1",
85 + "thread_id": "issue-21397-thread",
86 + "provider_thread_id": "issue-21397-provider_threads-1",
87 + "node_id": "issue-21397-nodes-1",
88 + "run_attempt_id": "issue-21397-run_attempts-1",
89 + "ordinal": 1,
90 + "status": "completed",
91 + "started_at": "2026-10-22T13:06:25.539Z",
92 + "completed_at": "2026-10-22T13:09:08.225Z",
93 + "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\"}"
94 + }
95 + ],
96 + "orchestration_v2_projection_messages": [
97 + {
98 + "message_id": "issue-21397-thread",
99 + "thread_id": "issue-21397-thread",
100 + "run_id": "issue-21397-runs-1",
101 + "node_id": "issue-21397-nodes-1",
102 + "role": "user",
103 + "streaming": 0,
104 + "created_at": "2026-10-22T13:06:24.676Z",
105 + "updated_at": "2026-10-22T13:06:24.676Z",
106 + "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\"}"
107 + }
108 + ],
109 + "orchestration_v2_projection_turn_items": [
110 + {
111 + "turn_item_id": "issue-21397-turn_items-1",
112 + "thread_id": "issue-21397-thread",
113 + "run_id": "issue-21397-runs-1",
114 + "node_id": "issue-21397-nodes-1",
115 + "provider_thread_id": null,
116 + "provider_turn_id": null,
117 + "parent_item_id": null,
118 + "ordinal": 9999999,
119 + "type": "error",
120 + "status": "failed",
121 + "updated_at": "2026-10-22T19:00:00.000Z",
122 + "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\"}}"
123 + }
124 + ],
125 + "projection_projects": [
126 + {
127 + "project_id": "issue-21397-project",
128 + "title": "Sample project",
129 + "workspace_root": "__WORKTREE__",
130 + "scripts_json": "[]",
131 + "created_at": "2026-10-19T00:39:38.662Z",
132 + "updated_at": "2026-10-19T00:39:38.662Z",
133 + "deleted_at": null,
134 + "default_model_selection_json": null,
135 + "default_thread_env_mode": null,
136 + "favicon_path": null,
137 + "auto_pull": 0,
138 + "project_icon_json": null
139 + }
140 + ]
141 +}
scripts/seed-issue-21397.py new
+112
@@ -0,0 +1,112 @@
1 +#!/usr/bin/env python3
2 +"""python3 scripts/seed-issue-21397.py --home NEW_DIR [matching|absent|unrelated] [--now [ISO]] [--source DB].
3 +
4 +Copies a migrated statev2.sqlite (default: this worktree's .t3, with dev stopped;
5 +run dev once first to migrate it) into NEW_DIR/userdata, then replaces every
6 +thread/project projection in that copy with a synthetic stopped usage-limit run.
7 +The source is only read as bytes, never opened by SQLite, so it stays unchanged.
8 +NEW_DIR must not exist and must not be under the live ~/.t3. Then run the printed
9 +`vp run dev --home-dir NEW_DIR`.
10 +
11 +Fixture times are frozen around the evidence clock, 2026-10-22T19:00:00Z (usage
12 +limit hit; reset and matching snooze at 2026-10-23T08:50:00Z). By default they
13 +are seeded unchanged, reproducing the PR captures. After that reset, pass --now
14 +(current time) or --now ISO to shift every timestamp so the failure happens then.
15 +"""
16 +import argparse
17 +import contextlib
18 +import datetime
19 +import json
20 +import pathlib
21 +import re
22 +import shlex
23 +import shutil
24 +import sqlite3
25 +
26 +EVIDENCE_CLOCK = datetime.datetime(2026, 10, 22, 19, tzinfo=datetime.timezone.utc)
27 +ISO = re.compile(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$')
28 +
29 +
30 +def parse_iso(value):
31 + parsed = datetime.datetime.fromisoformat(value.replace('Z', '+00:00'))
32 + return parsed if parsed.tzinfo else parsed.replace(tzinfo=datetime.timezone.utc)
33 +
34 +
35 +def shift(value, delta):
36 + if isinstance(value, dict):
37 + return {k: shift(v, delta) for k, v in value.items()}
38 + if isinstance(value, str) and ISO.match(value):
39 + moved = parse_iso(value) + delta
40 + return moved.strftime('%Y-%m-%dT%H:%M:%S.') + f'{moved.microsecond // 1000:03d}Z'
41 + return value
42 +
43 +
44 +root = pathlib.Path(__file__).resolve().parent.parent
45 +parser = argparse.ArgumentParser()
46 +parser.add_argument('mode', nargs='?', default='matching', choices=('matching', 'absent', 'unrelated'))
47 +parser.add_argument('--home', required=True, type=pathlib.Path, help='new T3 home to create; must not exist')
48 +parser.add_argument('--source', type=pathlib.Path, default=root / '.t3/userdata/statev2.sqlite')
49 +parser.add_argument('--now', nargs='?', const='now', help='shift fixture times so the limit is hit at this ISO time')
50 +args = parser.parse_args()
51 +mode = args.mode
52 +now = None if args.now is None else datetime.datetime.now(datetime.timezone.utc) if args.now == 'now' else parse_iso(args.now)
53 +delta = datetime.timedelta() if now is None else now - EVIDENCE_CLOCK
54 +
55 +source = args.source.absolute()
56 +if source.is_symlink() or not source.is_file():
57 + raise SystemExit(f'Expected a migrated statev2.sqlite regular file at {source}')
58 +# Resolve the parent, not the home itself, so a symlink at the home path is refused below.
59 +home = args.home.absolute().parent.resolve() / args.home.name
60 +live = (pathlib.Path.home() / '.t3').resolve()
61 +if not args.home.name or home == live or live in home.parents:
62 + raise SystemExit(f'Refusing fixture home {home}: pick a new directory outside {live}')
63 +home.parent.mkdir(parents=True, exist_ok=True)
64 +try:
65 + home.mkdir() # Atomic: fails on any existing file, directory, or symlink.
66 +except FileExistsError:
67 + raise SystemExit(f'Refusing existing fixture home {home}: pick a new directory')
68 +
69 +try:
70 + userdata = home / 'userdata'
71 + userdata.mkdir()
72 + path = userdata / 'statev2.sqlite'
73 + shutil.copyfile(source, path)
74 + wal = source.with_name(source.name + '-wal')
75 + if wal.is_file() and not wal.is_symlink():
76 + shutil.copyfile(wal, path.with_name(path.name + '-wal'))
77 + fixture = json.loads((root / 'scripts/fixtures/issue-21397.json').read_text())
78 + # closing() outlives the transaction so cleanup below never deletes an open database.
79 + with contextlib.closing(sqlite3.connect(path)) as db, db:
80 + # Drop copied conversations, including V1 tables the server could re-import.
81 + tables = [r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type='table'")]
82 + for table in tables:
83 + if table.startswith('orchestration_v2_projection_') and table != 'orchestration_v2_projection_metadata':
84 + db.execute(f'DELETE FROM "{table}"')
85 + elif table.startswith('projection_thread') or table == 'projection_projects':
86 + db.execute(f'DELETE FROM "{table}"')
87 + db.execute("UPDATE orchestration_v2_effect_outbox SET status='cancelled' WHERE status IN ('pending','running')")
88 + for table, rows in fixture.items():
89 + for row in rows:
90 + row = shift(dict(row), delta)
91 + if table == 'projection_projects':
92 + row['workspace_root'] = str(root)
93 + if table == 'orchestration_v2_projection_threads':
94 + payload = json.loads(row['payload_json'])
95 + if mode == 'absent':
96 + payload['snoozedUntil'] = None
97 + elif mode == 'unrelated':
98 + payload['snoozedUntil'] = '2026-10-24T08:50:00.000Z'
99 + row['payload_json'] = json.dumps(shift(payload, delta))
100 + elif delta and 'payload_json' in row:
101 + row['payload_json'] = json.dumps(shift(json.loads(row['payload_json']), delta))
102 + columns = ','.join(f'"{k}"' for k in row)
103 + placeholders = ','.join('?' for _ in row)
104 + db.execute(f'INSERT INTO "{table}" ({columns}) VALUES ({placeholders})', list(row.values()))
105 + settings = dict(snoozeLimitedThreads=False, autoResumeLimitedThreads=False)
106 + (userdata / 'settings.json').write_text(json.dumps(settings, indent=2) + '\n')
107 +except BaseException:
108 + shutil.rmtree(home) # Created above by this run, so it holds nothing else.
109 + raise
110 +hit = (now or EVIDENCE_CLOCK).astimezone(datetime.timezone.utc)
111 +print(f'Seeded synthetic {mode} fixture in {path} (limit hit at {hit:%Y-%m-%dT%H:%M:%SZ})')
112 +print(f'Run: vp run dev --home-dir {shlex.quote(str(home))}')
scripts/seed-issue-21397.test.py new
+181
@@ -0,0 +1,181 @@
1 +#!/usr/bin/env python3
2 +"""python3 scripts/seed-issue-21397.test.py — runs the seeder against synthetic SQLite files only."""
3 +import datetime
4 +import hashlib
5 +import json
6 +import os
7 +import pathlib
8 +import sqlite3
9 +import subprocess
10 +import sys
11 +import tempfile
12 +import unittest
13 +
14 +SCRIPT = pathlib.Path(__file__).resolve().with_name('seed-issue-21397.py')
15 +FIXTURE = json.loads(SCRIPT.with_name('fixtures').joinpath('issue-21397.json').read_text())
16 +# Windows cannot delete a file SQLite still holds open, so cleanup must close connections first.
17 +OPEN_DB_PROBE = '''
18 +import runpy, shutil, sqlite3, sys
19 +opened, connect, rmtree = [], sqlite3.connect, shutil.rmtree
20 +def tracked(*args, **kwargs):
21 + opened.append(connect(*args, **kwargs))
22 + return opened[-1]
23 +def checked(*args, **kwargs):
24 + for db in opened:
25 + try:
26 + db.total_changes
27 + except sqlite3.ProgrammingError:
28 + continue
29 + sys.exit('rmtree ran while a SQLite connection was open')
30 + return rmtree(*args, **kwargs)
31 +sqlite3.connect, shutil.rmtree = tracked, checked
32 +sys.argv = sys.argv[1:]
33 +runpy.run_path(sys.argv[0], run_name='__main__')
34 +'''
35 +
36 +
37 +def snapshot(directory):
38 + return {
39 + str(p.relative_to(directory)): hashlib.sha256(p.read_bytes()).hexdigest() if p.is_file() else 'dir'
40 + for p in sorted(directory.rglob('*'))
41 + }
42 +
43 +
44 +class SeederTest(unittest.TestCase):
45 + def setUp(self):
46 + temp = tempfile.TemporaryDirectory()
47 + self.addCleanup(temp.cleanup)
48 + self.tmp = pathlib.Path(temp.name)
49 + self.fake_home = self.tmp / 'user'
50 + (self.fake_home / '.t3/userdata').mkdir(parents=True)
51 + self.source_home = self.tmp / 'worktree/.t3/userdata'
52 + self.source_home.mkdir(parents=True)
53 + self.source = self.source_home / 'statev2.sqlite'
54 + db = sqlite3.connect(self.source)
55 + db.execute('PRAGMA journal_mode=WAL')
56 + for table, rows in FIXTURE.items():
57 + db.execute(f'CREATE TABLE "{table}" ({",".join(sorted({k for r in rows for k in r}))})')
58 + db.execute(f'INSERT INTO "{table}" (thread_id) VALUES (?)' if table != 'projection_projects'
59 + else f'INSERT INTO "{table}" (project_id) VALUES (?)', ['sentinel'])
60 + db.execute('CREATE TABLE orchestration_v2_projection_metadata (key)')
61 + db.execute("INSERT INTO orchestration_v2_projection_metadata VALUES ('kept')")
62 + db.execute('CREATE TABLE projection_thread_messages (id)')
63 + db.execute("INSERT INTO projection_thread_messages VALUES ('sentinel')")
64 + db.execute('CREATE TABLE orchestration_v2_effect_outbox (status)')
65 + db.executemany('INSERT INTO orchestration_v2_effect_outbox VALUES (?)', [('pending',), ('done',)])
66 + db.commit()
67 + db.close()
68 + (self.source_home / 'settings.json').write_text('{"sentinel": true}\n')
69 + self.before = snapshot(self.source_home)
70 +
71 + def run_seeder(self, *args, probe=()):
72 + env = {**os.environ, 'HOME': str(self.fake_home)}
73 + return subprocess.run([sys.executable, '-I', *probe, str(SCRIPT), '--source', str(self.source), *args],
74 + env=env, capture_output=True, text=True)
75 +
76 + def assertSourceUnchanged(self):
77 + self.assertEqual(snapshot(self.source_home), self.before)
78 +
79 + def thread_payload(self, home):
80 + with sqlite3.connect(home / 'userdata/statev2.sqlite') as db:
81 + self.assertEqual(db.execute('SELECT count(*) FROM projection_thread_messages').fetchone(), (0,))
82 + self.assertEqual(db.execute('SELECT key FROM orchestration_v2_projection_metadata').fetchall(), [('kept',)])
83 + self.assertEqual(db.execute('SELECT status FROM orchestration_v2_effect_outbox ORDER BY 1').fetchall(),
84 + [('cancelled',), ('done',)])
85 + rows = db.execute('SELECT thread_id, payload_json FROM orchestration_v2_projection_threads').fetchall()
86 + self.assertEqual(len(rows), 1)
87 + self.assertNotEqual(rows[0][0], 'sentinel')
88 + return json.loads(rows[0][1])
89 +
90 + def test_seeds_a_fresh_copy_for_every_mode_and_clock(self):
91 + snooze = json.loads(FIXTURE['orchestration_v2_projection_threads'][0]['payload_json'])['snoozedUntil']
92 + clocks = [([], datetime.timedelta(), '2026-10-22T19:00:00Z'),
93 + (['--now', '2026-11-01T12:30:00+02:00'], datetime.timedelta(days=9, hours=15, minutes=30),
94 + '2026-11-01T10:30:00Z'),
95 + (['--now'], None, None)]
96 + for mode in ('matching', 'absent', 'unrelated'):
97 + for clock_args, delta, logged in clocks:
98 + with self.subTest(mode=mode, clock=clock_args):
99 + home = self.tmp / 'fixtures' / f'{mode}-{len(clock_args)}'
100 + started = datetime.datetime.now(datetime.timezone.utc)
101 + result = self.run_seeder('--home', str(home), mode, *clock_args)
102 + self.assertEqual(result.returncode, 0, result.stderr)
103 + self.assertSourceUnchanged()
104 + if delta is None:
105 + delta = started.replace(microsecond=0) - datetime.datetime(
106 + 2026, 10, 22, 19, tzinfo=datetime.timezone.utc)
107 + logged = None
108 + if logged:
109 + self.assertIn(f'(limit hit at {logged})', result.stdout)
110 + self.assertIn(f'Run: vp run dev --home-dir {home}', result.stdout)
111 + expected = {'matching': snooze, 'absent': None, 'unrelated': '2026-10-24T08:50:00.000Z'}[mode]
112 + actual = self.thread_payload(home)['snoozedUntil']
113 + if expected is None:
114 + self.assertIsNone(actual)
115 + else:
116 + moved = datetime.datetime.fromisoformat(actual.replace('Z', '+00:00')) - delta
117 + original = datetime.datetime.fromisoformat(expected.replace('Z', '+00:00'))
118 + self.assertLess(abs(moved - original), datetime.timedelta(seconds=2))
119 + self.assertEqual(json.loads((home / 'userdata/settings.json').read_text()),
120 + {'snoozeLimitedThreads': False, 'autoResumeLimitedThreads': False})
121 +
122 + def test_refuses_unsafe_destinations_without_touching_anything(self):
123 + existing_dir = self.tmp / 'existing'
124 + existing_dir.mkdir()
125 + (existing_dir / 'keep').write_text('keep')
126 + existing_file = self.tmp / 'file'
127 + existing_file.write_text('keep')
128 + link_to_dir = self.tmp / 'link-dir'
129 + link_to_dir.symlink_to(existing_dir)
130 + dangling = self.tmp / 'dangling'
131 + dangling.symlink_to(self.tmp / 'missing')
132 + live_link = self.tmp / 'live-link'
133 + live_link.symlink_to(self.fake_home / '.t3')
134 + cases = {
135 + 'existing directory': existing_dir,
136 + 'existing file': existing_file,
137 + 'symlink to directory': link_to_dir,
138 + 'dangling symlink': dangling,
139 + 'source home': self.source_home.parent,
140 + 'live home': self.fake_home / '.t3',
141 + 'inside live home': self.fake_home / '.t3/fixture',
142 + 'through symlink into live home': live_link / 'fixture',
143 + }
144 + for name, home in cases.items():
145 + with self.subTest(name):
146 + listing = sorted(str(p) for p in self.tmp.rglob('*'))
147 + result = self.run_seeder('--home', str(home))
148 + self.assertNotEqual(result.returncode, 0)
149 + self.assertIn('Refusing', result.stderr)
150 + self.assertSourceUnchanged()
151 + self.assertEqual(sorted(str(p) for p in self.tmp.rglob('*')), listing)
152 + self.assertEqual((existing_dir / 'keep').read_text(), 'keep')
153 + self.assertFalse((self.tmp / 'missing').exists())
154 +
155 + def test_refuses_missing_or_symlinked_source(self):
156 + link = self.tmp / 'linked.sqlite'
157 + link.symlink_to(self.source)
158 + for source in (self.tmp / 'absent.sqlite', link):
159 + with self.subTest(str(source)):
160 + env = {**os.environ, 'HOME': str(self.fake_home)}
161 + result = subprocess.run([sys.executable, '-I', str(SCRIPT), '--source', str(source),
162 + '--home', str(self.tmp / 'new')], env=env, capture_output=True, text=True)
163 + self.assertNotEqual(result.returncode, 0)
164 + self.assertFalse((self.tmp / 'new').exists())
165 + self.assertSourceUnchanged()
166 +
167 + def test_failed_seed_removes_only_its_new_home(self):
168 + with sqlite3.connect(self.source) as db:
169 + db.execute('DROP TABLE orchestration_v2_effect_outbox')
170 + db.close()
171 + self.before = snapshot(self.source_home)
172 + home = self.tmp / 'broken'
173 + result = self.run_seeder('--home', str(home), probe=('-c', OPEN_DB_PROBE))
174 + self.assertNotEqual(result.returncode, 0)
175 + self.assertIn('orchestration_v2_effect_outbox', result.stderr)
176 + self.assertFalse(home.exists(), result.stderr)
177 + self.assertSourceUnchanged()
178 +
179 +
180 +if __name__ == '__main__':
181 + unittest.main()