Skip to content

Commit fcf1239

Browse files
refactor(desktop): narrow to lifecycle and start paths; attach reads presence
Trim this PR to the reported bug: the lifecycle controls and badges, and redeploying an offline remote agent wherever a start happens. Instance reuse ranking, persona-card selection, Pulse, mention ranking, the model picker prompt and the stop-all count move to a follow-up. `attachManagedAgentToChannel` now reads presence itself for a deployed agent, so every attach path (mention, add to channel, persona provisioning in a regular channel) redeploys an offline remote agent without each caller threading presence in. The mention path re-checks cancellation after its presence read so a cancelled send queues no wake. Signed-off-by: Tony <[email protected]>
1 parent bb699c5 commit fcf1239

19 files changed

Lines changed: 119 additions & 272 deletions

‎desktop/src/features/agents/agentReuse.test.mjs‎

Lines changed: 0 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -396,46 +396,3 @@ test("resolveReusableAgentAccessPolicy uses explicit, persona, then safe default
396396
{ respondTo: "owner-only", respondToAllowlist: [] },
397397
);
398398
});
399-
400-
test("presence-aware reuse never prefers a reaped deployment over a running sibling", async () => {
401-
const { managedAgentActivityFrom } = await import(
402-
"./lib/managedAgentControlActions.ts"
403-
);
404-
// Newer `updatedAt`, so the receipt-only ranking picks it on the tie.
405-
const reaped = makeAgent({
406-
pubkey: PUB_A,
407-
personaId: "persona-1",
408-
status: "deployed",
409-
updatedAt: "2026-02-01T00:00:00Z",
410-
});
411-
const running = makeAgent({
412-
pubkey: PUB_B,
413-
personaId: "persona-1",
414-
status: "running",
415-
updatedAt: "2026-01-01T00:00:00Z",
416-
});
417-
const members = new Set();
418-
419-
assert.equal(
420-
findReusablePersonaAgent([running, reaped], "persona-1", members),
421-
reaped,
422-
"without presence the stale receipt still ranks as live",
423-
);
424-
for (const [presence, expected] of [
425-
["offline", running],
426-
["online", reaped],
427-
[undefined, reaped],
428-
]) {
429-
const isActive = managedAgentActivityFrom(new Map([[PUB_A, presence]]));
430-
assert.equal(
431-
findReusablePersonaAgent(
432-
[running, reaped],
433-
"persona-1",
434-
members,
435-
isActive,
436-
),
437-
expected,
438-
`deployed × ${presence ?? "unknown"}`,
439-
);
440-
}
441-
});

‎desktop/src/features/agents/agentReuse.ts‎

Lines changed: 7 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -36,22 +36,12 @@ export function parseTimestamp(value: string | null | undefined) {
3636
return Number.isNaN(timestamp) ? 0 : timestamp;
3737
}
3838

