mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-20 09:50:48 +01:00
fix(auth): preserve identity across connection request handoffs
Continue accepted connection requests as the verified recipient and retain their original audit parent. Keep declined and automatically closed requests on the source identity. Preserve the latest accepted retry context, ordinary preparation retries, and saved approval origins. Verification: 209 focused local tests passed. Final-head CI passed, Greptile and both Paperclip reviewers rated the change 5/5, and all review threads are resolved. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
2a43fe3e34
commit
875e4d375e
6 files changed
+301
-11
No files matched your search
@@ -10,6 +10,29 @@ Human messages use their stored authenticated author. Queued messages retain the
|
||||
|
||||
Delegated work and interactions persist their originating context. Retries retain the originating run's active context. Background continuations carry their source run; dependency wakes use the task's continuation context, independently of its owner. Scheduled and webhook routines use the routine's responsible person; manual invocations use the caller, and edits preserve the routine's responsible person.
|
||||
|
||||
An accepted connection request continues for the addressed person who connected
|
||||
the account. If an authorized transfer changed that person, the new run records
|
||||
a connection handoff and keeps the original context as its audit parent.
|
||||
Declined or automatically closed requests and ordinary approvals retain their
|
||||
originating identity. Automatic retirement observes the addressee's existing
|
||||
access; its wake does not attribute work to that person or authorize use of that
|
||||
person's accounts. A request transfer alone cannot authorize that identity.
|
||||
Retries keep the previous run's latest accepted context,
|
||||
even when the retry still references the original request. If that context is
|
||||
unavailable, a retry that references a connection request stops instead of replaying
|
||||
the handoff or falling back to another person. An ordinary approval retry
|
||||
restores the approval's saved originating context when the prior run never
|
||||
initialized an identity, including an explicitly absent person. Otherwise,
|
||||
an ordinary retry after a
|
||||
preparation failure retains its existing responsible-user resolution when no
|
||||
identity context was initialized. It prefers the source run's stored person
|
||||
when available and can process newly authorized messages. It does not adopt
|
||||
the task's old continuation identity. A new explicit operator action retains
|
||||
precedence.
|
||||
A transfer grants no
|
||||
credential access; connection selection still checks the new person's grants and
|
||||
policies.
|
||||
|
||||
## Managed GitHub operations
|
||||
|
||||
Executions with managed GitHub configured receive token-free `git` and `gh` launchers. Each launcher invocation resolves one eligible credential from the current run's accepted identity at operation start. A `gh` command's child Git processes inherit that command's captured identity; later steering does not change already-started operations.
|
||||
|
||||
@@ -43,6 +43,8 @@ import { toolAccessPolicyService } from "../services/tool-access-policy.js";
|
||||
import { connectionIntentService } from "../services/connection-intents.js";
|
||||
import { resolveManagedGitHubIdentitySelection } from "../services/git-credentials.js";
|
||||
import { instanceSettingsService } from "../services/instance-settings.js";
|
||||
import { attentionService } from "../services/attention.js";
|
||||
import { initializeRunIdentity } from "../services/run-identity.js";
|
||||
import {
|
||||
getEmbeddedPostgresTestSupport,
|
||||
startEmbeddedPostgresTestDatabase,
|
||||
@@ -913,6 +915,49 @@ describeEmbeddedPostgres("connectionIntentService", () => {
|
||||
await expect(service.search(claims, "notion"))
|
||||
.rejects.toThrow("no longer active");
|
||||
});
|
||||
it("resumes transferred AI authentication with the recipient's account without sharing it with the original person", async () => {
|
||||
const companyId = claims.company_id, agentId = randomUUID(), issueId = randomUUID(), sourceRunId = randomUUID();
|
||||
const recipient = `recipient-${randomUUID()}`;
|
||||
await db.insert(authUsers).values({ id: recipient, name: "Recipient", email: `${recipient}@example.test`, createdAt: new Date(), updatedAt: new Date() });
|
||||
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: recipient, status: "active", membershipRole: "member" });
|
||||
const binding = { provider: "openai", method: "api_key", mode: "responsible_user" } as const;
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "Transferred agent", adapterType: "codex_local", runtimeConfig: { aiConnection: binding } });
|
||||
await db.insert(issues).values({ id: issueId, companyId, title: "Transferred authentication", status: "in_progress", assigneeAgentId: agentId, responsibleUserId: recipient });
|
||||
await db.insert(heartbeatRuns).values({ id: sourceRunId, companyId, agentId, status: "running", contextSnapshot: { issueId } });
|
||||
const origin = await initializeRunIdentity(db, { companyId, runId: sourceRunId, issueId, responsibleUserId: claims.responsible_user_id!, cause: "company_default" });
|
||||
const [app] = await db.insert(toolApplications).values({ companyId, applicationKey: `handoff-${agentId}`, name: "OpenAI", type: "mcp_http", metadata: { sourceTemplateKey: "openai" } }).returning();
|
||||
const [connection] = await db.insert(toolConnections).values({ companyId, applicationId: app!.id, name: "Recipient account", uid: `handoff-${agentId}`, connectionPurpose: "ai", transport: "runtime_auth", authKind: "api_key", credentialPolicy: "per_user", healthStatus: "ok", status: "active", enabled: true, config: { sourceTemplateKey: "openai", ai: { provider: "openai", method: "api_key" } } }).returning();
|
||||
const [grant] = await db.insert(connectionGrants).values({ companyId, connectionId: connection!.id, kind: "user", subjectUserId: recipient, createdByUserId: recipient }).returning();
|
||||
await db.insert(aiProviderDefaults).values({ companyId, userId: recipient, provider: "openai", grantId: grant!.id });
|
||||
const service = connectionIntentService(db);
|
||||
const sourceClaims = { ...claims, sub: agentId, run_id: sourceRunId };
|
||||
const pending = await service.request(sourceClaims, "openai", { purpose: "ai" });
|
||||
expect(pending.state).toBe("needs_user_action");
|
||||
await attentionService(db).transfer(companyId, {
|
||||
sourceKind: "issue_thread_interaction", sourceId: pending.interactionId!, toUserId: recipient,
|
||||
actor: { type: "board", source: "session", userId: claims.responsible_user_id! },
|
||||
});
|
||||
await expect(service.complete(pending.interactionId!, connection!.id, claims.responsible_user_id!)).rejects.toThrow("Only the addressed user");
|
||||
await service.complete(pending.interactionId!, connection!.id, recipient);
|
||||
const wakeup = vi.fn().mockResolvedValue(null);
|
||||
await connectionIntentDeliveryService(db, { wakeup } as never).deliver(pending.interactionId!);
|
||||
expect(wakeup).toHaveBeenCalledTimes(1);
|
||||
const contextSnapshot = wakeup.mock.calls[0][1].contextSnapshot;
|
||||
expect(contextSnapshot).toMatchObject({ interactionId: pending.interactionId, forceFreshSession: true });
|
||||
const continuedRunId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: continuedRunId, companyId, agentId, status: "running", contextSnapshot });
|
||||
const continued = await initializeRunIdentity(db, {
|
||||
companyId, runId: continuedRunId, issueId, interactionId: contextSnapshot.interactionId,
|
||||
responsibleUserId: claims.responsible_user_id!, cause: contextSnapshot.wakeReason,
|
||||
});
|
||||
expect(continued).toMatchObject({ responsibleUserId: recipient, parentContextId: origin.id, cause: "connection_handoff" });
|
||||
expect(await service.request({ ...sourceClaims, run_id: continuedRunId, responsible_user_id: recipient }, "openai", { purpose: "ai" }))
|
||||
.toMatchObject({ state: "ready", connectionId: connection!.id });
|
||||
expect(await service.usableConnectionForAgent({ companyId, agentId, responsibleUserId: claims.responsible_user_id!, serviceSlug: "openai", purpose: "ai" })).toBeNull();
|
||||
const [saved] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, pending.interactionId!));
|
||||
expect(saved).toMatchObject({ sourceIdentityContextId: origin.id, addresseeUserId: recipient, resolvedByUserId: recipient });
|
||||
});
|
||||
|
||||
it("keeps runtime authentication separate from obsolete Anthropic tool requests", async () => {
|
||||
const companyId = claims.company_id;
|
||||
const agentId = randomUUID();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { agentWakeupRequests, agents, companies, applyPendingMigrations, createDb, closeRegisteredClients, heartbeatRuns, heartbeatRunEvents, issueComments, issueThreadInteractions, issues, secretAccessEvents } from "@paperclipai/db";
|
||||
import { agentWakeupRequests, agents, companies, applyPendingMigrations, createDb, closeRegisteredClients, heartbeatRuns, heartbeatRunEvents, issueComments, issueThreadInteractions, issues, runIdentityContexts, secretAccessEvents } from "@paperclipai/db";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { acceptSteeredIdentity, reconcileSteeredIdentity, captureRunIdentity, initializeRunIdentity, listRunIdentityContexts, rejectSteeredIdentity, reserveSteeredIdentity } from "../services/run-identity.js";
|
||||
|
||||
@@ -240,6 +240,172 @@ const support = externalDatabaseUrl ? { supported: true } : await getEmbeddedPos
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["durable", "snapshot"])("continues a connected handoff and retains the latest identity on a %s retry", async (retryKind) => {
|
||||
const input = await seed();
|
||||
const origin = await initializeRunIdentity(db, {
|
||||
...input, messageIds: [], responsibleUserId: "A", cause: "company_default",
|
||||
});
|
||||
const interactionId = randomUUID();
|
||||
await db.insert(issueThreadInteractions).values({
|
||||
id: interactionId, companyId: input.companyId, issueId: input.issueId,
|
||||
kind: "connection_intent", status: "accepted", sourceRunId: input.runId,
|
||||
sourceIdentityContextId: origin.id, addresseeUserId: "B", resolvedByUserId: "B",
|
||||
payload: { version: 1, serviceSlug: "openai", serviceName: "OpenAI", purpose: "ai", requestingAgentId: input.agentId, requestingAgentName: "Shared agent", phase: "requested" },
|
||||
result: { version: 1, outcome: "connected", connectionId: randomUUID() }, resolvedAt: new Date(),
|
||||
});
|
||||
const runId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({
|
||||
id: runId, companyId: input.companyId, agentId: input.agentId,
|
||||
status: "running", contextSnapshot: { issueId: input.issueId, interactionId },
|
||||
});
|
||||
const continued = await initializeRunIdentity(db, {
|
||||
...input, runId, interactionId, messageIds: [], responsibleUserId: "A", cause: "issue_commented",
|
||||
});
|
||||
expect(continued).toMatchObject({
|
||||
responsibleUserId: "B", parentContextId: origin.id, cause: "connection_handoff",
|
||||
});
|
||||
expect((await captureRunIdentity(db, { ...input, runId })).run.responsibleUserId).toBe("B");
|
||||
const [task] = await db.select().from(issues).where(eq(issues.id, input.issueId));
|
||||
expect(task).toMatchObject({ responsibleUserId: "owner", continuationIdentityContextId: continued.id });
|
||||
const [request] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, interactionId));
|
||||
expect(request.sourceIdentityContextId).toBe(origin.id);
|
||||
expect((await listRunIdentityContexts(db, input.companyId, input.runId))[0].responsibleUserId).toBe("A");
|
||||
const retryRunId = randomUUID();
|
||||
const retryFields = retryKind === "durable" ? { retryOfRunId: runId }
|
||||
: { contextSnapshot: { issueId: input.issueId, interactionId, retryOfRunId: runId } };
|
||||
await db.insert(heartbeatRuns).values({ id: retryRunId, companyId: input.companyId, agentId: input.agentId, status: "running", ...retryFields });
|
||||
expect(await initializeRunIdentity(db, {
|
||||
...input, runId: retryRunId, interactionId, messageIds: [], parentRunId: runId, responsibleUserId: "A", cause: "retry",
|
||||
})).toMatchObject({ responsibleUserId: "B", parentContextId: continued.id });
|
||||
const later = await reserveSteeredIdentity(db, { ...input, runId, messageId: input.messageIds[0] });
|
||||
await db.transaction(tx => acceptSteeredIdentity(tx, later!));
|
||||
const steeredRetryRunId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: steeredRetryRunId, companyId: input.companyId, agentId: input.agentId, status: "running", ...retryFields });
|
||||
expect(await initializeRunIdentity(db, {
|
||||
...input, runId: steeredRetryRunId, interactionId, messageIds: [], parentRunId: runId, responsibleUserId: "B", cause: "retry",
|
||||
})).toMatchObject({ responsibleUserId: "A", parentContextId: later!.id });
|
||||
});
|
||||
|
||||
it.each(["durable", "snapshot"].flatMap(retryKind => ["A", null].map(person => ({ retryKind, person }))))(
|
||||
"preserves an approval's saved identity $person after pre-initialization failure ($retryKind)", async ({ retryKind, person }) => {
|
||||
const input = await seed();
|
||||
const origin = await initializeRunIdentity(db, { ...input, messageIds: [], responsibleUserId: person, cause: "instruction" });
|
||||
const interactionId = randomUUID(), failedRunId = randomUUID(), runId = randomUUID();
|
||||
await db.insert(issueThreadInteractions).values({ id: interactionId, companyId: input.companyId, issueId: input.issueId,
|
||||
kind: "request_confirmation", status: "accepted", sourceIdentityContextId: origin.id,
|
||||
addresseeUserId: "B", resolvedByUserId: "B", payload: { prompt: "Continue?" } as never,
|
||||
});
|
||||
// Admission selected the task owner B, but preparation failed before the
|
||||
// approval's originating identity could be restored on that run.
|
||||
await db.insert(heartbeatRuns).values({ id: failedRunId, companyId: input.companyId, agentId: input.agentId,
|
||||
status: "failed", responsibleUserId: "B", contextSnapshot: { issueId: input.issueId, interactionId } });
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId: input.companyId, agentId: input.agentId, status: "running",
|
||||
...(retryKind === "durable" ? { retryOfRunId: failedRunId } : {}),
|
||||
contextSnapshot: { issueId: input.issueId, interactionId, retryOfRunId: failedRunId },
|
||||
});
|
||||
expect(await initializeRunIdentity(db, { ...input, runId, interactionId, messageIds: [],
|
||||
responsibleUserId: "B", cause: "retry" })).toMatchObject({ responsibleUserId: person, parentContextId: origin.id });
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["durable", "snapshot"])("retries a pre-initialization failure as the stored source person (%s)", async (retryKind) => {
|
||||
const input = await seed();
|
||||
await db.update(heartbeatRuns).set({ status: "failed", responsibleUserId: "A" }).where(eq(heartbeatRuns.id, input.runId));
|
||||
// The task's continuation and the caller's fallback can name another person.
|
||||
// Neither replaces the persisted person on this uninitialized source run.
|
||||
const [otherRun] = await db.insert(heartbeatRuns).values({ companyId: input.companyId, agentId: input.agentId, status: "succeeded" }).returning();
|
||||
const other = await initializeRunIdentity(db, { companyId: input.companyId, runId: otherRun.id, responsibleUserId: "B", cause: "instruction" });
|
||||
const runId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId: input.companyId, agentId: input.agentId, status: "running",
|
||||
...(retryKind === "durable" ? { retryOfRunId: input.runId } : {}),
|
||||
contextSnapshot: { issueId: input.issueId, retryOfRunId: input.runId },
|
||||
});
|
||||
expect(await initializeRunIdentity(db, { ...input, runId, messageIds: [], parentContextId: other.id,
|
||||
responsibleUserId: "B", cause: "retry" })).toMatchObject({ responsibleUserId: "A", parentContextId: null });
|
||||
});
|
||||
|
||||
it.each(["durable", "snapshot"].flatMap(retryKind =>
|
||||
["missing-context", "pending-context", "missing-parent"].map(fault => ({ retryKind, fault })),
|
||||
))("refuses a $retryKind retry with $fault instead of replaying a connection handoff", async ({ retryKind, fault }) => {
|
||||
const input = await seed();
|
||||
const origin = await initializeRunIdentity(db, { ...input, messageIds: [], responsibleUserId: "A", cause: "instruction" });
|
||||
const interactionId = randomUUID(), previousRunId = randomUUID(), runId = randomUUID();
|
||||
await db.insert(issueThreadInteractions).values({
|
||||
id: interactionId, companyId: input.companyId, issueId: input.issueId,
|
||||
kind: "connection_intent", status: "accepted", addresseeUserId: "B", resolvedByUserId: "B",
|
||||
sourceIdentityContextId: origin.id, payload: {} as never,
|
||||
result: { version: 1, outcome: "connected", connectionId: randomUUID() },
|
||||
});
|
||||
if (fault !== "missing-parent") {
|
||||
await db.insert(heartbeatRuns).values({ id: previousRunId, companyId: input.companyId, agentId: input.agentId, status: "failed" });
|
||||
if (fault === "pending-context") {
|
||||
const [pending] = await db.insert(runIdentityContexts).values({
|
||||
companyId: input.companyId, runId: previousRunId, revision: 1, responsibleUserId: "C",
|
||||
cause: "instruction", correlationId: "dispatch", status: "pending",
|
||||
}).returning();
|
||||
await db.update(heartbeatRuns).set({ activeIdentityContextId: pending.id }).where(eq(heartbeatRuns.id, previousRunId));
|
||||
}
|
||||
}
|
||||
await db.insert(heartbeatRuns).values({
|
||||
id: runId, companyId: input.companyId, agentId: input.agentId, status: "running",
|
||||
// The durable FK is cleared if the previous run was deleted; the saved
|
||||
// snapshot must still identify this as a retry rather than a new handoff.
|
||||
...(retryKind === "durable" && fault !== "missing-parent" ? { retryOfRunId: previousRunId } : {}),
|
||||
contextSnapshot: { issueId: input.issueId, interactionId, retryOfRunId: previousRunId },
|
||||
});
|
||||
await expect(initializeRunIdentity(db, {
|
||||
...input, runId, interactionId, messageIds: [], parentRunId: previousRunId, responsibleUserId: "B", cause: "retry",
|
||||
})).rejects.toThrow(/execution identity is unavailable/);
|
||||
expect(await listRunIdentityContexts(db, input.companyId, runId)).toEqual([]);
|
||||
});
|
||||
|
||||
it.each(["", " ", true])("ignores an invalid legacy retry marker %j on a new accepted handoff", async (retryOfRunId) => {
|
||||
const input = await seed();
|
||||
const origin = await initializeRunIdentity(db, { ...input, messageIds: [], responsibleUserId: "A", cause: "instruction" });
|
||||
const interactionId = randomUUID(), runId = randomUUID();
|
||||
await db.insert(issueThreadInteractions).values({
|
||||
id: interactionId, companyId: input.companyId, issueId: input.issueId,
|
||||
kind: "connection_intent", status: "accepted", addresseeUserId: "B", resolvedByUserId: "B",
|
||||
sourceIdentityContextId: origin.id, payload: {} as never,
|
||||
result: { version: 1, outcome: "connected", connectionId: randomUUID() },
|
||||
});
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId: input.companyId, agentId: input.agentId,
|
||||
status: "running", contextSnapshot: { issueId: input.issueId, interactionId, retryOfRunId } });
|
||||
expect(await initializeRunIdentity(db, { ...input, runId, interactionId, parentRunId: input.runId,
|
||||
messageIds: [], responsibleUserId: "A", cause: "continuation" })).toMatchObject({
|
||||
responsibleUserId: "B", parentContextId: origin.id, cause: "connection_handoff",
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["approval", "pending", "other-resolver", "unaddressed", "declined", "satisfied", "administrative-expiry", "agent-resolved", "unconnected", "missing-connection"])("retains source identity for a %s request without an accepted connection handoff", async (fault) => {
|
||||
const input = await seed();
|
||||
const origin = await initializeRunIdentity(db, { ...input, messageIds: [], responsibleUserId: "A", cause: "instruction" });
|
||||
const interactionId = randomUUID(), runId = randomUUID();
|
||||
const interaction: typeof issueThreadInteractions.$inferInsert = {
|
||||
id: interactionId, companyId: input.companyId, issueId: input.issueId,
|
||||
kind: "connection_intent", status: "accepted", addresseeUserId: "B", resolvedByUserId: "B",
|
||||
sourceIdentityContextId: origin.id, payload: {} as never,
|
||||
result: { version: 1, outcome: "connected", connectionId: randomUUID() },
|
||||
};
|
||||
if (fault === "approval") { interaction.kind = "request_confirmation"; interaction.result = { version: 1, outcome: "accepted" }; }
|
||||
if (fault === "pending") { interaction.status = "pending"; interaction.resolvedByUserId = null; interaction.result = null; }
|
||||
if (fault === "other-resolver") interaction.resolvedByUserId = "C";
|
||||
if (fault === "unaddressed") interaction.addresseeUserId = null;
|
||||
if (fault === "declined") { interaction.status = "rejected"; interaction.result = { version: 1, outcome: "declined" }; }
|
||||
if (fault === "satisfied" || fault === "administrative-expiry") {
|
||||
interaction.status = "expired"; interaction.resolvedByUserId = null;
|
||||
interaction.result = { version: 1, outcome: "expired", ...(fault === "satisfied" ? { connectionId: randomUUID() } : { reason: "Request withdrawn" }) };
|
||||
}
|
||||
if (fault === "agent-resolved") interaction.resolvedByAgentId = input.agentId;
|
||||
if (fault === "unconnected") interaction.result = { version: 1, outcome: "declined" };
|
||||
if (fault === "missing-connection") interaction.result = { version: 1, outcome: "connected", connectionId: null };
|
||||
await db.insert(issueThreadInteractions).values(interaction);
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId: input.companyId, agentId: input.agentId, status: "running" });
|
||||
expect(await initializeRunIdentity(db, {
|
||||
...input, runId, interactionId, messageIds: [], responsibleUserId: "B", cause: "continuation",
|
||||
})).toMatchObject({ responsibleUserId: "A", parentContextId: origin.id });
|
||||
});
|
||||
|
||||
it.each(["update", "no key update"] as const)("serializes identity initialization behind a task's %s lock", async (lockMode) => {
|
||||
const input = await seed();
|
||||
let initialization!: ReturnType<typeof initializeRunIdentity>;
|
||||
|
||||
@@ -10,6 +10,7 @@ import { activityLog, agentWakeupRequests, agents, approvals, authUsers, compani
|
||||
} from "@paperclipai/db";
|
||||
import { createPostgresRunDispatchAdapter } from "../modules/run-dispatch/adapters/postgres.js";
|
||||
import { connectionIntentDeliveryService } from "../services/connection-intent-delivery.js";
|
||||
import { initializeRunIdentity } from "../services/run-identity.js";
|
||||
import { connectionContinuationPendingResponse, findSatisfiedToolConnection, satisfiedConnectionIntentService } from "../services/satisfied-connection-intents.js";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { materializeNativeInteractionResponses } from "../services/native-runtime/native-interaction-bridge.js";
|
||||
@@ -424,14 +425,28 @@ describePostgres("already available connection requests", () => {
|
||||
} finally { await single.$client.end({ timeout: 1 }); }
|
||||
});
|
||||
|
||||
it("discovers pending cards through the existing delivery worker", async () => {
|
||||
it("discovers pending cards without attributing system closure to the connection owner", async () => {
|
||||
const f = await seed(); const wakeup = vi.fn().mockResolvedValue(null);
|
||||
const [source] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId,
|
||||
status: "succeeded", contextSnapshot: { issueId: f.issueId } }).returning();
|
||||
const origin = await initializeRunIdentity(db, { companyId: f.companyId, runId: source.id,
|
||||
issueId: f.issueId, responsibleUserId: "requester", cause: "instruction" });
|
||||
await db.update(issueThreadInteractions).set({ sourceRunId: source.id, sourceIdentityContextId: origin.id })
|
||||
.where(eq(issueThreadInteractions.id, f.intent.id));
|
||||
const worker = connectionIntentDeliveryService(db, { wakeup });
|
||||
expect(await worker.hasPending()).toBe(true);
|
||||
await worker.sweepPending();
|
||||
expect((await db.select().from(issueThreadInteractions))[0].status).toBe("expired");
|
||||
expect(wakeup).toHaveBeenCalledOnce();
|
||||
expect(wakeup).toHaveBeenCalledWith(f.agentId, expect.objectContaining({ requestedByActorType: "system", idempotencyKey: `connection-intent:${f.intent.id}:expired`, contextSnapshot: expect.objectContaining({ refreshTools: true, responsibleUserId: "connection-owner" }) }));
|
||||
expect(wakeup).toHaveBeenCalledWith(f.agentId, expect.objectContaining({ requestedByActorType: "system", idempotencyKey: `connection-intent:${f.intent.id}:expired`, contextSnapshot: expect.objectContaining({ refreshTools: true, connectionIntentResolution: "existing_connection" }) }));
|
||||
const wake = wakeup.mock.calls[0][1];
|
||||
expect(wake.contextSnapshot).not.toHaveProperty("responsibleUserId");
|
||||
const [continued] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId,
|
||||
status: "running", contextSnapshot: wake.contextSnapshot }).returning();
|
||||
expect(await initializeRunIdentity(db, { companyId: f.companyId, runId: continued.id, issueId: f.issueId,
|
||||
interactionId: f.intent.id, responsibleUserId: "requester", cause: "continuation" })).toMatchObject({
|
||||
responsibleUserId: "requester", parentContextId: origin.id,
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["blocked", "todo", "backlog"] as const)("retires a satisfied card on a %s task without waking its agent", async (status) => {
|
||||
|
||||
@@ -57,8 +57,10 @@ export async function wakeConnectionIntentAfterResolution(
|
||||
mutation: "interaction",
|
||||
wakeReason: "issue_commented",
|
||||
source: "connection_intent.resolved",
|
||||
...(input.actorType === "system" && input.loaded.interaction.addresseeUserId
|
||||
? { responsibleUserId: input.loaded.interaction.addresseeUserId, connectionIntentResolution: "existing_connection" }
|
||||
// Automatic retirement observes access; it does not accept work as the
|
||||
// addressee. Identity initialization retains the request's source context.
|
||||
...(input.actorType === "system"
|
||||
? { connectionIntentResolution: "existing_connection" }
|
||||
: {}),
|
||||
...(interactionResolvedAt
|
||||
? { interactionResolvedAt }
|
||||
|
||||
@@ -77,6 +77,20 @@ export async function explicitOperatorRunIdentity(
|
||||
|
||||
export type RunIdentityContext = typeof runIdentityContexts.$inferSelect;
|
||||
|
||||
/** Only the recipient's completed connection action authorizes a handoff. */
|
||||
function acceptedConnectionRecipient(interaction: Pick<typeof issueThreadInteractions.$inferSelect,
|
||||
"kind" | "status" | "resolvedByAgentId" | "resolvedByUserId" | "addresseeUserId" | "result"
|
||||
> | undefined): string | null {
|
||||
return interaction?.kind === "connection_intent"
|
||||
&& interaction.status === "accepted"
|
||||
&& !interaction.resolvedByAgentId
|
||||
&& interaction.resolvedByUserId === interaction.addresseeUserId
|
||||
&& interaction.result?.outcome === "connected"
|
||||
&& "connectionId" in interaction.result
|
||||
&& typeof interaction.result.connectionId === "string"
|
||||
? interaction.addresseeUserId : null;
|
||||
}
|
||||
|
||||
function assertRunTaskIdentity(run: {
|
||||
nativeIssueId?: string | null;
|
||||
issueId?: string | null;
|
||||
@@ -270,13 +284,19 @@ export async function initializeRunIdentity(
|
||||
retryOrigin = origin.identityContextId;
|
||||
}
|
||||
}
|
||||
const [parent] = input.parentRunId
|
||||
const snapshotRetryRunId = run.contextSnapshot?.retryOfRunId;
|
||||
const retryRunId = run.retryOfRunId ?? (
|
||||
typeof snapshotRetryRunId === "string" ? snapshotRetryRunId.trim() || null : null
|
||||
);
|
||||
const isRetry = retryRunId !== null || retryOrigin !== null;
|
||||
const parentRunId = retryRunId ?? input.parentRunId;
|
||||
const [parent] = parentRunId
|
||||
? await tx
|
||||
.select()
|
||||
.from(heartbeatRuns)
|
||||
.where(
|
||||
and(
|
||||
eq(heartbeatRuns.id, input.parentRunId),
|
||||
eq(heartbeatRuns.id, parentRunId),
|
||||
eq(heartbeatRuns.companyId, input.companyId),
|
||||
),
|
||||
)
|
||||
@@ -294,8 +314,20 @@ export async function initializeRunIdentity(
|
||||
),
|
||||
)
|
||||
: [];
|
||||
const retryContextId = retryOrigin ?? (isRetry ? parent?.activeIdentityContextId : null);
|
||||
// A preparation failure can precede identity initialization. An ordinary
|
||||
// retry retains its stored person when available, or the caller's existing
|
||||
// responsible-user resolution. It never replays a connection handoff.
|
||||
const uninitializedRetryUserId = isRetry && !retryContextId
|
||||
? parent?.responsibleUserId : null;
|
||||
if (!operatorIdentity && isRetry && !retryContextId && interaction?.kind === "connection_intent")
|
||||
throw forbidden("Originating execution identity is unavailable");
|
||||
// An ordinary approval keeps its saved origin when preparation failed
|
||||
// before the previous run accepted an identity. A stored retry context
|
||||
// still wins after initialization or later accepted steering.
|
||||
const parentId = operatorIdentity ? null : (
|
||||
retryOrigin ?? interaction?.sourceIdentityContextId ?? input.parentContextId ?? parent?.activeIdentityContextId
|
||||
retryContextId ?? interaction?.sourceIdentityContextId
|
||||
?? (isRetry ? null : input.parentContextId ?? parent?.activeIdentityContextId)
|
||||
);
|
||||
const [origin] = parentId
|
||||
? await tx
|
||||
@@ -311,13 +343,20 @@ export async function initializeRunIdentity(
|
||||
: [];
|
||||
if (parentId && !origin)
|
||||
throw forbidden("Originating execution identity is unavailable");
|
||||
const connectionRecipient = acceptedConnectionRecipient(interaction);
|
||||
const identity = operatorIdentity
|
||||
? { responsibleUserId: operatorIdentity.actorId, cause: operatorIdentity.cause }
|
||||
: !isRetry && connectionRecipient && origin?.responsibleUserId !== connectionRecipient
|
||||
? { responsibleUserId: connectionRecipient, cause: "connection_handoff" }
|
||||
: {
|
||||
responsibleUserId: origin ? origin.responsibleUserId : uninitializedRetryUserId ?? input.responsibleUserId,
|
||||
cause: origin?.cause === "company_default" ? "company_default" : input.cause,
|
||||
};
|
||||
let current = await append(tx, {
|
||||
companyId: input.companyId,
|
||||
runId: input.runId,
|
||||
responsibleUserId: operatorIdentity?.actorId ?? (origin ? origin.responsibleUserId : input.responsibleUserId),
|
||||
...identity,
|
||||
parentContextId: origin?.id ?? null,
|
||||
cause:
|
||||
operatorIdentity ? operatorIdentity.cause : origin?.cause === "company_default" ? "company_default" : input.cause,
|
||||
correlationId: "dispatch",
|
||||
});
|
||||
const ids = [...new Set(input.messageIds ?? [])];
|
||||
|
||||
Reference in new issue
Block a user