Skip to content

Commit a86967d

Browse files
author
hMB2
committed
agents2: keep create and delete retryable; address review
- Native delete removes the key before forgetting the identity, so a refused credential store leaves the identity for a retry. - Native commit saves the identity before the key and withdraws it only once the key is known to be gone, so no key is ever left without an identity. - Create saves the local record before native commit, and `write` changes memory only after storage accepts it; a failed write commits nothing. - Create returns the committed agent even when the community changed meanwhile; the page opens it only if it is in the community still shown. - The profile panel keeps Agents2 behavior (Attention, no Memories) for a saved agent whose type plugin is unavailable. - Escape in the rename field no longer saves the discarded name. - New attention slugs never reuse a skipped object's slug.
1 parent 1c49853 commit a86967d

10 files changed

Lines changed: 279 additions & 39 deletions

File tree

‎crates/agent-controller/src/app_agent.rs‎

Lines changed: 33 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,10 @@ impl AppAgents {
152152
owner: owner.into(),
153153
})
154154
}
155-
/// Saves the key, then the identity. An attestation for another key or owner is refused.
155+
/// Saves the identity, then the key, so a saved key always has an identity to
156+
/// delete it by. If the key cannot be saved, the identity is withdrawn once
157+
/// its key is known to be gone; otherwise it stays for `remove` to retry.
158+
/// An attestation for another key or owner is refused.
156159
pub fn commit(
157160
&self,
158161
prepared: NewAppAgent,
@@ -173,29 +176,43 @@ impl AppAgents {
173176
auth,
174177
};
175178
let id = agent.credential_id();
176-
credentials.add(&id, &prepared.key)?;
177-
agent
178-
.read_key(credentials)
179-
.map_err(|_| "New agent key could not be verified")?;
180179
self.update(|agents| {
181180
agents.retain(|saved| saved.pubkey != agent.pubkey);
182181
agents.push(agent.clone());
183182
Ok(())
184183
})?;
184+
let saved = credentials.add(&id, &prepared.key).and_then(|()| {
185+
agent
186+
.read_key(credentials)
187+
.map(drop)
188+
.map_err(|_| "New agent key could not be verified".into())
189+
});
190+
if let Err(error) = saved {
191+
if credentials.delete(&id, &agent.pubkey).is_ok() {
192+
let _ = self.forget(&agent.pubkey);
193+
}
194+
return Err(error);
195+
}
185196
Ok(agent)
186197
}
187-
/// Forgets the identity, then deletes its key. Absence is success.
198+
/// Deletes the key, then forgets the identity, so a failed deletion can be
199+
/// retried. Absence is success.
188200
pub fn remove(&self, pubkey: &str, credentials: &dyn Credentials) -> Result<()> {
189-
let removed = self.update(|agents| {
190-
Ok(agents
191-
.iter()
192-
.position(|agent| agent.pubkey == pubkey)
193-
.map(|index| agents.remove(index)))
194-
})?;
195-
match removed {
196-
Some(agent) => credentials.delete(&agent.credential_id(), &agent.pubkey),
197-
None => Ok(()),
198-
}
201+
let Some(agent) = self
202+
.list()?
203+
.into_iter()
204+
.find(|agent| agent.pubkey == pubkey)
205+
else {
206+
return Ok(());
207+
};
208+
credentials.delete(&agent.credential_id(), &agent.pubkey)?;
209+
self.forget(pubkey)
210+
}
211+
fn forget(&self, pubkey: &str) -> Result<()> {
212+
self.update(|agents| {
213+
agents.retain(|agent| agent.pubkey != pubkey);
214+
Ok(())
215+
})
199216
}
200217
}
201218

‎crates/agent-controller/src/app_agent/tests.rs‎

Lines changed: 69 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,30 @@ use std::collections::BTreeMap;
33
use std::sync::Mutex;
44