39-
/** Whether an instance counts as live when choosing among candidates. */
40-
export type ManagedAgentActivity = (agent: ManagedAgent) => boolean;
41-
42-
/** Lifecycle status alone. A provider's `deployed` receipt outlives a shut-down
43-
* or reaped body, so callers holding presence should pass a presence-aware
44-
* predicate instead. */
45-
const isStatusActive: ManagedAgentActivity = (agent) =>
46-
agent.status === "running" || agent.status === "deployed";
47-
48-
export function pickPreferredManagedAgent(
49-
agents: ManagedAgent[],
50-
isActive: ManagedAgentActivity = isStatusActive,
51-
) {
39+
export function pickPreferredManagedAgent(agents: ManagedAgent[]) {
5240
return [...agents].sort((left, right) => {
53-
const leftRunningScore = isActive(left) ? 1 : 0;
54-
const rightRunningScore = isActive(right) ? 1 : 0;
41+
const leftRunningScore =
42+
left.status === "running" || left.status === "deployed" ? 1 : 0;
43+
const rightRunningScore =
44+
right.status === "running" || right.status === "deployed" ? 1 : 0;
5545
if (leftRunningScore !== rightRunningScore) {
5646
return rightRunningScore - leftRunningScore;
5747
}
@@ -64,21 +54,19 @@ export function findReusablePersonaAgent(
6454
agents: ManagedAgent[],
6555
personaId: string,
6656
channelMemberPubkeys: ReadonlySet<string>,
67-
isActive?: ManagedAgentActivity,
6857
): ManagedAgent | undefined {
6958
const candidates = agents.filter(
7059
(agent) =>
7160
agent.personaId === personaId &&
7261
!channelMemberPubkeys.has(normalizePubkey(agent.pubkey)),
7362
);
74-
return pickPreferredManagedAgent(candidates, isActive);
63+
return pickPreferredManagedAgent(candidates);
7564
}
7665

7766
export function findReusableGenericAgent(
7867
agents: ManagedAgent[],
7968
command: string,
8069
channelMemberPubkeys: ReadonlySet<string>,
81-
isActive?: ManagedAgentActivity,
8270
): ManagedAgent | undefined {
8371
const candidates = agents.filter(
8472
(agent) =>
@@ -87,7 +75,7 @@ export function findReusableGenericAgent(
8775
commandsMatch(agent.agentCommand, command) &&
8876
!channelMemberPubkeys.has(normalizePubkey(agent.pubkey)),
8977
);
90-
return pickPreferredManagedAgent(candidates, isActive);
78+
return pickPreferredManagedAgent(candidates);
9179
}
9280

9381
/**

‎desktop/src/features/agents/channelAgents.attach.test.mjs‎

Lines changed: 47 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import { attachManagedAgentToChannel } from "./channelAgents.ts";
66
const AGENT_PUBKEY = "a".repeat(64);
77
const CHANNEL_ID = "11111111-2222-3333-4444-555555555555";
88

9+
const { relayClient } = await import("../../shared/api/relayClient.ts");
10+
911
function installTauriInvoke(handler) {
1012
const prior = globalThis.window;
1113
globalThis.window ??= {};
@@ -25,40 +27,57 @@ function deployedProvider() {
2527
};
2628
}
2729

28-
test("attaching a deployed provider agent redeploys only once presence shows it gone", async (t) => {
30+
/** Attach once against a relay presence answer; return what it woke. */
31+
async function wakesFor(t, { presence, connection = "connected" }) {
32+
const originalState = relayClient.getConnectionState;
33+
relayClient.getConnectionState = () => connection;
2934
const commands = [];
30-
t.after(
31-
installTauriInvoke((command) => {
32-
commands.push(command);
33-
return Promise.resolve(
34-
command === "add_channel_members"
35-
? { added: [AGENT_PUBKEY], errors: [] }
36-
: null,
37-
);
38-
}),
35+
const restore = installTauriInvoke((command) => {
36+
commands.push(command);
37+
if (command === "add_channel_members") {
38+
return Promise.resolve({ added: [AGENT_PUBKEY], errors: [] });
39+
}
40+
if (command === "get_presence") {
41+
if (presence instanceof Error) return Promise.reject(presence);
42+
return Promise.resolve(presence ? { [AGENT_PUBKEY]: presence } : {});
43+
}
44+
return Promise.resolve(null);
45+
});
46+
t.after(() => {
47+
restore();
48+
relayClient.getConnectionState = originalState;
49+
});
50+
51+
const woken = [];
52+
await attachManagedAgentToChannel(CHANNEL_ID, {
53+
agent: deployedProvider(),
54+
detachedStart: (agent) => woken.push(agent.pubkey),
55+
});
56+
assert.ok(
57+
!commands.includes("start_managed_agent"),
58+
"a detached caller owns the start; attach never fires it",
3959
);
60+
return woken;
61+
}
4062

41-
const startsFor = async (availability) => {
42-
const woken = [];
43-
await attachManagedAgentToChannel(CHANNEL_ID, {
44-
agent: deployedProvider(),
45-
availability,
46-
detachedStart: (agent) => woken.push(agent.pubkey),
47-
});
48-
return woken;
49-
};
63+
// The `deployed` receipt outlives a shut-down or inactivity-reaped pod; the
64+
// attach reads presence itself, and only established offline means redeploy.
65+
test("attach redeploys a deployed agent that presence shows offline", async (t) => {
66+
// A successful snapshot that omits the agent is established offline.
67+
assert.deepEqual(await wakesFor(t, { presence: null }), [AGENT_PUBKEY]);
68+
});
5069

51-
// The `deployed` receipt outlives a shut-down or inactivity-reaped pod;
52-
// established offline presence is what says the body is gone.
53-
assert.deepEqual(await startsFor("offline"), [AGENT_PUBKEY]);
54-
assert.deepEqual(await startsFor("online"), []);
70+
test("attach trusts the receipt while the agent is present", async (t) => {
71+
assert.deepEqual(await wakesFor(t, { presence: "online" }), []);
72+
});
73+
74+
test("attach never invents an offline agent from an unknown read", async (t) => {
5575
assert.deepEqual(
56-
await startsFor(undefined),
76+
await wakesFor(t, { presence: new Error("relay unavailable") }),
5777
[],
58-
"unknown presence keeps trusting the receipt",
5978
);
60-
assert.ok(
61-
!commands.includes("start_managed_agent"),
62-
"a detached caller owns the start; attach never fires it",
79+
assert.deepEqual(
80+
await wakesFor(t, { presence: null, connection: "disconnected" }),
81+
[],
6382
);
6483
});

‎desktop/src/features/agents/channelAgents.ts‎

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ import {
22
commandsMatch,
33
findReusableGenericAgent,
44
findReusablePersonaAgent,
5-
type ManagedAgentActivity,
65
pickPreferredManagedAgent,
76
resolveReusableAgentAccessPolicy,
87
} from "@/features/agents/agentReuse";
@@ -19,14 +18,14 @@ import {
1918
import { listPersonas } from "@/shared/api/tauriPersonas";
2019
import { startManagedAgent } from "@/shared/api/tauriManagedAgents";
2120
import { isManagedAgentLive } from "@/features/agents/lib/managedAgentControlActions";
21+
import { fetchAgentAvailability } from "@/features/agents/lib/useAgentAvailability";
2222
import type {
2323
AcpRuntime,
2424
AgentPersona,
2525
ChannelRole,
2626
CreateManagedAgentInput,
2727
ManagedAgent,
2828
ManagedAgentBackend,
29-
PresenceStatus,
3029
RespondToMode,
3130
} from "@/shared/api/types";
3231

@@ -49,11 +48,6 @@ export type AttachManagedAgentToChannelInput = {
4948
* published message and an aborted send leaves no orphan wake.
5049
*/
5150
detachedStart?: (agent: ManagedAgent) => void;
52-
/**
53-
* Relay presence, when the caller read it. A provider `deployed` receipt
54-
* established offline (shut down or reaped) is redeployed, not trusted.
55-
*/
56-
availability?: PresenceStatus;
5751
};
5852

5953
export type AttachManagedAgentToChannelResult = {
@@ -135,9 +129,6 @@ export type CreateChannelManagedAgentsResult = {
135129
type ChannelAgentReuseContext = {
136130
managedAgents: ManagedAgent[];
137131
channelMemberPubkeys: ReadonlySet<string>;
138-
/** Presence-aware liveness for ranking reuse candidates; without it a
139-
* provider's stale `deployed` receipt outranks a running local sibling. */
140-
isActive?: ManagedAgentActivity;
141132
personas: readonly Pick<
142133
AgentPersona,
143134
"id" | "respondTo" | "respondToAllowlist"
@@ -213,7 +204,15 @@ export async function attachManagedAgentToChannel(
213204
// community's (agent, relay) pair, and `startManagedAgent` spawns that same
214205
// pair — so this ensures the pair the caller is attaching to, never
215206
// another community's.
216-
if (!isManagedAgentLive(input.agent, input.availability)) {
207+
// A provider's `deployed` receipt outlives a shut-down or reaped body, so
208+
// read presence once: established offline means this attach redeploys.
209+
// Every attach path (mention, add-to-channel, persona provisioning) shares
210+
// this check rather than each caller threading presence in.
211+
const availability =
212+
input.agent.status === "deployed"
213+
? await fetchAgentAvailability(input.agent.pubkey)
214+
: undefined;
215+
if (!isManagedAgentLive(input.agent, availability)) {
217216
if (input.detachedStart) {
218217
input.detachedStart(input.agent);
219218
} else {
@@ -345,7 +344,6 @@ export async function provisionChannelManagedAgent(
345344
context.managedAgents,
346345
input.personaId,
347346
context.channelMemberPubkeys,
348-
context.isActive,
349347
);
350348
if (reusable) {
351349
const definition = context.personas.find(
@@ -378,7 +376,6 @@ export async function provisionChannelManagedAgent(
378376
context.managedAgents,
379377
input.runtime.command,
380378
context.channelMemberPubkeys,
381-
context.isActive,
382379
);
383380
if (reusable) {
384381
const { agent: updatedAgent } = await applyReusableAgentAccessPolicy(

‎desktop/src/features/agents/hooks.ts‎

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
import * as React from "react";
2-
import { managedAgentActivityFrom } from "@/features/agents/lib/managedAgentControlActions";
3-
import { fetchAgentsAvailability } from "@/features/agents/lib/useAgentAvailability";
42
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
53

64
import {
@@ -842,20 +840,12 @@ export function useProvisionChannelManagedAgentMutation(
842840
? listPersonas()
843841
: Promise.resolve([]),
844842
]);
845-
// One presence read, only when a deployed provider instance could be
846-
// a reuse candidate: its receipt alone must not outrank a live sibling.
847-
const availability = await fetchAgentsAvailability(
848-
managedAgents
849-
.filter((agent) => agent.status === "deployed")
850-
.map((agent) => agent.pubkey),
851-
);
852843
return provisionChannelManagedAgent(rest, {
853844
managedAgents,
854845
personas,
855846
channelMemberPubkeys: new Set(
856847
members.map((member) => normalizePubkey(member.pubkey)),
857848
),
858-
isActive: managedAgentActivityFrom(availability),
859849
});
860850
},
861851
onSuccess: (result) => {

‎desktop/src/features/agents/lib/managedAgentControlActions.ts‎

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -56,15 +56,6 @@ export function isManagedAgentLive(
5656
return agent.status === "running";
5757
}
5858

59-
/** Presence-aware liveness for ranking candidate instances, from a one-shot
60-
* availability read keyed by normalized pubkey (see `fetchAgentsAvailability`). */
61-
export function managedAgentActivityFrom(
62-
availability: ReadonlyMap<string, PresenceStatus | undefined>,
63-
) {
64-
return (agent: Pick<ManagedAgent, "pubkey" | "status">) =>
65-
isManagedAgentLive(agent, availability.get(normalizePubkey(agent.pubkey)));
66-
}
67-
6859
/** The status to display: a `deployed` receipt whose agent is established
6960
* offline reads as stopped, the same as a local agent that is not running. */
7061
export function displayedManagedAgentStatus(

‎desktop/src/features/agents/lib/pickProfileAgent.test.mjs‎

Lines changed: 0 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -65,29 +65,3 @@ test("a fail-open predicate keeps every instance eligible while loading", () =>
6565
// Fail-open (all false) during the archive-snapshot window: normal ranking.
6666
assert.equal(pickProfileAgent([stopped, running], NONE_ARCHIVED), running);
6767
});
68-
69-
test("a deployment presence shows offline does not outrank a running sibling", () => {
70-
const reaped = agent({
71-
name: "A reaped deployment",
72-
pubkey: "a".repeat(64),
73-
status: "deployed",
74-
});
75-
const running = agent({
76-
name: "B running instance",
77-
pubkey: "b".repeat(64),
78-
status: "running",
79-
});
80-
const presence = (status) => (pubkey) =>
81-
pubkey === reaped.pubkey ? status : undefined;
82-
83-
// Both rank active without presence, so the name tiebreak picks the reaped one.
84-
assert.equal(pickProfileAgent([running, reaped], NONE_ARCHIVED), reaped);
85-
assert.equal(
86-
pickProfileAgent([running, reaped], NONE_ARCHIVED, presence("offline")),
87-
running,
88-
);
89-
assert.equal(
90-
pickProfileAgent([running, reaped], NONE_ARCHIVED, presence("online")),
91-
reaped,
92-
);
93-
});

‎desktop/src/features/agents/lib/pickProfileAgent.ts‎

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { isManagedAgentLive } from "@/features/agents/lib/managedAgentControlActions";
2-
import type { ManagedAgent, PresenceStatus } from "@/shared/api/types";
1+
import { isManagedAgentActive } from "@/features/agents/lib/managedAgentControlActions";
2+
import type { ManagedAgent } from "@/shared/api/types";
33

44
/**
55
* Pick the instance that represents a persona throughout the UI.
@@ -13,22 +13,17 @@ import type { ManagedAgent, PresenceStatus } from "@/shared/api/types";
1313
* instance is archived — the card then renders in persona-only mode. The
1414
* `isArchived` predicate is fail-open (returns `false` while the relay archive
1515
* snapshot loads), so a cold start never briefly picks nothing.
16-
*
17-
* Pass `getAvailability` where the surface has presence: a provider's
18-
* `deployed` receipt outlives a shut-down or reaped body and must not outrank
19-
* a sibling that is actually running.
2016
*/
2117
export function pickProfileAgent(
2218
agents: readonly ManagedAgent[],
2319
isArchived: (pubkey: string) => boolean,
24-
getAvailability?: (pubkey: string) => PresenceStatus | undefined,
2520
) {
26-
const isActive = (agent: ManagedAgent) =>
27-
isManagedAgentLive(agent, getAvailability?.(agent.pubkey));
2821
return [...agents]
2922
.filter((agent) => !isArchived(agent.pubkey))
3023
.sort((left, right) => {
31-
const activeDiff = Number(isActive(right)) - Number(isActive(left));
24+
const activeDiff =
25+
Number(isManagedAgentActive(right)) -
26+
Number(isManagedAgentActive(left));
3227
if (activeDiff !== 0) return activeDiff;
3328
return left.name.localeCompare(right.name);
3429
})[0];

0 commit comments

Comments
 (0)