Skip to content

Commit 7c9b4e5

Browse files
ARTclaude
authored andcommitted
fix(agents2): the packaged app never waits on a dev build
A dev build holds an agent's lock in native state and lets go only when its frontend runs, so a dev build stuck at a breakpoint or error overlay could silence the packaged app. Release builds are single-instance, so the packaged app now always runs what it can and only holds `<pubkey>.packaged`; dev builds alone coordinate through `<pubkey>.lock` and step aside while it is held. Each agent is also claimed or released as it comes into or leaves view, not on its next event or tick, which shrinks the handover window to one lock call. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Bradley Axen <[email protected]>
1 parent 4914674 commit 7c9b4e5

4 files changed

Lines changed: 64 additions & 46 deletions

File tree

‎src-tauri/src/app_agents.rs‎

Lines changed: 35 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -127,29 +127,26 @@ impl AppAgentHost {
127127

128128
/// Which running copy of the app runs each agent. Every copy on this machine
129129
/// (the packaged app and any dev builds) shares the agent list and hears the
130-
/// same events, so each agent is run by the one copy holding its lock file. The
131-
/// OS lets go when that copy exits, however it exits.
130+
/// same events. The packaged app always runs what it can and holds
131+
/// `<pubkey>.packaged` while it does; there is only ever one, since release
132+
/// builds are single-instance. Dev builds step aside while that is held, and
133+
/// otherwise run each agent from whichever holds `<pubkey>.lock`. The OS lets go
134+
/// of both when a copy exits, however it exits.
132135
struct Hosting {
133136
dir: Result<PathBuf, String>,
134-
/// A dev build steps aside for a packaged app that can run the same agent.
135137
packaged: bool,
136-
held: Mutex<HashMap<String, Held>>,
137-
}
138-
#[derive(Default)]
139-
struct Held {
140-
/// `<pubkey>.lock`: this copy runs the agent.
141-
run: Option<File>,
142-
/// `<pubkey>.packaged`, held by a packaged copy that can run it, so dev builds let go.
143-
first: Option<File>,
138+
/// The lock file this copy holds per agent: `.packaged` or `.lock`.
139+
held: Mutex<HashMap<String, File>>,
144140
}
145141
impl Hosting {
146-
fn held(&self) -> std::sync::MutexGuard<'_, HashMap<String, Held>> {
142+
fn held(&self) -> std::sync::MutexGuard<'_, HashMap<String, File>> {
147143
self.held
148144
.lock()
149145
.unwrap_or_else(std::sync::PoisonError::into_inner)
150146
}
151-
/// Whether this copy runs the agent, taking it if no other copy does. A dev
152-
/// build lets go of it, and declines, while a packaged copy wants it.
147+
/// Whether this copy runs the agent. The packaged app always does, so a
148+
/// stuck dev build can never silence it. A dev build takes the agent if no
149+
/// other copy runs it, and lets go while the packaged app does.
153150
#[allow(clippy::incompatible_msrv)] // `File` locking; see `sign_out::Instance`.
154151
fn claim(&self, pubkey: &str) -> Result<bool, String> {
155152
if pubkey.len() != 64
@@ -161,30 +158,29 @@ impl Hosting {
161158
}
162159
let dir = self.dir.as_ref().map_err(Clone::clone)?;
163160
std::fs::create_dir_all(dir).map_err(|_| "Could not open agent hosting")?;
164-
let first = dir.join(format!("{pubkey}.packaged"));
161+
let packaged = dir.join(format!("{pubkey}.packaged"));
165162
let mut held = self.held();
166-
if !self.packaged {
167-
let probe = open_lock(&first)?;
168-
if !lock(probe.try_lock_shared())? {
169-
held.remove(pubkey);
170-
return Ok(false);
163+
if self.packaged {
164+
if !held.contains_key(pubkey) {
165+
let file = open_lock(&packaged)?;
166+
// A dev build checking for it holds it briefly; this tries again next time.
167+
if lock(file.try_lock())? {
168+
held.insert(pubkey.into(), file);
169+
}
171170
}
171+
return Ok(true);
172172
}
173-
let entry = held.entry(pubkey.into()).or_default();
174-
if self.packaged && entry.first.is_none() {
175-
let file = open_lock(&first)?;
176-
// A dev build checking for it holds it briefly; this tries again next time.
177-
if lock(file.try_lock())? {
178-
entry.first = Some(file);
179-
}
173+
if !lock(open_lock(&packaged)?.try_lock_shared())? {
174+
held.remove(pubkey);
175+
return Ok(false);
180176
}
181-
if entry.run.is_none() {
177+
if !held.contains_key(pubkey) {
182178
let file = open_lock(&dir.join(format!("{pubkey}.lock")))?;
183179
if lock(file.try_lock())? {
184-
entry.run = Some(file);
180+
held.insert(pubkey.into(), file);
185181
}
186182
}
187-
Ok(entry.run.is_some())
183+
Ok(held.contains_key(pubkey))
188184
}
189185
}
190186
/// Whether a try at a lock took it; closing the file lets go.
@@ -645,22 +641,26 @@ mod tests {
645641
}
646642

647643
#[test]
648-
fn a_dev_build_lets_go_of_what_a_packaged_copy_can_run() {
644+
fn a_packaged_app_runs_what_it_can_and_dev_builds_let_go() {
649645
let dir = tempfile::tempdir().unwrap();
650646
let (agent, other) = ("a".repeat(64), "b".repeat(64));
651647
let dev = hosting(Ok(dir.path().join("hosts")), false);
652648
let packaged = hosting(Ok(dir.path().join("hosts")), true);
653649
assert!(dev.claim(&agent).unwrap());
654650
assert!(dev.claim(&other).unwrap());
655-
// The dev build had it first, and lets go at its next claim.
656-
assert!(!packaged.claim(&agent).unwrap());
657-
assert!(!dev.claim(&agent).unwrap());
651+
// The packaged app runs it at once, though the dev build had it first,
658652
assert!(packaged.claim(&agent).unwrap());
653+
// and the dev build lets go at its next claim.
659654
assert!(!dev.claim(&agent).unwrap());
660-
// One the packaged copy does not ask for stays with the dev build.
655+
assert!(packaged.claim(&agent).unwrap());
656+
// A second dev build cannot take it either.
657+
let another = hosting(Ok(dir.path().join("hosts")), false);
658+
assert!(!another.claim(&agent).unwrap());
659+
// One the packaged app does not ask for stays with the dev build.
661660
assert!(dev.claim(&other).unwrap());
662661
// As when it can no longer run it.
663662
packaged.held().remove(&agent);
664663
assert!(dev.claim(&agent).unwrap());
664+
assert!(!another.claim(&agent).unwrap());
665665
}
666666
}

‎src/features/agents2/native.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,8 @@ export type AgentsNative = {
6363
/** Publishes its name as its profile unless the community already has it. */
6464
publishProfile(pubkey: string): Promise<void>;
6565
/** Whether this app runs the agent: every copy of the app on this machine
66-
* shares the agent list, and one holds each agent until it exits. A dev build
67-
* lets go while an installed app is running. */
66+
* shares the agent list, and one runs each agent. The installed app always
67+
* runs what it can; a dev build lets go while it does. */
6868
claim(pubkey: string): Promise<boolean>;
6969
/** Lets another copy run it. */
7070
release(pubkey: string): Promise<void>;

‎src/features/agents2/service.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,17 @@ it("lets another copy of the app run an agent it cannot run", async () => {
413413
expect(native.claim).toHaveBeenCalledWith(bot);
414414
});
415415

416+
it("claims an agent as it comes into view, and releases it as it leaves, without waiting for a tick", async () => {
417+
const { service, native, connect } = await setup();
418+
await service.create({ type: "example/echo", name: "Echo" });
419+
await vi.waitFor(() => expect(native.claim).toHaveBeenCalledWith(bot));
420+
connect(false);
421+
await vi.waitFor(() => expect(native.release).toHaveBeenCalledWith(bot));
422+
native.claim.mockClear();
423+
connect(true);
424+
await vi.waitFor(() => expect(native.claim).toHaveBeenCalledWith(bot));
425+
});
426+
416427
it("is not woken by reactions, deletions or DMs", async () => {
417428
const { service, run, emit } = await setup();
418429
await service.create({ type: "example/echo", name: "Echo" });

‎src/features/agents2/service.ts‎

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -605,6 +605,7 @@ export class Agents2Service extends Service implements Agents2 {
605605
// agent's type is replaced.
606606
private update() {
607607
const binding = this.binding;
608+
const wasShown = new Set(this.state.agents.map((agent) => agent.pubkey));
608609
const identities = this.identities.filter((identity) => !identity.deleted);
609610
const agents: Agent[] = [];
610611
for (const identity of identities) {
@@ -652,9 +653,16 @@ export class Agents2Service extends Service implements Agents2 {
652653
});
653654
this.notify();
654655
}
655-
// Resume runners whose queue paused while their agent was out of view.
656+
// Resume runners whose queue paused while their agent was out of view, and
657+
// claim or release each agent as it comes into or leaves view, so a copy of
658+
// the app takes over without waiting for an event or tick.
659+
const shown = new Set(agents.map((agent) => agent.pubkey));
656660
for (const runner of this.runners.values())
657-
if (runner.queue.length) void this.drain(runner);
661+
if (
662+
runner.queue.length ||
663+
shown.has(runner.pubkey) !== wasShown.has(runner.pubkey)
664+
)
665+
void this.drain(runner);
658666
}
659667
private notify() {
660668
for (const listener of this.listeners) listener();
@@ -829,16 +837,15 @@ export class Agents2Service extends Service implements Agents2 {
829837
runner.running = true;
830838
while (this.runners.get(runner.pubkey) === runner) {
831839
const agent = this.find(runner.pubkey);
832-
// An agent this copy cannot run is left to another copy of the app.
833-
if (!agent) {
834-
await this.release(runner);
835-
break;
836-
}
837840
const type = runner.type;
838841
const run = type?.run;
839-
if (!type || !run) {
840-
runner.queue.length = 0;
842+
// An agent this copy cannot run is left to another copy of the app.
843+
if (!agent || !type || !run) {
844+
if (agent) runner.queue.length = 0;
841845
await this.release(runner);
846+
// It may have come back into view, or gained its type, meanwhile.
847+
if (this.find(runner.pubkey) !== agent || runner.type !== type)
848+
continue;
842849
break;
843850
}
844851
// Every copy of the app on this machine hears the same events; only the

0 commit comments

Comments
 (0)