55
#[derive(Default)]
6-
struct Memory(Mutex<BTreeMap<String, String>>);
6+
struct Memory(Mutex<BTreeMap<String, String>>, Faults);
7+
/// Credential-store operations to refuse, standing in for a denied or busy store.
8+
#[derive(Default)]
9+
struct Faults {
10+
add: std::sync::atomic::AtomicBool,
11+
read: std::sync::atomic::AtomicBool,
12+
delete: std::sync::atomic::AtomicBool,
13+
}
14+
fn set(fault: &std::sync::atomic::AtomicBool, on: bool) {
15+
fault.store(on, std::sync::atomic::Ordering::SeqCst);
16+
}
17+
fn failing(fault: &std::sync::atomic::AtomicBool) -> Result<()> {
18+
if fault.load(std::sync::atomic::Ordering::SeqCst) {
19+
Err("Credential store refused".into())
20+
} else {
21+
Ok(())
22+
}
23+
}
724
impl Credentials for Memory {
825
fn read_legacy(&self, _: crate::LegacySource, _: &str) -> Result<Secret> {
926
panic!("App agents never import")
1027
}
1128
fn read(&self, id: &str, pubkey: &str) -> Result<Option<Secret>> {
29+
failing(&self.1.read)?;
1230
self.0
1331
.lock()
1432
.unwrap()
@@ -17,13 +35,15 @@ impl Credentials for Memory {
1735
.transpose()
1836
}
1937
fn add(&self, id: &str, key: &Secret) -> Result<()> {
38+
failing(&self.1.add)?;
2039
self.0
2140
.lock()
2241
.unwrap()
2342
.insert(id.into(), key.hex().to_string());
2443
Ok(())
2544
}
2645
fn delete(&self, id: &str, _: &str) -> Result<()> {
46+
failing(&self.1.delete)?;
2747
self.0.lock().unwrap().remove(id);
2848
Ok(())
2949
}
@@ -61,6 +81,54 @@ fn creates_saves_and_removes_an_identity_with_its_key() {
6181
agents.remove(&agent.pubkey, &credentials).unwrap();
6282
}
6383

84+
#[test]
85+
fn a_failed_key_deletion_keeps_the_identity_for_a_retry() {
86+
let dir = tempfile::tempdir().unwrap();
87+
let credentials = Memory::default();
88+
let (agents, agent) = created(dir.path(), &credentials);
89+
set(&credentials.1.delete, true);
90+
assert!(agents.remove(&agent.pubkey, &credentials).is_err());
91+
assert_eq!(agents.list().unwrap(), std::slice::from_ref(&agent));
92+
assert!(agent.read_key(&credentials).is_ok());
93+
set(&credentials.1.delete, false);
94+
agents.remove(&agent.pubkey, &credentials).unwrap();
95+
assert!(agents.list().unwrap().is_empty());
96+
assert!(credentials.0.lock().unwrap().is_empty());
97+
}
98+
99+
#[test]
100+
fn a_failed_key_save_leaves_no_orphaned_key() {
101+
let dir = tempfile::tempdir().unwrap();
102+
let credentials = Memory::default();
103+
let agents = AppAgents::open(dir.path().join("identities.json"));
104+
let commit = |credentials: &Memory| {
105+
let prepared = AppAgents::prepare("wss://relay.example", &owner()).unwrap();
106+
let auth: Vec<String> =
107+
serde_json::from_str(&crate::secret::test_attestation(prepared.pubkey())).unwrap();
108+
agents.commit(prepared, &auth, credentials)
109+
};
110+
// The store refuses the key: nothing is left behind.
111+
set(&credentials.1.add, true);
112+
assert!(commit(&credentials).is_err());
113+
assert!(agents.list().unwrap().is_empty());
114+
set(&credentials.1.add, false);
115+
// The key is saved but cannot be read back: it is deleted with its identity.
116+
set(&credentials.1.read, true);
117+
assert!(commit(&credentials).is_err());
118+
assert!(agents.list().unwrap().is_empty());
119+
assert!(credentials.0.lock().unwrap().is_empty());
120+
// ...and if it cannot be deleted either, its identity stays so `remove` can.
121+
set(&credentials.1.delete, true);
122+
assert!(commit(&credentials).is_err());
123+
let [stranded] = agents.list().unwrap().try_into().unwrap();
124+
set(&credentials.1.read, false);
125+
set(&credentials.1.delete, false);
126+
assert!(stranded.read_key(&credentials).is_ok());
127+
agents.remove(&stranded.pubkey, &credentials).unwrap();
128+
assert!(agents.list().unwrap().is_empty());
129+
assert!(credentials.0.lock().unwrap().is_empty());
130+
}
131+
64132
#[test]
65133
fn refuses_an_attestation_for_another_key_or_owner() {
66134
let dir = tempfile::tempdir().unwrap();

‎src/bundled/agents2/Agents2Page.test.tsx‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ const agent = (name: string, n: number): Agent => ({
4848
},
4949
});
5050

51-
function setup(agents: Agent[]) {
51+
function setup(agents: Agent[], { shown = true } = {}) {
5252
let snapshot: AgentsSnapshot = { status: "ready", agents };
5353
const listeners = new Set<() => void>();
5454
const type = {
@@ -75,6 +75,8 @@ function setup(agents: Agent[]) {
7575
find: (pubkey: string) => snapshot.agents.find((a) => a.pubkey === pubkey),
7676
register: vi.fn(),
7777
create: vi.fn(async () => {
78+
// `shown: false`: it was made for a community no longer selected.
79+
if (!shown) return created;
7880
snapshot = { ...snapshot, agents: [...snapshot.agents, created] };
7981
for (const listener of listeners) listener();
8082
return created;
@@ -149,3 +151,36 @@ it("makes a new agent in the side panel and goes straight to building it", async
149151
expect(await screen.findByRole("tab", { name: "Attention" })).toBeVisible();
150152
expect(screen.getByRole("heading", { name: "Nova" })).toBeInTheDocument();
151153
});
154+
155+
it("stays on the grid when the new agent belongs to a community no longer shown", async () => {
156+
const user = userEvent.setup();
157+
const { agents2 } = setup([agent("Ada", 1)], { shown: false });
158+
await user.click(screen.getByRole("button", { name: "New agent" }));
159+
const form = screen.getByRole("form", { name: "New agent" });
160+
await user.type(within(form).getByLabelText("Name"), "Nova{Enter}");
161+
await vi.waitFor(() => expect(agents2.create).toHaveBeenCalled());
162+
expect(
163+
await screen.findByRole("listbox", { name: "Agents" }),
164+
).toBeInTheDocument();
165+
expect(screen.queryByRole("form", { name: "New agent" })).toBeNull();
166+
expect(screen.queryByRole("tab", { name: "Attention" })).toBeNull();
167+
});
168+
169+
it("saves a rename on Enter and discards it on Escape", async () => {
170+
const user = userEvent.setup();
171+
const { agents2 } = setup([agent("Ada", 1)]);
172+
await user.click(screen.getByRole("option", { name: /Ada/ }));
173+
await user.keyboard("{Enter}");
174+
const field = within(
175+
screen.getByRole("complementary", { name: "Ada identity" }),
176+
).getByLabelText("Name");
177+
await user.clear(field);
178+
await user.type(field, "Discarded{Escape}");
179+
expect(agents2.save).not.toHaveBeenCalled();
180+
expect(field).toHaveValue("Ada");
181+
await user.clear(field);
182+
await user.type(field, "Kept{Enter}");
183+
expect(agents2.save).toHaveBeenCalledExactlyOnceWith("1".repeat(64), {
184+
name: "Kept",
185+
});
186+
});

‎src/bundled/agents2/Agents2Page.tsx‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,11 @@ export function Agents2Page({
118118
agents2={agents2}
119119
types={types}
120120
onClose={() => browse()}
121-
onCreated={(agent) => build(agent.pubkey)}
121+
// The community may have changed while it was created; the agent then
122+
// lives in the one it was made for, so stay on this grid.
123+
onCreated={(agent) =>
124+
agents2.find(agent.pubkey) ? build(agent.pubkey) : browse()
125+
}
122126
/>
123127
) : selected ? (
124128
<AgentPeek
@@ -585,8 +589,14 @@ function NameField({
585589
}) {
586590
const [draft, setDraft] = useState(name);
587591
const [error, setError] = useState("");
592+
// Escape blurs too, and blur saves; this skips that one save.
593+
const cancelled = useRef(false);
588594
useEffect(() => setDraft(name), [name]);
589595
const commit = () => {
596+
if (cancelled.current) {
597+
cancelled.current = false;
598+
return;
599+
}
590600
const next = draft.trim();
591601
if (!next) return setDraft(name);
592602
if (next === name) return;
@@ -605,8 +615,10 @@ function NameField({
605615
onKeyDown={(event) => {
606616
if (event.key === "Enter") event.currentTarget.blur();
607617
if (event.key === "Escape") {
618+
cancelled.current = true;
608619
setDraft(name);
609620
event.currentTarget.blur();
621+
cancelled.current = false;
610622
}
611623
}}
612624
/>

‎src/features/agents2/AttentionPanel.test.tsx‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,3 +197,31 @@ it("keeps an Interest in use, shows skipped objects, and rearms a spent timer",
197197
];
198198
expect(change.attention["watch/timer"]?.armed_at).toBeGreaterThan(100);
199199
});
200+
201+
it("never names a new object after a skipped one it would replace", async () => {
202+
const user = userEvent.setup();
203+
const save = vi.fn(async () => {});
204+
render(
205+
<AttentionPanel
206+
agent={{
207+
...agent,
208+
skipped: {
209+
"watch/messages": {
210+
slug: "watch/messages",
211+
value: { type: "event" },
212+
modifiedAt: 1,
213+
problem: "Missing field: interest_id",
214+
},
215+
},
216+
}}
217+
save={save}
218+
channels={[]}
219+
/>,
220+
);
221+
const group = screen.getByRole("region", { name: "Release triage" });
222+
await user.click(within(group).getByRole("button", { name: "Add watch" }));
223+
await user.click(screen.getByRole("button", { name: "Add watch" }));
224+
expect(save).toHaveBeenLastCalledWith({
225+
attention: { "watch/messages-2": expect.any(Object) },
226+
});
227+
});

‎src/features/agents2/AttentionPanel.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -640,8 +640,11 @@ function freeSlug(space: "interest" | "watch", base: string, agent: Agent) {
640640
.toLowerCase()
641641
.replace(/[^!-~]+/g, "-")
642642
.slice(0, 56) || space;
643+
// A skipped object still owns its slug until it is fixed or removed.
644+
const taken = (slug: string) =>
645+
slug in agent.attention || slug in agent.skipped;
643646
let id = stem;
644-
for (let n = 2; `${space}/${id}` in agent.attention; n++) id = `${stem}-${n}`;
647+
for (let n = 2; taken(`${space}/${id}`); n++) id = `${stem}-${n}`;
645648
return `${space}/${id}`;
646649
}
647650
const now = () => Math.floor(Date.now() / 1000);
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// @vitest-environment jsdom
2+
import { renderHook } from "@testing-library/react";
3+
import { expect, it } from "vitest";
4+
import { useAgent2 } from "./react";
5+
import type { Agent, Agents2 } from "./service";
6+
7+
it("still finds a saved agent whose type plugin is not registered", () => {
8+
const agent = { pubkey: "a".repeat(64), type: "gone/echo" } as Agent;
9+
const agents2 = {
10+
subscribe: () => () => {},
11+
find: (pubkey: string) => (pubkey === agent.pubkey ? agent : undefined),
12+
types: () => [],
13+
} as unknown as Agents2;
14+
const { result } = renderHook(() => useAgent2(agents2, agent.pubkey));
15+
expect(result.current).toEqual({ agent, type: undefined });
16+
const other = renderHook(() => useAgent2(agents2, "b".repeat(64)));
17+
expect(other.result.current).toBeUndefined();
18+
});

‎src/features/agents2/react.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ export function useAgents2(agents2: Agents2) {
2121
return { snapshot, types };
2222
}
2323

24-
/** The Agents2 agent at `pubkey` with its type, when both are present. */
24+
/** The Agents2 agent at `pubkey`, with its type when that is registered. A saved
25+
* agent whose type plugin is disabled or reloading is still an Agents2 agent. */
2526
export function useAgent2(agents2: Agents2 | undefined, pubkey: string) {
2627
const subscribe = agents2?.subscribe ?? noSubscribe;
2728
const agent = useSyncExternalStore(
@@ -36,7 +37,7 @@ export function useAgent2(agents2: Agents2 | undefined, pubkey: string) {
3637
: none,
3738
none,
3839
);
39-
return agent && type ? { agent, type } : undefined;
40+
return agent ? { agent, type } : undefined;
4041
}
4142

4243
const noList = () => undefined;

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

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -376,6 +376,48 @@ it("keeps a created agent when its profile cannot be published", async () => {
376376
warn.mockRestore();
377377
});
378378

379+
it("commits no identity when its record cannot be saved", async () => {
380+
const storage = memoryStorage();
381+
const { service, native } = await setup({ storage });
382+
const setItem = vi.spyOn(storage, "setItem").mockImplementationOnce(() => {
383+
throw new Error("QuotaExceededError");
384+
});
385+
await expect(
386+
service.create({ type: "example/echo", name: "Echo" }),
387+
).rejects.toThrow("QuotaExceededError");
388+
expect(native.commit).not.toHaveBeenCalled();
389+
// Memory did not take the failed write, so a later save cannot expose it.
390+
await service.create({ type: "example/echo", name: "Next" });
391+
expect(storage.getItem("buzz.agents2.v1")).not.toContain(bot);
392+
expect(service.snapshot().agents.map((agent) => agent.name)).toEqual([
393+
"Next",
394+
]);
395+
setItem.mockRestore();
396+
});
397+
398+
it("keeps the record of a create whose native commit fails, for the identity it may have left", async () => {
399+
const storage = memoryStorage();
400+
const { service, native } = await setup({ storage });
401+
native.commit.mockRejectedValueOnce(new Error("Credential store refused"));
402+
await expect(
403+
service.create({ type: "example/echo", name: "Echo" }),
404+
).rejects.toThrow("Credential store refused");
405+
// Not shown without an identity, but there to manage one by after a reload.
406+
expect(service.find(bot)).toBeUndefined();
407+
expect(storage.getItem("buzz.agents2.v1")).toContain(bot);
408+
});
409+
410+
it("returns the created agent after the community changes mid-create", async () => {
411+
const { service, native, connect } = await setup();
412+
native.commit.mockImplementationOnce(async (pubkey: string) => {
413+
connect(false);
414+
return { pubkey, relay: "wss://relay.example.test", owner: viewer };
415+
});
416+
const agent = await service.create({ type: "example/echo", name: "Echo" });
417+
expect(agent).toMatchObject({ pubkey: bot, name: "Echo" });
418+
expect(service.find(bot)).toBeUndefined();
419+
});
420+
379421
it("forgets records whose key is gone when identities load", async () => {
380422
const storage = memoryStorage();
381423
storage.setItem(

0 commit comments

Comments
 (0)