mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-03 09:37:19 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Task conversations save messages that arrive during an active turn. > - Legacy adapters deliver these messages in a later turn. > - A run can stop before the saved queue is delivered. > - The Interrupt button previously required an active run, so it could not release this queue. > - This pull request lets a board operator send the saved queue after the run stops and retries queues missed during finalization. > - Manual dispatch must use the clicking operator and must not require permission to create agents. > - The task can continue without a duplicate message or a second execution owner. ## Linked Issues or Issue Description **What happened?** A legacy task retained a queued message after its run stopped. Interrupt was disabled because the queue had no active target. Finalization and deferred message admission can also leave a queue without a successor. **Expected behavior** Interrupt sends the saved messages when no runner is active. Messages that arrive during normal completion are delivered automatically. An uncertain previous execution still requires proof that its process or sandbox stopped. **Steps to reproduce** 1. Queue a user message during a legacy conversation turn. 2. Let the turn stop or simulate a server restart before queue promotion. 3. Open the task with a deferred queue and no active run. 4. Try Interrupt. Before this change, the button is disabled. **Paperclip version or commit** Reproduced against `8f40b4ad4`. **Deployment mode** Legacy conversation adapter. The same persisted queue state is covered with an isolated PostgreSQL fixture. Related public work: #13275 adds active legacy interruption. #13291 addresses automatic sandbox conversation recovery. This change handles explicit saved-queue delivery and late queue promotion. ## What Changed - Accept a null Interrupt target while retaining queue identity, revision, company, and assignee checks. - Save the operator's request on the existing queue. Reuse normal admission after verified stop, including older messages, different authors, and queues whose original wake came from the system. - Strip interruption authority from caller-supplied wake payloads. Only the board queue route can persist that authority. - Retry durable interruption requests after restart and deferred queues after legacy cleanup. - Let an explicit Interrupt retry cleanup for its stopped run, including old ephemeral leases that recorded success without a provider stop receipt. Preserve retained resources, other lease owners, and the automatic retry limit. - Preserve the server's waiting explanation when normalizing and combining queue entries. - Revalidate the consumed board queue receipt at dispatch so a different message author does not cause setup failure. - Use the Interrupt user's execution identity for the new run. Preserve original message authors. Validate the receipt independently at startup and inherit the resulting identity on retry. - Persist authenticated board authority for ordinary manual wakes too. Adopting someone else's queued messages cannot switch a manual run to that author's permissions. Strip caller-supplied authority markers and retain private conversation ownership checks. - Keep the clicking user when a manual wake is merged into an older deferred receipt. Update its requester and payload in the same transaction. - Use the same current-queue/revision API on task details and pipeline conversations; show Interrupt after a legacy target stops. - Keep manual wakes out of active runs, including unscoped agent wakes. They receive their own execution identity; a matching receipt requester is not sufficient because an exact retry can retain a different originating identity. - Authorize both existing-agent wake endpoints with `agent:wake`, available to active non-viewer company members. Keep `agents:create` for hiring. Validate the stored task and current assignee before an exact task retry. - Reject viewer Interrupt requests before saving intent or stopping execution. Keep external chat retry authorization and per-action agent/user permission checks. - Preserve edits and discards until dispatch. Prevent another queue promotion when the same agent already has a successor. Keep independent reviewer recovery available. - Suppress cancelled/failed run toasts for intentional operator interruption. Keep ordinary runtime error notices. - Add UI, route, admission, restart, successor ownership, and toast regression tests. Document the behavior. - Reuse the existing socket reservation helper for both credential-quorum test cases after CI exposed an ambient-port collision. This changes test preparation only; production credential staging is still called exactly once. ## Verification - Failing regression tests reproduced the message-author identity bug and an operator's `agents:create` rejection before the fixes. - All 316 focused tests pass across eight route, queue, identity, authorization, continuation, and responsible-user suites, including the 44-test rerun of queue admission and actual startup after the final manual-wake restriction. Regressions reproduce cross-user merging both with and without a task, and same-requester receipt ambiguity. The cross-company existence guard also passes both tests. - Startup integration tests reach adapter execution under the clicking operator and retain that identity through follow-up. Coverage includes mixed authors, adopted queues, system-origin queues, restarts, forged or stale receipts, viewers, suspended memberships, changed assignees, private conversations, and caller-supplied authority markers. - The earlier queue/cleanup/UI regression suite passed 402 tests. The final review corrections pass another 180 tests across queue admission/persistence, real heartbeat startup, UI API, conversation rendering, and pipeline suites. Regression tests reproduced both review findings before correction. The final head has a 5/5 review with no unresolved threads. Full CI passes on `c2002979c`, including every general and serialized server shard, all browser shards, Paperclip Runner verification, typecheck, build, canary dry run, and the aggregate gates. - Full `pnpm -r typecheck`, `pnpm build`, and UI token gates pass after the final application changes. CI identified an outdated task-page API mock after the shared helper extraction; the fixture now exercises the real helper, and all 131 task-page/API tests pass. The final application build passes with the additional manual-wake restriction. - CI exposed a pre-existing port collision in the Codex credential-quorum fixture. It reproduced locally; both listener cases now use the existing bounded reservation helper. All 41 credential tests pass on rerun. One intervening local run hit a separate ambient bind collision in the two-occupied-port case. - The full local `pnpm test:run` attempt was stopped after host contention caused focused-suite timeouts. The affected focused tests passed on rerun. An expiring trace fixture and a missing private-conversation state were corrected. The successful full CI run is the complete-suite verification. - Hosted Interrupt previously cleared the original queue and produced exactly one successor with neutral interruption feedback. It exposed the dispatch authorization defect. Retry on that earlier build was rejected for missing `agents:create` before creating another run. - Deployed the final application build (`38257f391`) to the scoped hosted instance and verified readiness. The latest PR commit changes only the credential test fixture; application code matches that deployment. A live Retry by the same operator without `agents:create` created one successor attributed to that operator, passing the former dispatch permission gate. Startup then stopped at `configuration_incomplete` because that operator has not configured their required personal Claude Code OAuth secret; the post-deployment run page confirms the operator identity and no provider work started, and the My secrets UI still shows the token as not set. Provider execution remains unverified pending that credential. No permission grants or credentials were changed. ## Risks Queue admission and finalization can race. The task lock, durable queue receipt, current comment IDs, and successor guard prevent duplicate dispatch. Process and lease stop checks, task pauses, approvals, ownership, and budgets remain in force. The API change only allows null on legacy Interrupt; native steering still requires an active run. No schema migration is required. Active non-viewer board members can now invoke existing agents without agent-creation permission. Agent self-invocation rules, raw provider-trace admin access, task retry scope, external chat authorization, and action-specific user/agent permissions remain enforced. ## Model Used OpenAI GPT-6 through Codex. The session does not expose an exact backend model ID or context-window size. Used reasoning, repository search, code execution, tests, and browser tools. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
254 lines
17 KiB
TypeScript
254 lines
17 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { eq, sql } from "drizzle-orm";
|
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
import { agentWakeupRequests, agents, companies, createDb, heartbeatRuns, heartbeatRunEvents, issueComments, issueThreadInteractions, issues } from "@paperclipai/db";
|
|
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
|
import { acceptSteeredIdentity, captureRunIdentity, initializeRunIdentity, listRunIdentityContexts, rejectSteeredIdentity, reserveSteeredIdentity } from "../services/run-identity.js";
|
|
|
|
const support = await getEmbeddedPostgresTestSupport();
|
|
(support.supported ? describe : describe.skip)("durable execution identity", () => {
|
|
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
|
let db: ReturnType<typeof createDb>;
|
|
beforeAll(async () => {
|
|
database = await startEmbeddedPostgresTestDatabase("paperclip-run-identity-");
|
|
db = createDb(database.connectionString);
|
|
}, 30_000);
|
|
afterAll(async () => { await database?.cleanup(); }, 60_000);
|
|
|
|
async function seed() {
|
|
const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID();
|
|
await db.insert(companies).values({ id: companyId, name: "Identity tests", issuePrefix: companyId.slice(0, 8) });
|
|
await db.insert(agents).values({ id: agentId, companyId, name: "Shared agent", role: "engineer", adapterType: "codex_local" });
|
|
await db.insert(issues).values({ id: issueId, companyId, title: "Shared task", responsibleUserId: "owner" });
|
|
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", contextSnapshot: { issueId } });
|
|
const messageIds: string[] = [];
|
|
for (const author of ["A", "B", "A"]) {
|
|
const id = randomUUID();
|
|
await db.insert(issueComments).values({ id, companyId, issueId, authorUserId: author, body: "Instruction" });
|
|
messageIds.push(id);
|
|
}
|
|
return { companyId, agentId, issueId, runId, messageIds };
|
|
}
|
|
it("retains mixed-author delivery order without rewriting task ownership", async () => {
|
|
const input = await seed();
|
|
await initializeRunIdentity(db, { ...input, responsibleUserId: "owner", cause: "queued" });
|
|
const history = await listRunIdentityContexts(db, input.companyId, input.runId);
|
|
expect(history.map((row) => row.responsibleUserId)).toEqual(["owner", "A", "B", "A"]);
|
|
expect(history.map((row) => row.revision)).toEqual([1, 2, 3, 4]);
|
|
expect((await captureRunIdentity(db, input)).context?.responsibleUserId).toBe("A");
|
|
const [issue] = await db.select().from(issues).where(eq(issues.id, input.issueId));
|
|
expect(issue.responsibleUserId).toBe("owner");
|
|
await initializeRunIdentity(db, { ...input, responsibleUserId: "B", cause: "restart" });
|
|
expect(await listRunIdentityContexts(db, input.companyId, input.runId)).toHaveLength(4);
|
|
});
|
|
async function seedInterrupt() {
|
|
const input = await seed();
|
|
const queueId = randomUUID(), wakeupRequestId = randomUUID();
|
|
const contextSnapshot = { issueId: input.issueId, wakeCommentIds: input.messageIds };
|
|
await db.insert(agentWakeupRequests).values([
|
|
{ id: queueId, companyId: input.companyId, agentId: input.agentId, source: "automation",
|
|
status: "coalesced", runId: input.runId, requestedByActorType: "system",
|
|
payload: { issueId: input.issueId, _paperclipWakeContext: { wakeCommentIds: input.messageIds },
|
|
queuedCommentInterrupt: { actorId: "operator", requestedAt: new Date().toISOString() } } },
|
|
{ id: wakeupRequestId, companyId: input.companyId, agentId: input.agentId, source: "on_demand",
|
|
status: "queued", runId: input.runId, requestedByActorType: "user", requestedByActorId: "operator",
|
|
idempotencyKey: `queued-comment-interrupt:${queueId}` },
|
|
]);
|
|
await db.update(heartbeatRuns).set({ wakeupRequestId, contextSnapshot }).where(eq(heartbeatRuns.id, input.runId));
|
|
return { ...input, queueId, wakeupRequestId, contextSnapshot };
|
|
}
|
|
|
|
it("uses the clicking operator through startup and restart without changing message authors", async () => {
|
|
const input = await seedInterrupt();
|
|
// A stale originating context cannot replace the explicit click's identity.
|
|
const identity = await initializeRunIdentity(db, {
|
|
...input, responsibleUserId: "A", parentContextId: randomUUID(), cause: "dispatch",
|
|
});
|
|
expect(identity).toMatchObject({ responsibleUserId: "operator", cause: "queued_comment_interrupt" });
|
|
const history = await listRunIdentityContexts(db, input.companyId, input.runId);
|
|
expect(history.map(row => row.responsibleUserId)).toEqual(["operator", "operator", "operator", "operator"]);
|
|
expect(await initializeRunIdentity(db, { ...input, responsibleUserId: "B", cause: "restart" })).toEqual(identity);
|
|
const comments = await db.select().from(issueComments).where(eq(issueComments.issueId, input.issueId));
|
|
expect(input.messageIds.map(id => comments.find(c => c.id === id)?.authorUserId)).toEqual(["A", "B", "A"]);
|
|
expect((await captureRunIdentity(db, input)).context?.responsibleUserId).toBe("operator");
|
|
const retryRunId = randomUUID();
|
|
await db.insert(heartbeatRuns).values({ id: retryRunId, companyId: input.companyId,
|
|
agentId: input.agentId, contextSnapshot: input.contextSnapshot, status: "queued", retryOfRunId: input.runId });
|
|
const retried = await initializeRunIdentity(db, { companyId: input.companyId, runId: retryRunId,
|
|
issueId: input.issueId, parentRunId: input.runId, responsibleUserId: "A", cause: "retry" });
|
|
expect(retried.responsibleUserId).toBe("operator");
|
|
});
|
|
|
|
it.each(["malformed", "missing", "unconsumed", "other-run", "other-task", "other-agent", "other-actor", "other-message"])(
|
|
"rejects %s interrupt authority before creating any execution identity", async (fault) => {
|
|
const input = await seedInterrupt();
|
|
if (fault === "malformed" || fault === "missing") {
|
|
await db.update(agentWakeupRequests).set({
|
|
idempotencyKey: `queued-comment-interrupt:${fault === "malformed" ? "not-an-id" : randomUUID()}`,
|
|
}).where(eq(agentWakeupRequests.id, input.wakeupRequestId));
|
|
} else if (fault === "other-actor") {
|
|
await db.update(agentWakeupRequests).set({ requestedByActorId: "someone-else" }).where(eq(agentWakeupRequests.id, input.wakeupRequestId));
|
|
} else {
|
|
const [receipt] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, input.queueId));
|
|
if (fault === "other-agent") {
|
|
const agentId = randomUUID();
|
|
await db.insert(agents).values({ id: agentId, companyId: input.companyId, name: "Other", role: "engineer" });
|
|
await db.update(agentWakeupRequests).set({ agentId }).where(eq(agentWakeupRequests.id, input.queueId));
|
|
} else await db.update(agentWakeupRequests).set(
|
|
fault === "unconsumed" ? { status: "deferred_issue_execution" } :
|
|
fault === "other-run" ? { runId: null } :
|
|
{ payload: { ...receipt.payload, ...(fault === "other-task" ? { issueId: randomUUID() } :
|
|
{ _paperclipWakeContext: { wakeCommentIds: [randomUUID()] } }) } },
|
|
).where(eq(agentWakeupRequests.id, input.queueId));
|
|
}
|
|
await expect(initializeRunIdentity(db, { ...input, responsibleUserId: "A", cause: "dispatch" })).rejects.toThrow("interrupt authority");
|
|
expect(await listRunIdentityContexts(db, input.companyId, input.runId)).toHaveLength(0);
|
|
},
|
|
);
|
|
|
|
it("holds acquisition during uncertain steering, preserves snapshots, and never rewinds on replay", async () => {
|
|
const input = await seed();
|
|
await initializeRunIdentity(db, { ...input, messageIds: [input.messageIds[0]], responsibleUserId: "A", cause: "instruction" });
|
|
const startedUnderA = await captureRunIdentity(db, input);
|
|
const b = await reserveSteeredIdentity(db, { ...input, messageId: input.messageIds[1] });
|
|
expect(b).not.toBeNull();
|
|
await expect(captureRunIdentity(db, input)).rejects.toThrow(/reconciled/);
|
|
await expect(reserveSteeredIdentity(db, { ...input, messageId: input.messageIds[2] })).rejects.toThrow(/reconciled/);
|
|
await db.transaction(async tx => {
|
|
await tx.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, input.runId)).for("update");
|
|
await acceptSteeredIdentity(tx, b!);
|
|
});
|
|
expect((await captureRunIdentity(db, input)).context?.responsibleUserId).toBe("B");
|
|
expect(startedUnderA.context?.responsibleUserId).toBe("A");
|
|
const a = await reserveSteeredIdentity(db, { ...input, messageId: input.messageIds[2] });
|
|
await acceptSteeredIdentity(db, a!);
|
|
await acceptSteeredIdentity(db, b!);
|
|
expect((await captureRunIdentity(db, input)).context?.responsibleUserId).toBe("A");
|
|
});
|
|
it("keeps rejected steering unchanged and preserves the originating identity on retry", async () => {
|
|
const input = await seed();
|
|
await initializeRunIdentity(db, { ...input, messageIds: [], responsibleUserId: "A", cause: "instruction" });
|
|
const b = await reserveSteeredIdentity(db, { ...input, messageId: input.messageIds[1] });
|
|
await rejectSteeredIdentity(db, b!);
|
|
expect((await captureRunIdentity(db, input)).context?.responsibleUserId).toBe("A");
|
|
const runId = randomUUID();
|
|
await db.insert(heartbeatRuns).values({ id: runId, companyId: input.companyId, agentId: input.agentId, status: "running" });
|
|
const retry = await initializeRunIdentity(db, { companyId: input.companyId, runId, parentRunId: input.runId, responsibleUserId: "B", cause: "retry" });
|
|
expect(retry.responsibleUserId).toBe("A");
|
|
expect(retry.parentContextId).toBe((await captureRunIdentity(db, input)).context?.id);
|
|
await expect(captureRunIdentity(db, { ...input, companyId: randomUUID() })).rejects.toThrow();
|
|
await expect(captureRunIdentity(db, { ...input, agentId: randomUUID() })).rejects.toThrow();
|
|
});
|
|
it("preserves an explicitly absent identity through a continuation initiated by another person", async () => {
|
|
const input = await seed();
|
|
const origin = await initializeRunIdentity(db, {
|
|
...input, messageIds: [], responsibleUserId: null, cause: "routine",
|
|
});
|
|
const runId = randomUUID();
|
|
await db.insert(heartbeatRuns).values({
|
|
id: runId, companyId: input.companyId, agentId: input.agentId,
|
|
status: "running", responsibleUserId: "B",
|
|
});
|
|
const continued = await initializeRunIdentity(db, {
|
|
companyId: input.companyId, runId, parentContextId: origin.id,
|
|
responsibleUserId: "B", cause: "retry",
|
|
});
|
|
expect(continued.responsibleUserId).toBeNull();
|
|
const captured = await captureRunIdentity(db, { ...input, runId });
|
|
expect(captured.run.responsibleUserId).toBeNull();
|
|
expect(captured.context?.parentContextId).toBe(origin.id);
|
|
});
|
|
it("recovers an uncertain acknowledgement from the authenticated native event journal", async () => {
|
|
const input = await seed();
|
|
await initializeRunIdentity(db, { ...input, messageIds: [], responsibleUserId: "A", cause: "instruction" });
|
|
const pending = await reserveSteeredIdentity(db, { ...input, messageId: input.messageIds[1] });
|
|
await expect(captureRunIdentity(db, input)).rejects.toThrow(/reconciled/);
|
|
await db.insert(heartbeatRunEvents).values({ companyId: input.companyId, runId: input.runId,
|
|
agentId: input.agentId, seq: 1, eventType: "item.completed", sourceEventId: randomUUID(),
|
|
payload: { prpEvent: { turnId: "turn-1", itemId: `turn-1:steer:${pending!.messageId}`, payload: {kind: "steering_acknowledgement"} } },
|
|
});
|
|
expect((await captureRunIdentity(db, input)).context?.responsibleUserId).toBe("B");
|
|
await db.update(heartbeatRuns).set({status: "succeeded"}).where(eq(heartbeatRuns.id, input.runId));
|
|
expect((await reserveSteeredIdentity(db, { ...input, messageId: input.messageIds[1] }))?.status).toBe("accepted");
|
|
});
|
|
it("preserves an operation's origin through approval and delegation after another person steers", async () => {
|
|
const input = await seed();
|
|
const origin = await initializeRunIdentity(db, { ...input, messageIds: [], responsibleUserId: "A", cause: "instruction" });
|
|
const interactionId = randomUUID();
|
|
await db.insert(issueThreadInteractions).values({ id: interactionId, companyId: input.companyId,
|
|
issueId: input.issueId, kind: "request_confirmation", sourceRunId: input.runId,
|
|
sourceIdentityContextId: origin.id, payload: { prompt: "Continue?" } as never,
|
|
});
|
|
const b = await reserveSteeredIdentity(db, { ...input, messageId: input.messageIds[1] });
|
|
await acceptSteeredIdentity(db, b!);
|
|
for (const approval of [true, false]) {
|
|
const runId = randomUUID();
|
|
await db.insert(heartbeatRuns).values({ id: runId, companyId: input.companyId, agentId: input.agentId, status: "running" });
|
|
const continued = await initializeRunIdentity(db, { companyId: input.companyId, runId, issueId: input.issueId,
|
|
...(approval ? { interactionId } : { parentContextId: origin.id }),
|
|
responsibleUserId: "B", cause: approval ? "approval" : "delegation",
|
|
});
|
|
expect(continued.responsibleUserId).toBe("A");
|
|
expect(continued.parentContextId).toBe(origin.id);
|
|
}
|
|
});
|
|
it("retains continuation and approval attribution after deleting the originating agent and runs", async () => {
|
|
const input = await seed();
|
|
const origin = await initializeRunIdentity(db, { ...input, messageIds: [], responsibleUserId: "A", cause: "instruction" });
|
|
const interactionId = randomUUID();
|
|
await db.insert(issueThreadInteractions).values({ id: interactionId, companyId: input.companyId,
|
|
issueId: input.issueId, kind: "request_confirmation", sourceRunId: input.runId,
|
|
sourceIdentityContextId: origin.id, payload: { prompt: "Continue?" } as never,
|
|
});
|
|
await db.update(issues).set({ originIdentityContextId: origin.id }).where(eq(issues.id, input.issueId));
|
|
await db.delete(heartbeatRuns).where(eq(heartbeatRuns.agentId, input.agentId));
|
|
await db.delete(agents).where(eq(agents.id, input.agentId));
|
|
const agentId = randomUUID();
|
|
await db.insert(agents).values({ id: agentId, companyId: input.companyId, name: "Replacement", role: "engineer", adapterType: "codex_local" });
|
|
const [task] = await db.select().from(issues).where(eq(issues.id, input.issueId));
|
|
expect(task.continuationIdentityContextId).toBe(origin.id);
|
|
for (const source of [{ parentContextId: task.originIdentityContextId }, { parentContextId: task.continuationIdentityContextId }, { interactionId }]) {
|
|
const runId = randomUUID();
|
|
await db.insert(heartbeatRuns).values({ id: runId, companyId: input.companyId, agentId, status: "running" });
|
|
const continued = await initializeRunIdentity(db, { companyId: input.companyId, runId,
|
|
issueId: input.issueId, ...source, responsibleUserId: "B", cause: "continuation" });
|
|
expect(continued.responsibleUserId).toBe("A");
|
|
expect(continued.parentContextId).toBe(origin.id);
|
|
}
|
|
});
|
|
|
|
it("does not deadlock identity initialization against a task mutation that also updates the run", async () => {
|
|
const input = await seed();
|
|
let initialization!: ReturnType<typeof initializeRunIdentity>;
|
|
await db.transaction(async (tx) => {
|
|
await tx.select().from(issues).where(eq(issues.id, input.issueId)).for("update");
|
|
const [backend] = await tx.execute(sql`select pg_backend_pid() as pid`) as unknown as Array<{ pid: number }>;
|
|
initialization = initializeRunIdentity(db, { ...input, messageIds: [], responsibleUserId: "A", cause: "instruction" });
|
|
// Wait until initialization is blocked by this task mutation, rather than
|
|
// relying on timing to decide whether it has acquired its first lock.
|
|
let waiting = false;
|
|
for (let attempt = 0; attempt < 100; attempt++) {
|
|
const [state] = await db.execute(sql`select exists (
|
|
select 1 from pg_stat_activity where ${backend.pid} = any(pg_blocking_pids(pid))
|
|
) as waiting`) as unknown as Array<{ waiting: boolean }>;
|
|
if (state.waiting) { waiting = true; break; }
|
|
await new Promise(resolve => setTimeout(resolve, 10));
|
|
}
|
|
expect(waiting).toBe(true);
|
|
await tx.execute(sql`set local lock_timeout = '1s'`);
|
|
await tx.update(heartbeatRuns).set({ updatedAt: new Date() }).where(eq(heartbeatRuns.id, input.runId));
|
|
});
|
|
await expect(initialization).resolves.toMatchObject({ responsibleUserId: "A" });
|
|
});
|
|
|
|
it("does not turn a company-default fallback into personal consent on continuation", async () => {
|
|
const input = await seed();
|
|
await initializeRunIdentity(db, { ...input, messageIds: [], responsibleUserId: "A", cause: "company_default" });
|
|
const runId = randomUUID();
|
|
await db.insert(heartbeatRuns).values({ id: runId, companyId: input.companyId, agentId: input.agentId, status: "running" });
|
|
const retry = await initializeRunIdentity(db, { companyId: input.companyId, runId, parentRunId: input.runId, responsibleUserId: "A", cause: "retry" });
|
|
expect(retry.cause).toBe("company_default");
|
|
});
|
|
|
|
});
|