Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 27 additions & 9 deletions src/triggers/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -997,12 +997,23 @@ export function registerApiTriggers(
body: { error: "sessionId is required and must be a non-empty string" },
};
}
await withKeyedLock(`obs:${sessionId}`, () =>
kv.update(KV.sessions, sessionId, [
const endResult = await withKeyedLock(`obs:${sessionId}`, async () => {
const session = await kv.get<Session>(KV.sessions, sessionId);
if (!session || session.id !== sessionId) return "not_found" as const;
if (session.status === "completed") return "already_completed" as const;

await kv.update(KV.sessions, sessionId, [
{ type: "set", path: "endedAt", value: new Date().toISOString() },
{ type: "set", path: "status", value: "completed" },
]),
);
]);
return "ended" as const;
});
if (endResult !== "ended") {
return {
status_code: 200,
body: { success: true, ended: false, reason: endResult },
};
}
// Fan out session-stopped lifecycle (non-blocking).
try {
sdk.trigger({
Expand All @@ -1016,7 +1027,7 @@ export function registerApiTriggers(
error: err instanceof Error ? err.message : String(err),
});
}
return { status_code: 200, body: { success: true } };
return { status_code: 200, body: { success: true, ended: true } };
},
);
sdk.registerTrigger({
Expand Down Expand Up @@ -1185,6 +1196,13 @@ export function registerApiTriggers(
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
const sessions = await kv.list<Session>(KV.sessions);
const validSessions = sessions.filter(
(session): session is Session =>
!!session &&
typeof session === "object" &&
typeof session.id === "string" &&
session.id.length > 0,
);
const normalizedAgentId =
typeof req.query_params?.["agentId"] === "string"
? req.query_params["agentId"].trim()
Expand All @@ -1198,14 +1216,14 @@ export function registerApiTriggers(
(isAgentScopeIsolated() ? getAgentId() : undefined);
const listQuery = parseListQuery(req.query_params);
let filtered = filterAgentId
? sessions.filter((s) => s.agentId === filterAgentId)
: sessions;
? validSessions.filter((s) => s.agentId === filterAgentId)
: validSessions;
const facets =
req.query_params?.["facets"] === "true"
? sessionFacets(
!wildcardAgent && isAgentScopeIsolated()
? sessions.filter((s) => s.agentId === getAgentId())
: sessions,
? validSessions.filter((s) => s.agentId === getAgentId())
: validSessions,
)
: undefined;
if (listQuery.project) filtered = filtered.filter((s) => s.project === listQuery.project);
Expand Down
21 changes: 16 additions & 5 deletions src/triggers/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,13 +184,24 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
sdk.registerFunction(
"event::session::ended",
async (data: { sessionId: string }) => {
await withKeyedLock(`obs:${data.sessionId}`, () =>
kv.update(KV.sessions, data.sessionId, [
const sessionId = data?.sessionId;
if (typeof sessionId !== "string" || sessionId.length === 0) {
return { success: true, ended: false, reason: "not_found" as const };
}
const endResult = await withKeyedLock(`obs:${sessionId}`, async () => {
const session = await kv.get<Session>(KV.sessions, sessionId);
if (!session || session.id !== sessionId) return "not_found" as const;
if (session.status === "completed") return "already_completed" as const;
await kv.update(KV.sessions, sessionId, [
{ type: "set", path: "endedAt", value: new Date().toISOString() },
{ type: "set", path: "status", value: "completed" },
]),
);
return { success: true };
]);
return "ended" as const;
});
if (endResult !== "ended") {
return { success: true, ended: false, reason: endResult };
}
return { success: true, ended: true };
},
);
sdk.registerTrigger({
Expand Down
246 changes: 246 additions & 0 deletions test/session-lifecycle-api.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,246 @@
import { describe, expect, it, vi } from "vitest";

vi.mock("iii-sdk", async (importOriginal) => {
const actual = await importOriginal<typeof import("iii-sdk")>();
return {
...actual,
TriggerAction: {
...actual.TriggerAction,
Void: vi.fn(() => ({ type: "void" })),
},
};
});

import { registerApiTriggers } from "../src/triggers/api.js";
import { registerEventTriggers } from "../src/triggers/events.js";
import { KV } from "../src/state/schema.js";
import type { Session } from "../src/types.js";
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

type ApiResponse = {
status_code: number;
body: Record<string, unknown>;
};

function makeHarness(sessionRows: Array<[string, unknown]> = []) {
const store = new Map<string, Map<string, unknown>>([
[KV.sessions, new Map(sessionRows)],
[KV.summaries, new Map()],
]);
const functions = new Map<string, Function>();
const trigger = vi.fn(async () => undefined);
const update = vi.fn(
async (
scope: string,
key: string,
ops: Array<{ type: "set" | "remove"; path: string; value?: unknown }>,
) => {
const values = store.get(scope) ?? new Map<string, unknown>();
store.set(scope, values);
const existing = values.get(key);
const next =
existing && typeof existing === "object"
? { ...(existing as Record<string, unknown>) }
: {};
for (const op of ops) {
if (op.type === "remove") delete next[op.path];
else next[op.path] = op.value;
}
values.set(key, next);
return next;
},
);
const kv = {
get: vi.fn(async (scope: string, key: string) => {
if (typeof key !== "string" || key.length === 0) {
throw new Error("state::get requires a non-empty key");
}
return store.get(scope)?.get(key) ?? null;
}),
set: vi.fn(),
update,
delete: vi.fn(),
list: vi.fn(async (scope: string) =>
Array.from(store.get(scope)?.values() ?? []),
),
};
const sdk = {
registerFunction: (id: string, handler: Function) => functions.set(id, handler),
registerTrigger: vi.fn(),
trigger,
};

registerApiTriggers(sdk as never, kv as never);
registerEventTriggers(sdk as never, kv as never);

return { functions, kv, store, trigger, update };
}

function session(id: string, status: Session["status"] = "active"): Session {
return {
id,
project: "test-project",
cwd: "/tmp/test-project",
startedAt: "2026-08-26T00:00:00.000Z",
status,
observationCount: 1,
};
}

describe("session lifecycle API", () => {
it("treats ending an unknown session as a no-op without creating a partial row", async () => {
const harness = makeHarness();
const handler = harness.functions.get("api::session::end")!;

const response = (await handler({
body: { sessionId: "agent:dmp-pm:direct:test" },
})) as ApiResponse;

expect(response).toEqual({
status_code: 200,
body: { success: true, ended: false, reason: "not_found" },
});
expect(harness.update).not.toHaveBeenCalled();
expect(harness.store.get(KV.sessions)).toEqual(new Map());
expect(harness.trigger).not.toHaveBeenCalledWith(
expect.objectContaining({ function_id: "event::session::stopped" }),
);
});

it("does not treat an existing partial row as a valid session", async () => {
const sessionId = "agent:dmp-pm:direct:partial";
const harness = makeHarness([
[sessionId, { status: "completed", endedAt: "2026-08-26T00:00:00.000Z" }],
]);
const handler = harness.functions.get("api::session::end")!;

const response = (await handler({ body: { sessionId } })) as ApiResponse;

expect(response.body).toEqual({
success: true,
ended: false,
reason: "not_found",
});
expect(harness.update).not.toHaveBeenCalled();
});
Comment thread
a652 marked this conversation as resolved.
Resolved

it("treats ending an already-completed session as a no-op", async () => {
const sessionId = "agent:dmp-pm:direct:completed";
const harness = makeHarness([[sessionId, session(sessionId, "completed")]]);
const handler = harness.functions.get("api::session::end")!;

const response = (await handler({ body: { sessionId } })) as ApiResponse;

expect(response).toEqual({
status_code: 200,
body: { success: true, ended: false, reason: "already_completed" },
});
expect(harness.update).not.toHaveBeenCalled();
expect(harness.trigger).not.toHaveBeenCalled();
});

it("ends an existing session and publishes the stopped lifecycle once", async () => {
const sessionId = "agent:dmp-pm:direct:existing";
const harness = makeHarness([[sessionId, session(sessionId)]]);
const handler = harness.functions.get("api::session::end")!;

const response = (await handler({ body: { sessionId } })) as ApiResponse;

expect(response.body).toEqual({ success: true, ended: true });
expect(harness.store.get(KV.sessions)?.get(sessionId)).toMatchObject({
id: sessionId,
status: "completed",
endedAt: expect.any(String),
});
expect(harness.trigger).toHaveBeenCalledTimes(1);
expect(harness.trigger).toHaveBeenCalledWith(
expect.objectContaining({
function_id: "event::session::stopped",
payload: { sessionId },
}),
);
});

it("skips malformed rows when listing sessions and never reads an undefined summary key", async () => {
const valid = session("ses_valid", "completed");
const harness = makeHarness([
[valid.id, valid],
["agent:dmp-pm:direct:partial", { status: "completed", endedAt: "2026-08-26T00:00:00.000Z" }],
]);
const handler = harness.functions.get("api::sessions")!;

const response = (await handler({
headers: {},
query_params: { agentId: "*" },
})) as ApiResponse;

expect(response.status_code).toBe(200);
expect(response.body.sessions).toEqual([valid]);
expect(harness.kv.get).toHaveBeenCalledWith(KV.summaries, valid.id);
expect(harness.kv.get).not.toHaveBeenCalledWith(KV.summaries, undefined);
});
});

describe("event::session::ended", () => {
it("ignores an unknown session without creating a partial row", async () => {
const harness = makeHarness();
const handler = harness.functions.get("event::session::ended")!;

const result = await handler({ sessionId: "agent:dmp-pm:direct:test" });

expect(result).toEqual({ success: true, ended: false, reason: "not_found" });
expect(harness.update).not.toHaveBeenCalled();
expect(harness.store.get(KV.sessions)).toEqual(new Map());
});

it("ignores a malformed session id", async () => {
const harness = makeHarness();
const handler = harness.functions.get("event::session::ended")!;

const result = await handler({});

expect(result).toEqual({ success: true, ended: false, reason: "not_found" });
expect(harness.kv.get).not.toHaveBeenCalled();
expect(harness.update).not.toHaveBeenCalled();
});

it("does not treat an existing partial row as a valid session", async () => {
const sessionId = "agent:dmp-pm:direct:partial";
const harness = makeHarness([[sessionId, { status: "active" }]]);
const handler = harness.functions.get("event::session::ended")!;

const result = await handler({ sessionId });

expect(result).toEqual({ success: true, ended: false, reason: "not_found" });
expect(harness.update).not.toHaveBeenCalled();
});

it("leaves an already-completed session untouched", async () => {
const sessionId = "agent:dmp-pm:direct:completed";
const harness = makeHarness([[sessionId, session(sessionId, "completed")]]);
const handler = harness.functions.get("event::session::ended")!;

const result = await handler({ sessionId });

expect(result).toEqual({
success: true,
ended: false,
reason: "already_completed",
});
expect(harness.update).not.toHaveBeenCalled();
});

it("completes an existing active session", async () => {
const sessionId = "agent:dmp-pm:direct:existing";
const harness = makeHarness([[sessionId, session(sessionId)]]);
const handler = harness.functions.get("event::session::ended")!;

const result = await handler({ sessionId });

expect(result).toEqual({ success: true, ended: true });
expect(harness.store.get(KV.sessions)?.get(sessionId)).toMatchObject({
id: sessionId,
status: "completed",
endedAt: expect.any(String),
});
});
});