relay-codex 0.5.1 → 0.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/commands.md +6 -0
- package/docs/publishing.md +2 -2
- package/package.json +1 -1
- package/python/Menu.swift +117 -17
- package/python/commands.py +10 -5
- package/python/router.py +10 -1
- package/python/service.py +75 -2
- package/tests/test_audit.py +86 -0
- package/tests/test_features.py +25 -0
package/docs/commands.md
CHANGED
|
@@ -97,6 +97,8 @@ The watch view waits for local file changes and redraws only when useful status
|
|
|
97
97
|
changes. Heartbeats do not repeatedly print the table. Watching uses no model
|
|
98
98
|
allowance and does not fetch account allowance. `refresh` explicitly checks it.
|
|
99
99
|
The menu uses one local status stream, a template icon, and native session actions.
|
|
100
|
+
Opening it reads a fresh local snapshot, and visible rows update in place.
|
|
101
|
+
Short-window and weekly allowance are labeled separately.
|
|
100
102
|
It opens at Mac login after `relay menubar`; disable that in its menu or with
|
|
101
103
|
`relay menubar --no-startup --configure-only`.
|
|
102
104
|
|
|
@@ -122,6 +124,10 @@ A workspace saves the same supervised session IDs, rather than starting fresh
|
|
|
122
124
|
conversations. Restore restarts stopped jobs and prints reconnect commands; live
|
|
123
125
|
jobs are retained. Save specific sessions by appending their IDs to `workspace save`.
|
|
124
126
|
|
|
127
|
+
Foreground jobs close after their launcher disappears and current activity is
|
|
128
|
+
idle. Explicit background tasks and takeovers remain running. An interrupted action
|
|
129
|
+
is retained for review rather than being silently retried.
|
|
130
|
+
|
|
125
131
|
The normal command remains available after reboot. Background task recovery at
|
|
126
132
|
login is a separate opt-in setting; enabling the menu does not enable task startup.
|
|
127
133
|
Uncertain work still pauses for review after recovery.
|
package/docs/publishing.md
CHANGED
|
@@ -8,8 +8,8 @@ Friends can run `npx relay-codex` or install it with `npm install -g relay-codex
|
|
|
8
8
|
The GitHub repository is enough for friends to install or try Relay:
|
|
9
9
|
|
|
10
10
|
```sh
|
|
11
|
-
npm install -g github:blackspider-ops/relay#v0.5.
|
|
12
|
-
npx --yes github:blackspider-ops/relay#v0.5.
|
|
11
|
+
npm install -g github:blackspider-ops/relay#v0.5.3
|
|
12
|
+
npx --yes github:blackspider-ops/relay#v0.5.3 --version
|
|
13
13
|
```
|
|
14
14
|
|
|
15
15
|
`npx` runs packages; it is not a separate publishing service. Publishing
|
package/package.json
CHANGED
package/python/Menu.swift
CHANGED
|
@@ -8,6 +8,7 @@ final class MenuController: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
|
|
8
8
|
var message: String?
|
|
9
9
|
var reconnect: DispatchWorkItem?
|
|
10
10
|
var stopping = false
|
|
11
|
+
var snapshotInFlight = false
|
|
11
12
|
let command = Bundle.main.object(forInfoDictionaryKey: "RelayCommand") as? String ?? "/usr/bin/false"
|
|
12
13
|
let state = Bundle.main.object(forInfoDictionaryKey: "RelayState") as? String ?? ""
|
|
13
14
|
|
|
@@ -61,10 +62,56 @@ final class MenuController: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
|
|
61
62
|
while let newline = buffer.firstIndex(of: 10) {
|
|
62
63
|
let line = buffer.prefix(upTo: newline); buffer.removeSubrange(...newline)
|
|
63
64
|
if let value = (try? JSONSerialization.jsonObject(with: line)) as? [String: Any] {
|
|
64
|
-
current = value; message = nil; render()
|
|
65
|
+
if (value["at"] as? Double ?? 0) >= (current["at"] as? Double ?? 0) { current = value; message = nil; render() }
|
|
65
66
|
}
|
|
66
67
|
}
|
|
67
68
|
}
|
|
69
|
+
func refreshSnapshot() {
|
|
70
|
+
guard !snapshotInFlight, !stopping else { return }
|
|
71
|
+
snapshotInFlight = true
|
|
72
|
+
let proc = process(["status", "--json"])
|
|
73
|
+
let pipe = Pipe(); proc.standardOutput = pipe; proc.standardError = FileHandle.nullDevice
|
|
74
|
+
DispatchQueue.global(qos: .utility).async { [weak self] in
|
|
75
|
+
var snapshot: [String: Any]?
|
|
76
|
+
do {
|
|
77
|
+
try proc.run()
|
|
78
|
+
let timeout = DispatchWorkItem { if proc.isRunning { proc.terminate() } }
|
|
79
|
+
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 8, execute: timeout)
|
|
80
|
+
let bytes = pipe.fileHandleForReading.readDataToEndOfFile(); proc.waitUntilExit(); timeout.cancel()
|
|
81
|
+
if proc.terminationStatus == 0 { snapshot = (try? JSONSerialization.jsonObject(with: bytes)) as? [String: Any] }
|
|
82
|
+
} catch { }
|
|
83
|
+
let result = snapshot
|
|
84
|
+
DispatchQueue.main.async {
|
|
85
|
+
guard let self = self else { return }
|
|
86
|
+
self.snapshotInFlight = false
|
|
87
|
+
if let value = result {
|
|
88
|
+
let at = value["at"] as? Double ?? 0
|
|
89
|
+
if at >= (self.current["at"] as? Double ?? 0) { self.current = value; self.render() }
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
static func synchronise(_ live: NSMenu, with desired: NSMenu) {
|
|
95
|
+
let incoming = desired.items
|
|
96
|
+
while live.items.count > incoming.count { live.removeItem(at: live.items.count - 1) }
|
|
97
|
+
for (index, fresh) in incoming.enumerated() {
|
|
98
|
+
if index >= live.items.count {
|
|
99
|
+
desired.removeItem(fresh); live.addItem(fresh); continue
|
|
100
|
+
}
|
|
101
|
+
let existing = live.items[index]
|
|
102
|
+
if existing.isSeparatorItem != fresh.isSeparatorItem || existing.identifier != fresh.identifier {
|
|
103
|
+
live.removeItem(at: index); desired.removeItem(fresh); live.insertItem(fresh, at: index); continue
|
|
104
|
+
}
|
|
105
|
+
existing.title = fresh.title; existing.state = fresh.state
|
|
106
|
+
existing.target = fresh.target; existing.action = fresh.action
|
|
107
|
+
existing.keyEquivalent = fresh.keyEquivalent; existing.isEnabled = fresh.isEnabled
|
|
108
|
+
existing.representedObject = fresh.representedObject; existing.toolTip = fresh.toolTip
|
|
109
|
+
if let child = fresh.submenu {
|
|
110
|
+
if let previous = existing.submenu { synchronise(previous, with: child) }
|
|
111
|
+
else { fresh.submenu = nil; existing.submenu = child }
|
|
112
|
+
} else { existing.submenu = nil }
|
|
113
|
+
}
|
|
114
|
+
}
|
|
68
115
|
func updateIcon(attention: Bool) {
|
|
69
116
|
let symbol = attention ? "exclamationmark.circle.fill" : "arrow.triangle.branch"
|
|
70
117
|
let image = NSImage(systemSymbolName: symbol, accessibilityDescription: attention ? "Relay needs attention" : "Relay")
|
|
@@ -72,14 +119,36 @@ final class MenuController: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
|
|
72
119
|
item.button?.image = image
|
|
73
120
|
}
|
|
74
121
|
func text(_ title: String, into menu: NSMenu) {
|
|
75
|
-
|
|
122
|
+
let entry = NSMenuItem(title: title, action: nil, keyEquivalent: "")
|
|
123
|
+
entry.isEnabled = false; menu.addItem(entry)
|
|
76
124
|
}
|
|
77
125
|
func action(_ title: String, args: [String], into menu: NSMenu) {
|
|
78
126
|
let entry = NSMenuItem(title: title, action: #selector(runAction(_:)), keyEquivalent: "")
|
|
79
|
-
entry.target = self; entry.representedObject = args
|
|
127
|
+
entry.target = self; entry.representedObject = args
|
|
128
|
+
entry.identifier = NSUserInterfaceItemIdentifier("action:" + args.joined(separator: "|")); menu.addItem(entry)
|
|
129
|
+
}
|
|
130
|
+
struct TimingRow {
|
|
131
|
+
let title: String
|
|
132
|
+
let at: Double?
|
|
133
|
+
}
|
|
134
|
+
static func timestamp(_ value: Any?) -> Double? {
|
|
135
|
+
guard let seconds = value as? Double, seconds.isFinite, seconds > 0 else { return nil }
|
|
136
|
+
return seconds
|
|
137
|
+
}
|
|
138
|
+
static func accountTimingRows(_ account: [String: Any]) -> [TimingRow] {
|
|
139
|
+
var rows: [TimingRow] = []
|
|
140
|
+
if let primary = account["primary"] as? [String: Any], let at = timestamp(primary["resetsAt"]) {
|
|
141
|
+
rows.append(TimingRow(title: "Short reset", at: at))
|
|
142
|
+
}
|
|
143
|
+
if let secondary = account["secondary"] as? [String: Any], let at = timestamp(secondary["resetsAt"]) {
|
|
144
|
+
rows.append(TimingRow(title: "Weekly reset", at: at))
|
|
145
|
+
}
|
|
146
|
+
if let at = timestamp(account["next_check"]) { rows.append(TimingRow(title: "Next allowance check", at: at)) }
|
|
147
|
+
else { rows.append(TimingRow(title: "Allowance checked when needed", at: nil)) }
|
|
148
|
+
return rows
|
|
80
149
|
}
|
|
81
150
|
func date(_ value: Any?) -> String {
|
|
82
|
-
guard let seconds = value
|
|
151
|
+
guard let seconds = MenuController.timestamp(value) else { return "Not available" }
|
|
83
152
|
return Date(timeIntervalSince1970: seconds).formatted(date: .abbreviated, time: .shortened)
|
|
84
153
|
}
|
|
85
154
|
func countdown(_ title: String, value: Any, into menu: NSMenu) {
|
|
@@ -91,8 +160,9 @@ final class MenuController: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
|
|
91
160
|
for entry in menu.items {
|
|
92
161
|
if let data = entry.representedObject as? [String: Any], let at = data["at"] as? Double, let label = data["label"] as? String {
|
|
93
162
|
let seconds = max(0, Int(at - Date().timeIntervalSince1970))
|
|
94
|
-
let remaining = seconds < 60 ? "under a minute" : seconds < 3600 ? "\(seconds / 60)m" : "\(seconds / 3600)h \((seconds % 3600) / 60)m"
|
|
95
|
-
|
|
163
|
+
let remaining = seconds < 60 ? "under a minute" : seconds < 3600 ? "\(seconds / 60)m" : seconds < 86400 ? "\(seconds / 3600)h \((seconds % 3600) / 60)m" : "\(seconds / 86400)d \((seconds % 86400) / 3600)h"
|
|
164
|
+
let elapsed = label.contains("reset") ? "reported time passed" : "due now"
|
|
165
|
+
entry.title = label + ": " + (seconds == 0 ? elapsed : "in " + remaining) + " · " + date(at)
|
|
96
166
|
}
|
|
97
167
|
if let child = entry.submenu { updateTimes(child) }
|
|
98
168
|
}
|
|
@@ -110,17 +180,26 @@ final class MenuController: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
|
|
110
180
|
for account in accounts {
|
|
111
181
|
let name = account["name"] as? String ?? "Account"
|
|
112
182
|
let primary = account["primary"] as? [String: Any]
|
|
113
|
-
let
|
|
114
|
-
let
|
|
183
|
+
let short = account["short_remaining"] as? String ?? (primary?["usedPercent"] as? NSNumber).map { "\(max(0, 100 - $0.intValue))%" } ?? "?"
|
|
184
|
+
let remaining = short == "?" ? "allowance unknown" : short + " left"
|
|
185
|
+
let secondary = account["secondary"] as? [String: Any]
|
|
186
|
+
let weekly = account["weekly_remaining"] as? String ?? (secondary?["usedPercent"] as? NSNumber).map { "\(max(0, 100 - $0.intValue))%" } ?? "?"
|
|
187
|
+
let label = (account["enabled"] as? Bool ?? true) ? "Short \(short) · Week \(weekly)" : "disabled"
|
|
115
188
|
let submenu = NSMenu()
|
|
116
189
|
if let email = account["email"] as? String { text(email, into: submenu) }
|
|
117
190
|
text("Short window: \(remaining)", into: submenu)
|
|
118
|
-
if
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
191
|
+
if weekly != "?" { text("Weekly window: \(weekly) left", into: submenu) }
|
|
192
|
+
for row in MenuController.accountTimingRows(account) {
|
|
193
|
+
if let at = row.at { countdown(row.title, value: at, into: submenu) }
|
|
194
|
+
else { text(row.title, into: submenu) }
|
|
195
|
+
}
|
|
196
|
+
let lastChecked = MenuController.timestamp(account["usage_checked_at"]).map { date($0) } ?? "Not checked yet"
|
|
197
|
+
text("Last checked: \(lastChecked)", into: submenu)
|
|
198
|
+
let entry = NSMenuItem(title: "\(name) · \(label)", action: nil, keyEquivalent: "")
|
|
199
|
+
entry.identifier = NSUserInterfaceItemIdentifier("account:" + (account["id"] as? String ?? name))
|
|
200
|
+
entry.submenu = submenu; menu.addItem(entry)
|
|
122
201
|
}
|
|
123
|
-
menu.addItem(.separator())
|
|
202
|
+
if !sessions.isEmpty { menu.addItem(.separator()) }
|
|
124
203
|
for session in sessions {
|
|
125
204
|
let id = session["id"] as? String ?? ""
|
|
126
205
|
let name = session["name"] as? String ?? String(id.prefix(10))
|
|
@@ -128,13 +207,15 @@ final class MenuController: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
|
|
128
207
|
let submenu = NSMenu()
|
|
129
208
|
text("Account: \(session["account_name"] as? String ?? session["account"] as? String ?? "unknown")", into: submenu)
|
|
130
209
|
text("Model: \(session["model"] as? String ?? "unknown")", into: submenu)
|
|
131
|
-
if let next = session["next_wake"] { countdown("Next action", value: next, into: submenu) }
|
|
210
|
+
if let next = MenuController.timestamp(session["next_wake"]) { countdown("Next action", value: next, into: submenu) }
|
|
132
211
|
if let reason = session["reason"] as? String { text(reason.replacingOccurrences(of: "_", with: " "), into: submenu) }
|
|
133
212
|
action("Copy reconnect command", args: ["copy", "relay attach " + id], into: submenu)
|
|
134
213
|
action("Pause recovery", args: ["pause", id, "--wait"], into: submenu)
|
|
135
214
|
action("Resume recovery", args: ["unpause", id, "--wait"], into: submenu)
|
|
136
215
|
action("Review and retry…", args: ["confirm-retry", id], into: submenu)
|
|
137
|
-
let entry = NSMenuItem(title: "\(name) · \(status)", action: nil, keyEquivalent: "")
|
|
216
|
+
let entry = NSMenuItem(title: "\(name) · \(status)", action: nil, keyEquivalent: "")
|
|
217
|
+
entry.identifier = NSUserInterfaceItemIdentifier("session:" + id)
|
|
218
|
+
entry.submenu = submenu; menu.addItem(entry)
|
|
138
219
|
}
|
|
139
220
|
menu.addItem(.separator())
|
|
140
221
|
action("Copy dashboard command", args: ["copy", "relay status --watch"], into: menu)
|
|
@@ -143,9 +224,12 @@ final class MenuController: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
|
|
143
224
|
login.state = FileManager.default.fileExists(atPath: NSHomeDirectory() + "/Library/LaunchAgents/local.relay.menu.plist") ? .on : .off
|
|
144
225
|
menu.addItem(login)
|
|
145
226
|
let quit = NSMenuItem(title: "Quit Relay menu", action: #selector(quitMenu), keyEquivalent: "q"); quit.target = self; menu.addItem(quit)
|
|
146
|
-
|
|
227
|
+
updateTimes(menu)
|
|
228
|
+
if let visible = item.menu { MenuController.synchronise(visible, with: menu) }
|
|
229
|
+
else { item.menu = menu }
|
|
147
230
|
}
|
|
148
231
|
func menuWillOpen(_ menu: NSMenu) {
|
|
232
|
+
refreshSnapshot()
|
|
149
233
|
updateTimes(menu)
|
|
150
234
|
for entry in menu.items where entry.title == "Open at login" {
|
|
151
235
|
entry.state = FileManager.default.fileExists(atPath: NSHomeDirectory() + "/Library/LaunchAgents/local.relay.menu.plist") ? .on : .off
|
|
@@ -181,7 +265,23 @@ if CommandLine.arguments.contains("--self-check") {
|
|
|
181
265
|
let normal = NSImage(systemSymbolName: "arrow.triangle.branch", accessibilityDescription: "Relay")
|
|
182
266
|
let attention = NSImage(systemSymbolName: "exclamationmark.circle.fill", accessibilityDescription: "Relay needs attention")
|
|
183
267
|
print("Relay menu symbols available: \(normal != nil && attention != nil)")
|
|
184
|
-
|
|
268
|
+
let visible = NSMenu(); visible.addItem(NSMenuItem(title: "Short 83%", action: nil, keyEquivalent: ""))
|
|
269
|
+
let existing = visible.items[0]
|
|
270
|
+
let updated = NSMenu(); updated.addItem(NSMenuItem(title: "Short 30%", action: nil, keyEquivalent: ""))
|
|
271
|
+
MenuController.synchronise(visible, with: updated)
|
|
272
|
+
let liveUpdate = visible.items[0] === existing && existing.title == "Short 30%"
|
|
273
|
+
print("Visible menu update preserved: \(liveUpdate)")
|
|
274
|
+
existing.identifier = NSUserInterfaceItemIdentifier("session:old")
|
|
275
|
+
let replacement = NSMenu(); let newItem = NSMenuItem(title: "New task", action: nil, keyEquivalent: "")
|
|
276
|
+
newItem.identifier = NSUserInterfaceItemIdentifier("session:new"); replacement.addItem(newItem)
|
|
277
|
+
MenuController.synchronise(visible, with: replacement)
|
|
278
|
+
let safeIdentity = visible.items[0] !== existing && visible.items[0].identifier == newItem.identifier
|
|
279
|
+
print("Session action identity preserved: \(safeIdentity)")
|
|
280
|
+
let timing = MenuController.accountTimingRows(["next_check": NSNull(), "primary": ["resetsAt": 2000000000.0], "secondary": ["resetsAt": 2000100000.0]])
|
|
281
|
+
let scheduled = MenuController.accountTimingRows(["next_check": 2000200000.0])
|
|
282
|
+
let correctTiming = timing.map { $0.title } == ["Short reset", "Weekly reset", "Allowance checked when needed"] && scheduled.first?.title == "Next allowance check" && scheduled.first?.at == 2000200000.0
|
|
283
|
+
print("Empty retry schedule handled: \(correctTiming)")
|
|
284
|
+
exit(normal != nil && attention != nil && liveUpdate && safeIdentity && correctTiming ? 0 : 1)
|
|
185
285
|
} else {
|
|
186
286
|
let app = NSApplication.shared
|
|
187
287
|
let delegate = MenuController(); app.delegate = delegate; app.run()
|
package/python/commands.py
CHANGED
|
@@ -68,6 +68,13 @@ def resolve_label(state, value):
|
|
|
68
68
|
raise RouterError("Unknown or ambiguous account name")
|
|
69
69
|
|
|
70
70
|
|
|
71
|
+
def remaining_percent(window):
|
|
72
|
+
if not window or not isinstance(window.get("usedPercent"), (int, float)):
|
|
73
|
+
return "?"
|
|
74
|
+
value = max(0, min(100, 100 - window["usedPercent"]))
|
|
75
|
+
return f"{value:.1f}".rstrip("0").rstrip(".") + "%"
|
|
76
|
+
|
|
77
|
+
|
|
71
78
|
def snapshot(state, include_inactive=False):
|
|
72
79
|
from router import labels, VERSION
|
|
73
80
|
|
|
@@ -99,6 +106,8 @@ def snapshot(state, include_inactive=False):
|
|
|
99
106
|
"sessions": sum(s["account"] == label for s in sessions),
|
|
100
107
|
"primary": windows.get("primary"),
|
|
101
108
|
"secondary": windows.get("secondary"),
|
|
109
|
+
"short_remaining": remaining_percent(windows.get("primary")),
|
|
110
|
+
"weekly_remaining": remaining_percent(windows.get("secondary")),
|
|
102
111
|
"usage_known": usage is not None,
|
|
103
112
|
"usage_checked_at": pool.checked_at(label),
|
|
104
113
|
"maintenance": options.get("maintenance", False),
|
|
@@ -172,10 +181,6 @@ def snapshot(state, include_inactive=False):
|
|
|
172
181
|
|
|
173
182
|
|
|
174
183
|
def render(value):
|
|
175
|
-
def percent(window):
|
|
176
|
-
return (
|
|
177
|
-
"?" if not window else str(max(0, 100 - window.get("usedPercent", 0))) + "%"
|
|
178
|
-
)
|
|
179
184
|
|
|
180
185
|
lines = [
|
|
181
186
|
f"Relay · {len(value['sessions'])} sessions · {len(value['accounts'])} accounts",
|
|
@@ -200,7 +205,7 @@ def render(value):
|
|
|
200
205
|
else "—"
|
|
201
206
|
)
|
|
202
207
|
lines.append(
|
|
203
|
-
f"{label:<39}{state:<13}{
|
|
208
|
+
f"{label:<39}{state:<13}{account.get('short_remaining', remaining_percent(account['primary'])):<13}{account.get('weekly_remaining', remaining_percent(account['secondary'])):<13}{account['sessions']:<10}{next_at}"
|
|
204
209
|
)
|
|
205
210
|
if value["sessions"]:
|
|
206
211
|
lines += [
|
package/python/router.py
CHANGED
|
@@ -24,7 +24,7 @@ from pool import Pool, blocked, reset_time, failure_kind, file_lock
|
|
|
24
24
|
from launch import translate, RESUME_FIELDS
|
|
25
25
|
import settings
|
|
26
26
|
|
|
27
|
-
VERSION = "0.5.
|
|
27
|
+
VERSION = "0.5.3"
|
|
28
28
|
_support = Path.home() / "Library/Application Support"
|
|
29
29
|
_legacy = _support / "Codex Accounts"
|
|
30
30
|
_default_state = _legacy if (_legacy / "accounts").exists() else _support / "Relay"
|
|
@@ -427,6 +427,8 @@ class Controller:
|
|
|
427
427
|
self.stopping = asyncio.Event()
|
|
428
428
|
self.extra_accounts = None
|
|
429
429
|
self.starting = False
|
|
430
|
+
self.lifecycle_check = None
|
|
431
|
+
self.exit_state = "stopped"
|
|
430
432
|
self.on_thread = None
|
|
431
433
|
self.on_detach = None
|
|
432
434
|
self.project = os.getcwd()
|
|
@@ -525,6 +527,8 @@ class Controller:
|
|
|
525
527
|
|
|
526
528
|
def clear_review(self, thread):
|
|
527
529
|
self.paused_uncertain.discard(thread)
|
|
530
|
+
if not self.paused_uncertain:
|
|
531
|
+
self.exit_state = "stopped"
|
|
528
532
|
self.persist(thread, review_required=False, review_reason=None)
|
|
529
533
|
|
|
530
534
|
def can_continue(self, thread, generation):
|
|
@@ -681,6 +685,10 @@ class Controller:
|
|
|
681
685
|
except Exception:
|
|
682
686
|
self.pool.ack(command, "failed")
|
|
683
687
|
self.note("control_failed", operation=op)
|
|
688
|
+
if self.lifecycle_check:
|
|
689
|
+
await self.lifecycle_check()
|
|
690
|
+
if self.stopping.is_set():
|
|
691
|
+
break
|
|
684
692
|
if self.preferences.get("keep_awake") and self.active_threads:
|
|
685
693
|
if (
|
|
686
694
|
self.awake_process is None
|
|
@@ -738,6 +746,7 @@ class Controller:
|
|
|
738
746
|
self.wake.set()
|
|
739
747
|
self.note("resumed")
|
|
740
748
|
elif op == "stop":
|
|
749
|
+
self.exit_state = "stopped"
|
|
741
750
|
self.stopping.set()
|
|
742
751
|
elif op == "detach":
|
|
743
752
|
if self.pool:
|
package/python/service.py
CHANGED
|
@@ -51,6 +51,10 @@ def start(
|
|
|
51
51
|
"interactive": interactive,
|
|
52
52
|
"binary": binary,
|
|
53
53
|
"relay_runtime": str(Path(__file__).parent.resolve()),
|
|
54
|
+
"foreground_owner": {"pid": os.getpid(), "birth": process_birth(os.getpid())}
|
|
55
|
+
if interactive
|
|
56
|
+
else None,
|
|
57
|
+
"background_launch": not interactive,
|
|
54
58
|
}
|
|
55
59
|
if not Path(spec["cwd"]).is_dir():
|
|
56
60
|
raise ValueError("Working directory does not exist")
|
|
@@ -155,6 +159,21 @@ async def attach(
|
|
|
155
159
|
spec_path = root / (ident + ".job.json")
|
|
156
160
|
spec = json.loads(spec_path.read_text())
|
|
157
161
|
binary = spec.get("binary") or binary
|
|
162
|
+
owner = spec.get("foreground_owner")
|
|
163
|
+
if (
|
|
164
|
+
spec.get("interactive")
|
|
165
|
+
and not spec.get("background_launch")
|
|
166
|
+
and owner
|
|
167
|
+
and not (
|
|
168
|
+
Pool.alive(owner["pid"])
|
|
169
|
+
and process_birth(owner["pid"]) == owner.get("birth")
|
|
170
|
+
)
|
|
171
|
+
):
|
|
172
|
+
spec["foreground_owner"] = {
|
|
173
|
+
"pid": os.getpid(),
|
|
174
|
+
"birth": process_birth(os.getpid()),
|
|
175
|
+
}
|
|
176
|
+
atomic_json(spec_path, spec)
|
|
158
177
|
meta = root / (ident + ".connection.json")
|
|
159
178
|
invocation_cwd = cwd
|
|
160
179
|
reconnect = False
|
|
@@ -353,7 +372,7 @@ def restart(state, prefix):
|
|
|
353
372
|
spec = json.loads(path.read_text())
|
|
354
373
|
if not Path(spec["cwd"]).is_dir():
|
|
355
374
|
raise RouterError("The project folder no longer exists")
|
|
356
|
-
spec.update(state="starting")
|
|
375
|
+
spec.update(state="starting", background_launch=True, foreground_owner=None)
|
|
357
376
|
spec.pop("last_error", None)
|
|
358
377
|
atomic_json(path, spec)
|
|
359
378
|
process = spawn(
|
|
@@ -378,6 +397,54 @@ def restart(state, prefix):
|
|
|
378
397
|
return ident
|
|
379
398
|
|
|
380
399
|
|
|
400
|
+
def foreground_owner_gone(spec, preferences, controller, *, now=None):
|
|
401
|
+
"""Foreground jobs must not outlive a vanished launcher unless explicitly detached."""
|
|
402
|
+
if (
|
|
403
|
+
not spec.get("interactive")
|
|
404
|
+
or spec.get("background_launch")
|
|
405
|
+
or spec.get("takeover")
|
|
406
|
+
or preferences.get("background_on_disconnect")
|
|
407
|
+
or controller.client
|
|
408
|
+
):
|
|
409
|
+
return False
|
|
410
|
+
owner = spec.get("foreground_owner")
|
|
411
|
+
if owner:
|
|
412
|
+
return not (
|
|
413
|
+
Pool.alive(owner["pid"])
|
|
414
|
+
and process_birth(owner["pid"]) == owner.get("birth")
|
|
415
|
+
)
|
|
416
|
+
# Earlier jobs did not record a launcher. Only retire a definitely empty,
|
|
417
|
+
# unattached picker; retain older conversations whose ownership is uncertain.
|
|
418
|
+
return (
|
|
419
|
+
not spec.get("resume")
|
|
420
|
+
and not controller.last_turn
|
|
421
|
+
and (time.time() if now is None else now) - spec.get("created", time.time())
|
|
422
|
+
> 60
|
|
423
|
+
)
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
async def close_orphaned_foreground(controller, spec_path):
|
|
427
|
+
spec = json.loads(spec_path.read_text())
|
|
428
|
+
if not foreground_owner_gone(spec, controller.preferences, controller):
|
|
429
|
+
return
|
|
430
|
+
if (
|
|
431
|
+
controller.active_threads
|
|
432
|
+
or controller.active_items
|
|
433
|
+
or controller.server_requests
|
|
434
|
+
):
|
|
435
|
+
for thread in controller.last_turn:
|
|
436
|
+
controller.hold_for_review(thread, "terminal_closed_during_action")
|
|
437
|
+
controller.exit_state = "needs_attention"
|
|
438
|
+
if not getattr(controller, "orphan_reported", False):
|
|
439
|
+
controller.note("needs_attention", reason="terminal_closed_during_action")
|
|
440
|
+
controller.orphan_reported = True
|
|
441
|
+
return
|
|
442
|
+
controller.note("foreground_closed", reason="launcher_exited")
|
|
443
|
+
spec["state"] = controller.exit_state
|
|
444
|
+
atomic_json(spec_path, spec)
|
|
445
|
+
controller.stopping.set()
|
|
446
|
+
|
|
447
|
+
|
|
381
448
|
async def _serve(state, ident, binary):
|
|
382
449
|
from websockets.asyncio.server import serve as ws_serve
|
|
383
450
|
from router import (
|
|
@@ -456,6 +523,9 @@ async def _serve(state, ident, binary):
|
|
|
456
523
|
return new or old
|
|
457
524
|
|
|
458
525
|
controller.extra_accounts = reload_accounts
|
|
526
|
+
controller.lifecycle_check = lambda: close_orphaned_foreground(
|
|
527
|
+
controller, spec_path
|
|
528
|
+
)
|
|
459
529
|
controller.preferences = settings.load(state, cwd, spec.get("profile"))
|
|
460
530
|
controller.retry_interval = controller.preferences["retry_interval"]
|
|
461
531
|
controller.retry_attempts = controller.preferences["retry_attempts"]
|
|
@@ -513,6 +583,9 @@ async def _serve(state, ident, binary):
|
|
|
513
583
|
pool.touch(state="waiting_for_reset", next_wake=deadline)
|
|
514
584
|
await controller.wait_until(deadline, controller.user_generation)
|
|
515
585
|
if controller.stopping.is_set():
|
|
586
|
+
latest = json.loads(spec_path.read_text())
|
|
587
|
+
latest["state"] = controller.exit_state
|
|
588
|
+
atomic_json(spec_path, latest)
|
|
516
589
|
return 0
|
|
517
590
|
controller.backend_factory = factory
|
|
518
591
|
thread_id = old_thread or spec.get("resume")
|
|
@@ -688,7 +761,7 @@ async def _serve(state, ident, binary):
|
|
|
688
761
|
# have been reconciled. A frontend must not race recovery setup.
|
|
689
762
|
atomic_json(connection, meta)
|
|
690
763
|
await controller.stopping.wait()
|
|
691
|
-
spec["state"] =
|
|
764
|
+
spec["state"] = controller.exit_state
|
|
692
765
|
atomic_json(spec_path, spec)
|
|
693
766
|
return 0
|
|
694
767
|
finally:
|
package/tests/test_audit.py
CHANGED
|
@@ -343,3 +343,89 @@ class AttachmentRegressions(unittest.IsolatedAsyncioTestCase):
|
|
|
343
343
|
self.assertFalse(
|
|
344
344
|
parse_arguments(["attach", "task", "--", "--takeover"]).takeover
|
|
345
345
|
)
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
class ForegroundLifecycleTests(unittest.IsolatedAsyncioTestCase):
|
|
349
|
+
async def test_closed_launcher_retires_an_empty_idle_foreground_job(self):
|
|
350
|
+
with tempfile.TemporaryDirectory() as folder:
|
|
351
|
+
path = Path(folder) / "job.json"
|
|
352
|
+
job = {
|
|
353
|
+
"interactive": True,
|
|
354
|
+
"foreground_owner": {"pid": 99999999, "birth": "gone"},
|
|
355
|
+
"state": "starting",
|
|
356
|
+
}
|
|
357
|
+
atomic_json(path, job)
|
|
358
|
+
c = Controller([FakeAccount("one")], FakeBackend(), report=lambda _: None)
|
|
359
|
+
await service.close_orphaned_foreground(c, path)
|
|
360
|
+
self.assertTrue(c.stopping.is_set())
|
|
361
|
+
self.assertEqual(json.loads(path.read_text())["state"], "stopped")
|
|
362
|
+
|
|
363
|
+
async def test_real_launcher_background_preference_and_takeover_are_preserved(self):
|
|
364
|
+
c = Controller([FakeAccount("one")], FakeBackend(), report=lambda _: None)
|
|
365
|
+
job = {
|
|
366
|
+
"interactive": True,
|
|
367
|
+
"foreground_owner": {
|
|
368
|
+
"pid": os.getpid(),
|
|
369
|
+
"birth": process_birth(os.getpid()),
|
|
370
|
+
},
|
|
371
|
+
}
|
|
372
|
+
self.assertFalse(service.foreground_owner_gone(job, c.preferences, c))
|
|
373
|
+
dead = {**job, "foreground_owner": {"pid": 99999999, "birth": "gone"}}
|
|
374
|
+
for field in ("background_launch", "takeover"):
|
|
375
|
+
self.assertFalse(
|
|
376
|
+
service.foreground_owner_gone({**dead, field: True}, c.preferences, c)
|
|
377
|
+
)
|
|
378
|
+
self.assertFalse(
|
|
379
|
+
service.foreground_owner_gone(
|
|
380
|
+
dead, {**c.preferences, "background_on_disconnect": True}, c
|
|
381
|
+
)
|
|
382
|
+
)
|
|
383
|
+
c.client = FakeClient()
|
|
384
|
+
self.assertFalse(service.foreground_owner_gone(dead, c.preferences, c))
|
|
385
|
+
|
|
386
|
+
async def test_orphaned_active_action_requires_review_and_is_not_killed(self):
|
|
387
|
+
with tempfile.TemporaryDirectory() as folder:
|
|
388
|
+
state = Path(folder)
|
|
389
|
+
path = state / "job.json"
|
|
390
|
+
pool = Pool(state)
|
|
391
|
+
atomic_json(
|
|
392
|
+
path,
|
|
393
|
+
{
|
|
394
|
+
"interactive": True,
|
|
395
|
+
"foreground_owner": {"pid": 99999999, "birth": "gone"},
|
|
396
|
+
},
|
|
397
|
+
)
|
|
398
|
+
c = Controller(
|
|
399
|
+
[FakeAccount("one")], FakeBackend(), pool=pool, report=lambda _: None
|
|
400
|
+
)
|
|
401
|
+
c.last_turn["thread"] = {"threadId": "thread"}
|
|
402
|
+
c.active_items.add("command")
|
|
403
|
+
await service.close_orphaned_foreground(c, path)
|
|
404
|
+
self.assertFalse(c.stopping.is_set())
|
|
405
|
+
self.assertTrue(pool.intent("thread")["review_required"])
|
|
406
|
+
c.active_items.clear()
|
|
407
|
+
await service.close_orphaned_foreground(c, path)
|
|
408
|
+
self.assertTrue(c.stopping.is_set())
|
|
409
|
+
self.assertEqual(json.loads(path.read_text())["state"], "needs_attention")
|
|
410
|
+
pool.close()
|
|
411
|
+
|
|
412
|
+
async def test_explicit_review_or_stop_clears_orphan_exit_status(self):
|
|
413
|
+
c = Controller([FakeAccount("one")], FakeBackend(), report=lambda _: None)
|
|
414
|
+
c.hold_for_review("thread")
|
|
415
|
+
c.exit_state = "needs_attention"
|
|
416
|
+
c.clear_review("thread")
|
|
417
|
+
self.assertEqual(c.exit_state, "stopped")
|
|
418
|
+
c.exit_state = "needs_attention"
|
|
419
|
+
await c.control("stop", {})
|
|
420
|
+
self.assertEqual(c.exit_state, "stopped")
|
|
421
|
+
|
|
422
|
+
def test_legacy_empty_picker_expires_but_saved_conversation_is_retained(self):
|
|
423
|
+
c = Controller([FakeAccount("one")], FakeBackend(), report=lambda _: None)
|
|
424
|
+
job = {"interactive": True, "created": 1000}
|
|
425
|
+
self.assertFalse(service.foreground_owner_gone(job, c.preferences, c, now=1005))
|
|
426
|
+
self.assertTrue(service.foreground_owner_gone(job, c.preferences, c, now=1100))
|
|
427
|
+
self.assertFalse(
|
|
428
|
+
service.foreground_owner_gone(
|
|
429
|
+
{**job, "resume": "saved"}, c.preferences, c, now=1100
|
|
430
|
+
)
|
|
431
|
+
)
|
package/tests/test_features.py
CHANGED
|
@@ -85,6 +85,31 @@ class ManagementTests(unittest.TestCase):
|
|
|
85
85
|
with self.assertRaises(ValueError):
|
|
86
86
|
prepare_worktree(["resume", "--worktree"], state, str(repo))
|
|
87
87
|
|
|
88
|
+
def test_both_displays_receive_the_same_fractional_allowance(self):
|
|
89
|
+
with tempfile.TemporaryDirectory() as folder:
|
|
90
|
+
state = Path(folder)
|
|
91
|
+
home = state / "accounts" / "one"
|
|
92
|
+
home.mkdir(parents=True)
|
|
93
|
+
(home / "enrolled").write_text("{}")
|
|
94
|
+
pool = Pool(state)
|
|
95
|
+
pool.save(
|
|
96
|
+
"one",
|
|
97
|
+
{
|
|
98
|
+
"rateLimits": {
|
|
99
|
+
"primary": {"usedPercent": 70.2},
|
|
100
|
+
"secondary": {"usedPercent": 41.5},
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
)
|
|
104
|
+
value = commands.snapshot(state)
|
|
105
|
+
account = value["accounts"][0]
|
|
106
|
+
self.assertEqual(account["short_remaining"], "29.8%")
|
|
107
|
+
self.assertEqual(account["weekly_remaining"], "58.5%")
|
|
108
|
+
text = commands.render(value)
|
|
109
|
+
self.assertIn(account["short_remaining"], text)
|
|
110
|
+
self.assertIn(account["weekly_remaining"], text)
|
|
111
|
+
pool.close()
|
|
112
|
+
|
|
88
113
|
def test_account_emails_are_displayed_and_resolve_without_reading_tokens(self):
|
|
89
114
|
with tempfile.TemporaryDirectory() as folder:
|
|
90
115
|
state = Path(folder)
|