mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-14 00:26:28 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The server has about 1,100 test and helper files in `server/src/__tests__` > - `server/tsconfig.json` excludes that directory, Vitest does not check types, and no script runs the tsconfig in that directory > - So a test can call a function with the wrong arguments and still pass, and no tool reports it > - This gap hid 2,168 real type errors, and some of them hid tests that did not test what they claim > - This pull request fixes all of these errors and adds the directory to the server layers from paperclipai/paperclip#18737 > - The benefit is that a type error in a server test now fails the typecheck, with no baseline and no backlog ## Linked Issues or Issue Description Refs paperclipai/paperclip#18737, which is merged and added the server layers. Refs paperclipai/paperclip#18738, which is merged and checks the test projects outside `pnpm -r`, so it is not a duplicate. Refs paperclipai/paperclip#18137, which records that this directory has no check. **What happened?** No tool checked the types of 1,074 of the 1,101 files in `server/src/__tests__`. I searched `package.json`, the workflows, and all tsconfig files. 27 files are in the program of another tsconfig, and these 27 have 0 errors. 11 of the 27 are in `helpers/maintenance/tsconfig.json`. No script ran that project when I measured this. paperclipai/paperclip#18738 now runs it. **Expected behavior** The server typecheck checks these files, and a type error fails the check. **Steps to reproduce** 1. On the base commit, run `tsc -p server/src/__tests__/tsconfig.json --noEmit`. It reports 6,536 errors and needs 12.3 GiB. 2. Add a type error to any file in `server/src/__tests__`. 3. Run `pnpm --filter @paperclipai/server typecheck`. It passes. **Paperclip version or commit** I measured the error breakdown below on commit `8dfd632452`, with TypeScript 7.0.2. The branch now includes master up to paperclipai/paperclip#18865. **Deployment mode** Not applicable. This issue applies to development and CI. No production source file in the server changes. ### Error breakdown Each row adds one change to the row above. | Step | Total errors | Change | Cause | | --- | --- | --- | --- | | Config as committed | 6,536 | | | | Add `src/types/*.d.ts` | 4,447 | -2,089 | Config. The Express request types were missing. | | Set `rootDir` to the repository root | 2,436 | -2,011 | Config. | | Set `allowImportingTsExtensions` | 2,181 | -255 | Config. Vitest accepts `.ts` imports. | | Add `ES2024.Promise` to `lib` | 2,138 | -43 | Config. Node 24 has `Promise.withResolvers`. | | Set `allowJs` for `.mjs` imports | 2,148 | +10 | Config. It removes 8 `TS7016` errors and shows new real errors. | | Set `declaration` to false | 2,142 | -6 | Config. Tests emit nothing. | | Count only files in `server/src` | 2,058 | -84 | Other packages: 53 Daytona, 29 Runner test, 2 UI. | So 4,478 of the 6,536 errors (69%) came from config or scope, and 2,058 are real type errors in 314 files. The 29 Runner test errors are also real, which gives 2,087 errors. Tests that master added after this measurement had 81 more errors, so this pull request fixes 2,168 errors. This table classifies the first 2,058 errors. | Kind of real error | Errors | | --- | --- | | Wrong argument or assignment type | 1,023 | | Stale or partial fixture objects | 525 | | Property that the type does not have | 317 | | Missing narrowing of null or unknown | 101 | | Implicit any | 60 | | Missing name or module | 16 | | Other | 16 | ### What the type errors hid Most errors were stale fixtures and loose mocks. These errors hid real test problems, and this pull request fixes them: - **A test that never ran.** `instrumentation.test.ts` required `sdk-trace-base`, which is not installed. So 3 span tests were skipped. They now run and pass. - **Assertions that could not fail.** - `issue-thread-interactions-service` used a company ID as an issue ID. - `status-card-evaluation-work` compared `[]` with `[]` in a rollback check. - `slack-conversation-lifecycle` read `item.issueId`, which does not exist. - `email-channels` used a permission key that does not exist. - `heartbeat-project-env` imported `LOW_TRUST_REVIEW_PRESET`, which is not exported. The value was undefined. - **Postgres processes that did not stop.** 11 test files called `stop` on the test database helper. That method does not exist, and the helper method is `cleanup`. - **Arguments that the service ignored.** - `methodKey` is now `connectionMethodKey` in the Daytona, Unikraft, 1Password, and Railway tests. - 108 calls passed `"owner-user"` to a parameter that expects an options object. - 9 chat wizard fixtures passed `managementContext` as `source`, so they ran `existing_app` and not `manifest`. - 2 tests passed a `{ userId }` actor that the function ignores. - Inserts into `environments` passed a `companyId` column that the table does not have. - **Problems in tests that master added during this work.** - `sandbox-creation-operations` read `database.connectionString` when an external test database was set. In that mode `database` is undefined, so the fixture would stop with a TypeError. It now uses the external URL. - `idle-completed-history` set a Dot operation to `dispatched`. That is a Muse status, and the Dot type does not have it. The fixture now uses `admitted`, which is a real in-flight Dot status. ### Possible product problems, not changed These may be real problems in production code or types. I did not change them, because this pull request does not change production behavior: - `decisions-service` `service.create` does not validate the lenient `cancel_issue_tree` input. - `createConnection` ignores `input.connectionPurpose`. - The `createConnection` route schema default stores `{}` for `transportConfig`. - `prepareManagedAiRuntime` accepted the invalid value `mode: "connection"`. - `createBinding` accepts invalid `projectionClass` strings outside class 3. - `ensureManagedProjectWorkspace` forwards an untyped `repoRef` by spread. - `routineVariableSchema.label` is optional, but `RoutineVariable.label` is required. - `ToolRunContext.projectId` may be too strict. - `withdrawInteraction` reads `issue.status`, which its type omits. - `issueService.list` and `reconcileNativeFinalizations` omit fields that they return at runtime. - `createGitHubExternalObjectProvider` handles `tokenProvider: null`, but its type forbids this value. ## What Changed - Fixed the 2,168 type errors. The diff changes 322 test and helper files. - Corrected `server/src/__tests__/tsconfig.json`. Editors and the typecheck now read the same options and report the same errors. - Added three `test-tree` layers to `server/scripts/typecheck-layers.mjs`. They read the server layers as declarations, and any error fails them. A hash of the path selects the shard, so a new file does not move other files. - Added `server/scripts/typecheck-stubs/daytona-sdk.d.ts`. Server tests reach Daytona plugin source, and the root install does not have `@daytonaio/sdk`. - Changed two imports in `ui/src/lib/issue-execution-policy.ts` to use `.js` extensions, because server tests import this file. - Made `declarationsConfig` and `--declarations-only` skip the `test-tree` layers, because these layers emit nothing. Other projects read only the source layers. Added a test for this. - Updated `doc/DEVELOPING.md`. ## Verification Run these commands: ```sh pnpm --filter @paperclipai/server typecheck pnpm exec vitest run server/scripts/typecheck-layers.test.mjs ``` Results on macOS (arm64), Node 24, 16 cores. Each check ran after the merge of paperclipai/paperclip#18738 unless the row says otherwise: | Check | Commit | Result | | --- | --- | --- | | Server typecheck, `PAPERCLIP_TYPECHECK_LOW_MEMORY=1`, all 7 layers | `6e45a08573` | Exit 0, 0 errors, 62 seconds, peak 3.52 GiB | | `node scripts/typecheck-test-projects.mjs --low-memory` | `a3306bd13e` | Exit 0, 0 errors, 42 seconds, peak 3.25 GiB | | The same script with `--reuse-declarations` | `1b878aabc0` | Exit 0, 0 errors | | `typecheck-layers.test.mjs` and `live-recovery-work.test.ts` | `01db5634e4` | 90 passed. These include real compiler runs for a pass, a type error, and an invalid tsconfig. | | `tsconfig.declarations.json` after a full server typecheck | `0fb1e4fb0a` | It references only `below`, `cycle`, and `above`. No generated config names a `tsconfig.layers.json` file. | | Owned runtime test in `idle-completed-history` | `e8f2f448ac` | Passed, with the fix that master later replaced | | `idle-incoming-wake`, `plugin-idle-manager`, and the changed `chat-channels` test | `6e45a08573` | 30 passed | | Runner `native-execution.test.ts` | `eab4dcc1f4` | 114 passed | | The 19 server test files that changed since `eab4dcc1f4`, and `typecheck-layers.test.mjs` | `259737b700` | 4,275 of 4,277 passed. The 2 failures are in `chat-channels` and are in the list of 7 below. | The peak is the largest single process, from `/usr/bin/time -l`. Peaks for the server typecheck were between 3.42 GiB and 3.56 GiB across 8 runs. Peaks for the test projects were 3.25 GiB and 3.37 GiB across 2 runs. I did not measure a cgroup. **Runtime check of the fixes.** Types do not prove that a test still works. So I ran all 309 changed server test files, 11,929 tests, before the rebase onto paperclipai/paperclip#18737: | Result | Tests | Detail | | --- | --- | --- | | Passed | 11,913 | Includes the 2 tests and the 54 `dot-runner` tests that passed in a later run, as described below. | | Failed | 7 | The same 7 tests also fail on the commit before the fixes. | | Skipped | 9 | These tests have their own skip conditions: `sentry` 5, and 1 each in `bundled-plugin-registration`, `customer-success-cloud`, `onepassword-connection`, and `workspace-runtime-https-live-exercise`. | The 7 tests that fail with and without this change, on my machine: - 3 tests in `chat-channels` and `email-channels` stop with `ENOENT` on a `SKILL.md` file. The path is in the parent checkout, above the git worktree that I used, so I expect that the worktree is the cause. I did not prove this. - `workspace-instance-cleanup` compares `/private/var/...` with `/var/...`. This is a macOS symlink difference. - 2 tests in `git-reproducible-managed-checkouts` get `unknown_base_git_files` and expect `unpushed_managed_checkout`. I did not find the cause. - 1 more test in `chat-channels`, `materializes direct external-chat finals once`, gets `undefined`. I did not find the cause. CI is the check for these 7 tests. `ci / verify` passed on `eab4dcc1f4`. Failures during this work: - My fix to `agent-runtime-connector-access` changed an invalid permission key in the setup, but not in the assertion. The runtime check found this. I corrected the assertion, and the file passes. - `heartbeat-plugin-environment` failed one wait in the full run. It passed three times alone, so I think that load caused the failure. It can fail again under load. - `dot-runner` skipped all 54 tests in the full run because `cargo` was not on my `PATH`. It then passed 54 of 54 with the toolchain on the `PATH`. - My first `lib` value removed the default DOM types, and the error count went up by 375. I added the DOM libraries. - My Daytona stub with bare `any` left 48 errors, because generic helpers then inferred `unknown`. I added shapes that return promises. - One fix to `agent-secrets-routes` used `class_3_static_lease`, and the test failed. That class allows only specific paths. I reverted to `unclassified`. - `ci / General tests (server (8/12))` failed on `259737b700` because of the flaky port in `idle-completed-history`. paperclipai/paperclip#18853 fixed this test on master, so this pull request keeps that fix. **Audit of the diff.** I counted these patterns in added and removed lines, to find fixes that only hide an error: | Pattern | Added | Removed | | --- | --- | --- | | `@ts-ignore` | 0 | 0 | | `@ts-expect-error` | 0 | 1 | | `.skip` | 0 | 0 | | `as any` | 9 | 9 | | `: any` | 11 | 2 | | `as never` | 8 | 2 | | `as unknown as` | 35 | 4 | | `Promise<unknown>` | 16 | 5 | | `expect(` | 128 | 113 | No hunk removes more `expect(` calls than it adds. Three removals of test content were intentional, and I checked each one: - `muse-control` removed `signalToken`. Line 1012 already asserts that it is absent. - `merged-pr-confirmation-sweep` removed legacy aliases. Other tests cover them. - `heartbeat-workspace-branch-containment` removed a `finalize` branch that no test row can reach. Some partial fixtures stay unchecked through `as unknown as` and `Promise<unknown>`, mostly in `issue-agent-mutation-ownership-routes` and `issue-comment-reopen-routes`. **Accuracy of the check.** One program over the tree and the three shards reported the same errors at the same positions. Memory, as the peak of the largest process on one thread, was 3.93 GiB for one program and 2.43 GiB for the largest shard. I measured these two values before the fixes. Not run or not proven: - I did not run the full `pnpm test:run`, or a root `pnpm build`. I expect CI to run the full suites. - I did not run the 4 GiB container check, or the full `scripts/typecheck-low-memory.mjs`. The peaks above come from macOS, so they are not a Linux cgroup measurement. - I did not run the UI typecheck after the merges. - `workspace-runtime-https-live-exercise` is skipped, so its `cleanup` fix did not run. ## Risks - **A large diff in test files.** 328 files change. A pull request that edits the same tests can get merge conflicts. New tests on master can also add type errors before this merges. Any such error fails this check and needs a fix here. - **A higher cost for changes to source types.** A change to a type can add errors in test files that the author did not touch. The author must then fix them. This is the purpose of the check, but it is new work. - **Changed test behavior.** Some tests now run paths that they did not run before, such as the 9 chat wizard fixtures and the 3 span tests. They pass here, but they can be more sensitive to timing or to the environment. - **The Daytona stub can go stale.** The stub is written by hand. If the plugin uses a new SDK member, the typecheck reports an error until someone updates the stub. - **The release path.** `release-verify.yml` and `scripts/release.sh` run `pnpm -r typecheck`, so they now run this check. - **The tsconfig change.** The test transform reads `server/src/__tests__/tsconfig.json`. The options that I changed are for type checks, and the runs above passed. - **A gap that remains.** Tsconfigs in `packages/paperclip-runner` and in most sandbox provider plugins exclude `*.test.ts`. This check does not read most of those test files, so they can still drift. That work is separate from this pull request. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used Anthropic Claude Opus 5.5 (`claude-opus-5-5`) through Claude Code, with reasoning, tool use, code execution, and subagents. The runtime does not show the context window size. ## 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 #` / `Refs #` 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 - [ ] I have run tests locally and they pass (7 tests fail locally, with and without this change. See Verification.) - [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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1398 lines
53 KiB
TypeScript
1398 lines
53 KiB
TypeScript
import { externalConversationSettlementWork } from "../../services/external-conversation-settlement-work.js";
|
|
import { nativeStatusReassessmentWork } from "../../services/native-runtime/native-status-reassessment-work.js";
|
|
import { nativeReviewResponseWork } from "../../services/native-runtime/native-review-response-work.js";
|
|
import { nativeResponsePresentationWork } from "../../services/native-runtime/native-response-presentation-work.js";
|
|
import { DELIVERY_QUEUES } from "../../services/delivery-work-notifications.js";
|
|
import { idleWorkSnapshot } from "../../services/task-admission.js";
|
|
import { createDeliveryWorkCoordinator } from "../../services/delivery-work-coordinator.js";
|
|
import { resolveExternalTestDatabaseUrl } from "../helpers/external-test-database.js";
|
|
import { Readable } from "node:stream";
|
|
import type { StorageService } from "../../storage/types.js";
|
|
import { createHash, randomUUID } from "node:crypto";
|
|
import { mkdtemp, rm, readFile } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
import {
|
|
beforeAll,
|
|
afterAll,
|
|
beforeEach,
|
|
afterEach,
|
|
describe,
|
|
it,
|
|
expect,
|
|
vi,
|
|
} from "vitest";
|
|
import {
|
|
TypedEventStream,
|
|
type LiveEvent,
|
|
type GrpcAdvancedIMessage,
|
|
} from "@photon-ai/advanced-imessage";
|
|
import { and, eq, sql } from "drizzle-orm";
|
|
import {
|
|
applyPendingMigrations,
|
|
subscribeDatabaseWork,
|
|
createDb,
|
|
companies,
|
|
agents,
|
|
authUsers,
|
|
companyMemberships,
|
|
principalPermissionGrants,
|
|
chatEndpointLeases,
|
|
chatSdkState,
|
|
chatEndpoints,
|
|
chatConversations,
|
|
chatDeliveries,
|
|
chatMessageLinks,
|
|
chatActions,
|
|
chatPublications,
|
|
heartbeatRuns,
|
|
agentWakeupRequests,
|
|
issueComments,
|
|
issues,
|
|
activityLog,
|
|
issueQuestionResponseDeliveries,
|
|
chatIdentityLinks,
|
|
chatEndpointResources,
|
|
issueAttachments,
|
|
assets,
|
|
toolConnections,
|
|
} from "@paperclipai/db";
|
|
import { startEmbeddedPostgresTestDatabase } from "../helpers/embedded-postgres.js";
|
|
import {
|
|
chatChannelService,
|
|
type ChatChannelService,
|
|
} from "../../services/chat-channels.js";
|
|
import { ChatSdkRuntime } from "../../services/chat-sdk-runtime.js";
|
|
import { issueService } from "../../services/issues.js";
|
|
import { subscribeCompanyLiveEvents } from "../../services/live-events.js";
|
|
import { issueThreadInteractionService } from "../../services/issue-thread-interactions.js";
|
|
import { resolveExternalChatQuestionResponse } from "../../services/native-runtime/external-chat-question-response.js";
|
|
import { resolveChatRunPresentationAuthorizationReason } from "../../services/chat-run-publications.js";
|
|
import { PhotonChatAdapter } from "../../services/photon/adapter.js";
|
|
import { PhotonCloudClient, PhotonError } from "../../services/photon/cloud.js";
|
|
import { photonFixture, photonEvent as livePhotonEvent, photonChat, stream } from "./fixture.js";
|
|
|
|
// The fixture always builds a message event. Its declared return type is the wider LiveEvent.
|
|
const photonEvent = (...args: Parameters<typeof livePhotonEvent>) =>
|
|
livePhotonEvent(...args) as Extract<LiveEvent, { message: unknown }>;
|
|
|
|
function idleStream<T>(): TypedEventStream<T> {
|
|
let close!: () => void;
|
|
const done = new Promise<void>((resolve) => {
|
|
close = resolve;
|
|
});
|
|
return new TypedEventStream(
|
|
(async function* () {
|
|
await done;
|
|
})(),
|
|
async () => close(),
|
|
);
|
|
}
|
|
describe("iMessage Photon channel control plane", () => {
|
|
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
|
|
let db: ReturnType<typeof createDb>;
|
|
let secrets: string;
|
|
const oldKey = process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE;
|
|
const services: ChatChannelService[] = [];
|
|
const coordinators: ReturnType<typeof createDeliveryWorkCoordinator>[] = [];
|
|
const companyIds: string[] = [];
|
|
beforeAll(async () => {
|
|
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_PHOTON_TEST_DATABASE_URL");
|
|
if (!external) database = await startEmbeddedPostgresTestDatabase("paperclip-photon-");
|
|
if (external) await applyPendingMigrations(external);
|
|
db = createDb(external ?? database!.connectionString);
|
|
secrets = await mkdtemp(path.join(tmpdir(), "photon-secrets-"));
|
|
process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE = path.join(
|
|
secrets,
|
|
"master.key",
|
|
);
|
|
}, 30_000);
|
|
afterEach(async () => {
|
|
await Promise.all(coordinators.splice(0).map(coordinator => coordinator.stop()));
|
|
await Promise.all(services.splice(0).map((service) => service.shutdown()));
|
|
for (const id of companyIds.splice(0))
|
|
await db
|
|
.update(chatEndpoints)
|
|
.set({ status: "archived" })
|
|
.where(eq(chatEndpoints.companyId, id));
|
|
vi.restoreAllMocks();
|
|
});
|
|
afterAll(async () => {
|
|
await db?.$client.end({ timeout: 1 });
|
|
await database?.cleanup();
|
|
if (secrets) await rm(secrets, { recursive: true, force: true });
|
|
if (oldKey === undefined)
|
|
delete process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE;
|
|
else process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE = oldKey;
|
|
});
|
|
async function setup(shared = false) {
|
|
const companyId = randomUUID(),
|
|
agentId = randomUUID(),
|
|
userId = randomUUID();
|
|
companyIds.push(companyId);
|
|
await db.insert(companies).values({
|
|
id: companyId,
|
|
name: "Photon test",
|
|
issuePrefix: `P${companyId.replaceAll("-", "").slice(0, 7).toUpperCase()}`,
|
|
requireBoardApprovalForNewAgents: false,
|
|
});
|
|
await db.insert(agents).values({
|
|
id: agentId,
|
|
companyId,
|
|
name: "Photon Agent",
|
|
role: "engineer",
|
|
status: "idle",
|
|
adapterType: "paperclip_runner",
|
|
adapterConfig: {},
|
|
runtimeConfig: {},
|
|
permissions: {},
|
|
});
|
|
await db.insert(authUsers).values({
|
|
id: userId,
|
|
name: "Operator",
|
|
email: `${userId}@example.com`,
|
|
emailVerified: true,
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
});
|
|
await db.insert(companyMemberships).values({
|
|
companyId,
|
|
principalType: "user",
|
|
principalId: userId,
|
|
status: "active",
|
|
membershipRole: "operator",
|
|
});
|
|
await db.insert(principalPermissionGrants).values({
|
|
companyId,
|
|
principalType: "user",
|
|
principalId: userId,
|
|
permissionKey: "tools:manage_connections",
|
|
grantedByUserId: userId,
|
|
});
|
|
const f = photonFixture();
|
|
const allocation = shared ? {
|
|
inspection: { projectId: "project", projectName: "Test shared", allocation: "shared" as const, eligible: true, lines: [] },
|
|
tokens: new Map<string, string>(), sharedToken: "shared-project-token", expiresIn: 300,
|
|
} : await f.cloud.allocation("project", "secret");
|
|
vi.spyOn(PhotonCloudClient.prototype, "allocation").mockResolvedValue(
|
|
allocation,
|
|
);
|
|
for (const resource of [
|
|
f.client.messages,
|
|
f.client.chats,
|
|
f.client.groups,
|
|
f.client.polls,
|
|
])
|
|
resource.subscribeEvents.mockImplementation(() => idleStream());
|
|
vi.spyOn(PhotonChatAdapter.prototype, "initialize").mockImplementation(
|
|
async function (this: PhotonChatAdapter) {
|
|
await this.client.close();
|
|
Object.defineProperty(this, "client", {
|
|
value: f.client as unknown as GrpcAdvancedIMessage,
|
|
});
|
|
await this.authentication.token();
|
|
},
|
|
);
|
|
vi.spyOn(PhotonChatAdapter.prototype, "recoveryStream").mockImplementation(
|
|
() => stream([{ type: "catchup.complete", headSequence: 0 }]),
|
|
);
|
|
const chats = new Map([[f.chat.guid, f.chat]]);
|
|
f.client.chats.get.mockImplementation(async (guid?: string) => {
|
|
const chat = chats.get(guid ?? "");
|
|
if (!chat) throw new Error("Missing chat");
|
|
return chat;
|
|
});
|
|
let runtime = new ChatSdkRuntime();
|
|
let replacement = vi.spyOn(runtime, "replaceEndpoint");
|
|
const wakeup = vi.fn(async (assignedAgentId, opts) => {
|
|
const request = opts.durableChatRequest;
|
|
if (request)
|
|
await db.transaction(async (tx) => {
|
|
await request.authorize(tx);
|
|
await tx
|
|
.insert(agentWakeupRequests)
|
|
.values({
|
|
id: request.id,
|
|
companyId: request.companyId,
|
|
agentId: assignedAgentId,
|
|
source: opts.source,
|
|
triggerDetail: opts.triggerDetail,
|
|
reason: opts.reason,
|
|
payload: opts.payload,
|
|
requestedByActorType: opts.requestedByActorType,
|
|
requestedByActorId: opts.requestedByActorId,
|
|
idempotencyKey: request.idempotencyKey,
|
|
requestedAt: request.requestedAt,
|
|
status: "queued",
|
|
})
|
|
.onConflictDoNothing();
|
|
});
|
|
return { accepted: true };
|
|
});
|
|
const objects = new Map<string, Buffer>();
|
|
const storage: StorageService = {
|
|
provider: "local_disk",
|
|
putFile: async (input) => {
|
|
const objectKey = `${input.namespace}/${randomUUID()}`;
|
|
if (!Buffer.isBuffer(input.body)) throw new Error("Expected a buffered attachment body");
|
|
objects.set(objectKey, input.body);
|
|
return {
|
|
provider: "local_disk",
|
|
objectKey,
|
|
contentType: input.contentType,
|
|
byteSize: input.body.length,
|
|
sha256: createHash("sha256").update(input.body).digest("hex"),
|
|
originalFilename: input.originalFilename,
|
|
};
|
|
},
|
|
getObject: async (_company, key) => ({
|
|
stream: Readable.from([objects.get(key)!]),
|
|
contentLength: objects.get(key)!.length,
|
|
}),
|
|
headObject: async (_company, key) => ({ exists: objects.has(key) }),
|
|
deleteObject: async (_company, key) => {
|
|
objects.delete(key);
|
|
},
|
|
};
|
|
const inboundMessages = new Map();
|
|
f.client.messages.get.mockImplementation(
|
|
async (id) =>
|
|
inboundMessages.get(id) ??
|
|
[...f.receipts.values()].find((message) => message.guid === id),
|
|
);
|
|
const makeService = () => {
|
|
const service = chatChannelService(db, {
|
|
runtime,
|
|
publicBaseUrl: "https://paperclip.example",
|
|
heartbeat: { wakeup },
|
|
storage,
|
|
scheduleDeferredWork: () => {},
|
|
});
|
|
services.push(service);
|
|
return service;
|
|
};
|
|
let service = makeService();
|
|
const endpoint = await service.create(
|
|
companyId,
|
|
{ provider: "imessage-photon", assignedAgentId: agentId },
|
|
userId,
|
|
);
|
|
await service.configure(
|
|
endpoint.id,
|
|
{
|
|
action: "configure",
|
|
photon: shared ? { allocation: "shared", projectId: "project" } : { projectId: "project", lineId: "line" },
|
|
credentials: { projectSecret: "secret" },
|
|
},
|
|
userId,
|
|
);
|
|
const callbacks = () => replacement.mock.calls.at(-1)![0].callbacks;
|
|
const deliver = async (event: LiveEvent) => {
|
|
if (event.type === "message.received")
|
|
inboundMessages.set(event.message.guid, event.message);
|
|
await callbacks().onPhotonEvent!(event);
|
|
await service.processPendingDeliveries();
|
|
};
|
|
const link = async (address = "+15555550101", person = userId) => {
|
|
const principal = (await service.listPrincipals(endpoint.id)).find(
|
|
(entry) => entry.externalLabel === address,
|
|
)!;
|
|
expect(principal).toBeDefined();
|
|
const intent = await service.createLinkIntent(
|
|
endpoint.id,
|
|
principal.principalId,
|
|
1800,
|
|
);
|
|
await service.confirmIdentityLink(
|
|
new URL(intent.confirmationUrl).searchParams.get("token")!,
|
|
person,
|
|
);
|
|
};
|
|
const start = async () => {
|
|
await deliver(photonEvent(1));
|
|
expect(await service.listConversations(endpoint.id)).toHaveLength(0);
|
|
await link();
|
|
await deliver(photonEvent(2));
|
|
const [conversation] = await service.listConversations(endpoint.id);
|
|
expect(conversation).toBeDefined();
|
|
return conversation;
|
|
};
|
|
const qualify = async () => {
|
|
const [conversation] = await service.listConversations(endpoint.id);
|
|
const [source] = await db
|
|
.select()
|
|
.from(chatMessageLinks)
|
|
.where(
|
|
and(
|
|
eq(chatMessageLinks.endpointId, endpoint.id),
|
|
eq(chatMessageLinks.direction, "inbound"),
|
|
),
|
|
)
|
|
.orderBy(sql`${chatMessageLinks.createdAt} desc`)
|
|
.limit(1);
|
|
const runId = randomUUID();
|
|
await db.insert(heartbeatRuns).values({
|
|
id: runId,
|
|
companyId,
|
|
agentId,
|
|
status: "succeeded",
|
|
contextSnapshot: {
|
|
issueId: conversation.issueId,
|
|
source: "chat:imessage-photon",
|
|
wakeCommentId: source.commentId,
|
|
wakeCommentIds: [source.commentId],
|
|
},
|
|
});
|
|
const authorizationReason =
|
|
await resolveChatRunPresentationAuthorizationReason(db, {
|
|
companyId,
|
|
issueId: conversation.issueId,
|
|
runId,
|
|
});
|
|
expect(authorizationReason).toBe("allow_chat_run_presentation");
|
|
await issueService(db).addComment(
|
|
conversation.issueId,
|
|
"Agent reply through Photon",
|
|
{ agentId, runId },
|
|
{ authorType: "agent", authorizationReason },
|
|
);
|
|
await service.processPendingPublications();
|
|
await service.test(endpoint.id);
|
|
expect((await service.get(endpoint.id)).status).toBe("active");
|
|
};
|
|
return {
|
|
f,
|
|
companyId,
|
|
agentId,
|
|
userId,
|
|
endpoint,
|
|
service,
|
|
callbacks,
|
|
deliver,
|
|
link,
|
|
start,
|
|
qualify,
|
|
chats,
|
|
wakeup,
|
|
restart: async () => {
|
|
await service.shutdown();
|
|
runtime = new ChatSdkRuntime();
|
|
replacement = vi.spyOn(runtime, "replaceEndpoint");
|
|
service = makeService();
|
|
await service.reconcileProviderRuntimes();
|
|
return service;
|
|
},
|
|
};
|
|
}
|
|
it.each([DELIVERY_QUEUES.nativeResponsePresentation, DELIVERY_QUEUES.nativeReviewResponse, DELIVERY_QUEUES.nativeStatusReassessment, DELIVERY_QUEUES.externalConversationSettlement])(
|
|
"keeps repeated active Photon ownership assertions out of %s reconstruction and wakes once on recovery", async queue => {
|
|
const t = await setup();
|
|
await t.start();
|
|
await t.qualify();
|
|
const errors: unknown[] = [];
|
|
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: error => errors.push(error) });
|
|
coordinators.push(coordinator);
|
|
const work = queue === DELIVERY_QUEUES.externalConversationSettlement ? externalConversationSettlementWork(db)
|
|
: queue === DELIVERY_QUEUES.nativeResponsePresentation ? nativeResponsePresentationWork(db)
|
|
: queue === DELIVERY_QUEUES.nativeReviewResponse ? nativeReviewResponseWork(db) : nativeStatusReassessmentWork(db);
|
|
const worker = work.register(coordinator, () => true);
|
|
const debug = db.$client.options.debug;
|
|
const hints: unknown[] = [];
|
|
const queries: string[] = [];
|
|
const unsubscribe = subscribeDatabaseWork(db, queue, (event, values) => {
|
|
if (event === "settled") for (const value of values ?? []) {
|
|
const scope = JSON.parse(value);
|
|
if (scope.companyId === t.companyId) hints.push(scope);
|
|
}
|
|
});
|
|
try {
|
|
await worker.ready;
|
|
await expect.poll(() => ({ active: idleWorkSnapshot().active, next: coordinator.nextWakeAt() }), { timeout: 5000 })
|
|
.toEqual({ active: 0, next: null });
|
|
db.$client.options.debug = (_connection, query) => {
|
|
if (query.startsWith("select") && (queue === DELIVERY_QUEUES.externalConversationSettlement
|
|
? query.includes("exists (select 1 from chat_conversations c") : query.includes("native_run_finalizations"))) queries.push(query);
|
|
};
|
|
const assertOwned = t.callbacks().onPhotonAssertOwned!;
|
|
for (let i = 0; i < 5; i++) await assertOwned();
|
|
expect(hints).toEqual([]);
|
|
expect(queries).toEqual([]);
|
|
await db.update(chatEndpoints).set({ status: "attention", healthMessage: "Recovering transport" })
|
|
.where(eq(chatEndpoints.id, t.endpoint.id));
|
|
await Promise.all([assertOwned(), assertOwned(), assertOwned()]);
|
|
await expect.poll(() => ({ active: idleWorkSnapshot().active, next: coordinator.nextWakeAt() }), { timeout: 5000 })
|
|
.toEqual({ active: 0, next: null });
|
|
expect(hints).toEqual([{ companyId: t.companyId }]);
|
|
expect(queries).toHaveLength(1);
|
|
expect((await t.service.get(t.endpoint.id)).status).toBe("active");
|
|
hints.length = 0;
|
|
queries.length = 0;
|
|
for (let i = 0; i < 5; i++) await assertOwned();
|
|
expect(hints).toEqual([]);
|
|
expect(queries).toEqual([]);
|
|
expect(errors).toEqual([]);
|
|
} finally { unsubscribe(); db.$client.options.debug = debug; if ("stop" in worker) worker.stop(); }
|
|
});
|
|
|
|
it("recovers a Photon transport loss through the receiver worker and cancels fatal recovery", async () => {
|
|
const t = await setup();
|
|
const onError = vi.fn();
|
|
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError });
|
|
coordinators.push(coordinator);
|
|
await t.service.registerReceiverWork(coordinator, () => true).ready;
|
|
const first = t.service.runtime.get(t.endpoint.id);
|
|
expect(first).not.toBeNull();
|
|
await t.callbacks().onPhotonFailure!(new Error("transport interrupted"));
|
|
await vi.waitFor(() => {
|
|
const current = t.service.runtime.get(t.endpoint.id);
|
|
expect(current).not.toBeNull(); expect(current).not.toBe(first);
|
|
}, { timeout: 5000 });
|
|
await vi.waitFor(() => expect(coordinator.nextWakeAt()).toBeNull(), { timeout: 5000 });
|
|
await t.callbacks().onPhotonFailure!(new PhotonError("credentials", "Rejected credentials"));
|
|
await vi.waitFor(() => expect(t.service.runtime.get(t.endpoint.id)).toBeNull(), { timeout: 5000 });
|
|
await vi.waitFor(() => expect(coordinator.nextWakeAt()).toBeNull(), { timeout: 5000 });
|
|
expect(await db.select().from(toolConnections).where(eq(toolConnections.id, t.endpoint.connectionId)))
|
|
.toEqual([expect.objectContaining({ enabled: false })]);
|
|
expect(onError).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("keeps publication authentication failures stopped across receiver reconciliation and restart", async () => {
|
|
const t = await setup();
|
|
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: () => {} });
|
|
coordinators.push(coordinator);
|
|
await t.service.registerReceiverWork(coordinator, () => true).ready;
|
|
const conversation = await t.start();
|
|
await t.qualify();
|
|
const callbacks = t.callbacks();
|
|
vi.spyOn(PhotonChatAdapter.prototype, "publish").mockRejectedValueOnce(new PhotonError("credentials", "Rejected credentials"));
|
|
const comment = await issueService(db).addComment(conversation.issueId!, "Response with rejected credentials", { userId: t.userId }, { authorType: "user" });
|
|
await t.service.publishComment(t.endpoint.id, conversation.id, comment.id);
|
|
expect(await db.select().from(chatPublications).where(eq(chatPublications.commentId, comment.id))).toEqual([
|
|
expect.objectContaining({ state: "failed", attempts: 1, nextAttemptAt: null }),
|
|
]);
|
|
expect(await t.service.get(t.endpoint.id)).toMatchObject({ status: "attention" });
|
|
expect(await db.select().from(toolConnections).where(eq(toolConnections.id, t.endpoint.connectionId))).toEqual([
|
|
expect.objectContaining({ status: "active", enabled: true, healthStatus: "failed" }),
|
|
]);
|
|
await expect(callbacks.onPhotonAssertOwned!()).rejects.toThrow();
|
|
await vi.waitFor(() => expect(t.service.runtime.get(t.endpoint.id)).toBeFalsy(), { timeout: 5000 });
|
|
await coordinator.stop();
|
|
const restarted = await t.restart();
|
|
expect(restarted.runtime.get(t.endpoint.id)).toBeFalsy();
|
|
expect(await restarted.get(t.endpoint.id)).toMatchObject({ status: "attention" });
|
|
});
|
|
|
|
it("supports shared project DMs while rejecting groups, duplicate ownership and allocation changes", async () => {
|
|
const t = await setup(true);
|
|
const snapshot = await t.service.get(t.endpoint.id);
|
|
expect(snapshot).toMatchObject({ photonAllocation: "shared", botExternalId: "photon-project:project", botUsername: null, allowGroupChats: false });
|
|
await expect(t.service.update(t.endpoint.id, { allowGroupChats: true }, t.userId)).rejects.toThrow(/direct messages only/);
|
|
const group = photonChat("iMessage;+;shared-group", true);
|
|
t.chats.set(group.guid, group);
|
|
await t.deliver(photonEvent(10, group));
|
|
expect(await t.service.listResources(t.endpoint.id)).toHaveLength(0);
|
|
expect(t.wakeup).not.toHaveBeenCalled();
|
|
const conversation = await t.start();
|
|
expect(conversation.externalThreadId).toContain("shared-");
|
|
await t.qualify();
|
|
expect(t.f.client.groups.subscribeEvents).not.toHaveBeenCalled();
|
|
const duplicate = await t.service.create(t.companyId, { provider: "imessage-photon", assignedAgentId: t.agentId }, t.userId);
|
|
expect(await t.service.inspectPhoton(duplicate.id, {projectId: "project", projectSecret: "secret"})).toMatchObject({ allocation: "shared", eligible: false });
|
|
await expect(t.service.configure(duplicate.id, { action: "configure", photon: { allocation: "shared", projectId: "project" }, credentials: { projectSecret: "secret" } }, t.userId)).rejects.toThrow(/already/);
|
|
const restarted = await t.restart();
|
|
expect((await restarted.listConversations(t.endpoint.id))[0].id).toBe(conversation.id);
|
|
await expect(restarted.configure(t.endpoint.id, { action: "reconnect", photon: { projectId: "project", lineId: "line" }, credentials: { projectSecret: "secret" } }, t.userId)).rejects.toThrow(/allocation|identity|different/);
|
|
});
|
|
it("distinguishes setup validation from provider outages without replacing credentials", async () => {
|
|
const t = await setup();
|
|
const allocation = vi.spyOn(PhotonCloudClient.prototype, "allocation");
|
|
for (const [code, status] of [
|
|
["credentials", 422],
|
|
["line_unavailable", 422],
|
|
["quota", 429],
|
|
["network", 503],
|
|
["invalid_response", 502],
|
|
] as const) {
|
|
allocation.mockRejectedValueOnce(new PhotonError(code, `Safe Photon ${code} message`));
|
|
await expect(t.service.inspectPhoton(t.endpoint.id, {
|
|
projectId: "project", projectSecret: "replacement",
|
|
})).rejects.toMatchObject({ status, details: { code: `photon_${code}` } });
|
|
allocation.mockRejectedValueOnce(new PhotonError(code, `Safe Photon ${code} message`));
|
|
await expect(t.service.configure(t.endpoint.id, {
|
|
action: "reconnect", credentials: { projectSecret: "replacement" },
|
|
}, t.userId)).rejects.toMatchObject({ status, details: { code: `photon_${code}` } });
|
|
}
|
|
await t.start();
|
|
await t.qualify();
|
|
});
|
|
it("requires a fresh linked message and an agent reply before setup completes", async () => {
|
|
const t = await setup();
|
|
await expect(t.service.test(t.endpoint.id)).rejects.toThrow("test message");
|
|
await t.start();
|
|
await expect(t.service.test(t.endpoint.id)).rejects.toThrow();
|
|
expect(t.wakeup).toHaveBeenCalledTimes(1);
|
|
await t.qualify();
|
|
expect(
|
|
t.f.client.messages.sendText.mock.calls.find((call) =>
|
|
call[1].includes("Agent reply"),
|
|
)?.[2],
|
|
).toMatchObject({ replyTo: "message-2" });
|
|
const secretSafe = JSON.stringify(await t.service.get(t.endpoint.id));
|
|
expect(secretSafe).not.toContain("private-line-token");
|
|
expect(secretSafe).not.toContain('"projectSecret"');
|
|
}, 30_000);
|
|
it("preserves DM identity across restart, ignores echoes, and reserves a paused number", async () => {
|
|
const t = await setup();
|
|
const first = await t.start();
|
|
await t.qualify();
|
|
let service = await t.restart();
|
|
await t.deliver(photonEvent(3));
|
|
expect((await service.listConversations(t.endpoint.id))[0].issueId).toBe(
|
|
first.issueId,
|
|
);
|
|
const echo = photonEvent(4);
|
|
await t.deliver({ ...echo, isFromMe: true } as LiveEvent);
|
|
expect(t.wakeup).toHaveBeenCalledTimes(2);
|
|
await service.configure(t.endpoint.id, { action: "pause" }, t.userId);
|
|
const duplicate = await service.create(
|
|
t.companyId,
|
|
{ provider: "imessage-photon", assignedAgentId: t.agentId },
|
|
t.userId,
|
|
);
|
|
await expect(
|
|
service.configure(
|
|
duplicate.id,
|
|
{
|
|
action: "configure",
|
|
photon: { projectId: "project", lineId: "line" },
|
|
credentials: { projectSecret: "secret" },
|
|
},
|
|
t.userId,
|
|
),
|
|
).rejects.toThrow(/already|another/);
|
|
await service.configure(t.endpoint.id, { action: "resume" }, t.userId);
|
|
expect((await service.get(t.endpoint.id)).status).toBe("active");
|
|
await service.configure(t.endpoint.id, { action: "remove" }, t.userId);
|
|
expect((await service.get(t.endpoint.id)).status).toBe("archived");
|
|
}, 30_000);
|
|
it("discovers groups disabled and admits only fresh messages after enablement", async () => {
|
|
const t = await setup();
|
|
await t.start();
|
|
await t.qualify();
|
|
const group = photonChat("iMessage;+;group", true);
|
|
t.chats.set(group.guid, group);
|
|
await t.deliver(photonEvent(3, group, "Old disabled request"));
|
|
expect(await t.service.listConversations(t.endpoint.id)).toHaveLength(1);
|
|
const resources = await t.service.listResources(t.endpoint.id);
|
|
const resource = resources.find((row) => row.type === "group_chat")!;
|
|
expect(resource.enabled).toBe(false);
|
|
await t.service.replaceResources(
|
|
t.endpoint.id,
|
|
resources.map((row) => ({
|
|
id: row.id,
|
|
enabled: row.id === resource.id || row.enabled,
|
|
})),
|
|
t.userId,
|
|
);
|
|
await t.service.processPendingDeliveries();
|
|
expect(await t.service.listConversations(t.endpoint.id)).toHaveLength(1);
|
|
await t.deliver(photonEvent(4, group, "Fresh group request"));
|
|
expect(await t.service.listConversations(t.endpoint.id)).toHaveLength(2);
|
|
const conversation = (await t.service.listConversations(t.endpoint.id)).find((row) => !row.isDirectMessage)!;
|
|
await issueService(db).update(conversation.issueId, { status: "done", actorUserId: t.userId });
|
|
await t.deliver(photonEvent(5, group, "A group follow-up after completion"));
|
|
const conversations = await t.service.listConversations(t.endpoint.id);
|
|
expect(conversations).toHaveLength(2);
|
|
expect(conversations.find((row) => !row.isDirectMessage)).toMatchObject({ id: conversation.id, issueId: conversation.issueId, state: "active" });
|
|
}, 30_000);
|
|
it.each([true, false])("resolves an authorized exact poll vote once, including setup (qualified=%s)", async (qualified) => {
|
|
const t = await setup();
|
|
const conversation = await t.start();
|
|
if (qualified) await t.qualify();
|
|
const interaction = await issueThreadInteractionService(db).create(
|
|
{ id: conversation.issueId, companyId: t.companyId },
|
|
{
|
|
kind: "ask_user_questions",
|
|
continuationPolicy: "none",
|
|
payload: {
|
|
version: 1,
|
|
questions: [
|
|
{
|
|
id: "q",
|
|
prompt: "Choose",
|
|
selectionMode: "single",
|
|
required: true,
|
|
allowOther: false,
|
|
options: [
|
|
{ id: "one", label: "Same" },
|
|
{ id: "two", label: "Same" },
|
|
],
|
|
},
|
|
],
|
|
},
|
|
},
|
|
{ agentId: t.agentId },
|
|
);
|
|
await t.service.processPendingPublications();
|
|
expect(t.f.polls.size).toBe(1);
|
|
const poll = [...t.f.polls.values()][0];
|
|
const vote = {
|
|
type: "poll.changed",
|
|
sequence: 5,
|
|
chatGuid: t.f.chat.guid,
|
|
occurredAt: new Date(),
|
|
isFromMe: false,
|
|
actor: { address: "+15555550199", service: "iMessage" },
|
|
pollMessageGuid: poll.pollMessageGuid,
|
|
delta: {
|
|
type: "voted",
|
|
optionIdentifier: poll.options[1].optionIdentifier,
|
|
},
|
|
} as LiveEvent;
|
|
await t.deliver(vote);
|
|
expect(
|
|
(
|
|
await issueThreadInteractionService(db).listForIssue(
|
|
conversation.issueId,
|
|
)
|
|
)[0].status,
|
|
).toBe("pending");
|
|
await t.deliver({
|
|
...vote,
|
|
sequence: 6,
|
|
actor: { address: "+15555550101", service: "iMessage" },
|
|
} as LiveEvent);
|
|
const resolved = (
|
|
await issueThreadInteractionService(db).listForIssue(conversation.issueId)
|
|
)[0];
|
|
expect(resolved.status).toBe("answered");
|
|
expect(resolved.result).toMatchObject({
|
|
answers: [{ questionId: "q", optionIds: ["two"] }],
|
|
});
|
|
await t.deliver({
|
|
...vote,
|
|
sequence: 7,
|
|
actor: { address: "+15555550101", service: "iMessage" },
|
|
} as LiveEvent);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(issueQuestionResponseDeliveries)
|
|
.where(
|
|
eq(issueQuestionResponseDeliveries.interactionId, interaction.id),
|
|
),
|
|
).toHaveLength(1);
|
|
}, 30_000);
|
|
it("keeps multi-question drafts separate for two linked group participants", async () => {
|
|
const t = await setup();
|
|
await t.start();
|
|
await t.qualify();
|
|
const group = photonChat("iMessage;+;draft-group", true);
|
|
(group.participants as Array<(typeof group.participants)[number]>).push({ address: "+15555550102", service: "iMessage" });
|
|
t.chats.set(group.guid, group);
|
|
await t.deliver(photonEvent(3, group));
|
|
const resource = (await t.service.listResources(t.endpoint.id)).find(
|
|
(row) => row.type === "group_chat",
|
|
)!;
|
|
await t.service.replaceResources(
|
|
t.endpoint.id,
|
|
[{ id: resource.id, enabled: true }],
|
|
t.userId,
|
|
);
|
|
await t.deliver(photonEvent(4, group));
|
|
const conversation = (
|
|
await t.service.listConversations(t.endpoint.id)
|
|
).find((row) => !row.isDirectMessage)!;
|
|
const second = randomUUID();
|
|
await db.insert(authUsers).values({
|
|
id: second,
|
|
name: "Second",
|
|
email: `${second}@example.com`,
|
|
emailVerified: true,
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
});
|
|
await db.insert(companyMemberships).values({
|
|
companyId: t.companyId,
|
|
principalType: "user",
|
|
principalId: second,
|
|
status: "active",
|
|
membershipRole: "operator",
|
|
});
|
|
const fromSecond = (sequence: number, text: string) => {
|
|
const event = photonEvent(sequence, group, text);
|
|
return {
|
|
...event,
|
|
message: {
|
|
...event.message,
|
|
sender: { address: "+15555550102", service: "iMessage" },
|
|
},
|
|
} as LiveEvent;
|
|
};
|
|
await t.deliver(fromSecond(5, "Discover second participant"));
|
|
await t.link("+15555550102", second);
|
|
const interaction = await issueThreadInteractionService(db).create(
|
|
{ id: conversation.issueId, companyId: t.companyId },
|
|
{
|
|
kind: "ask_user_questions",
|
|
continuationPolicy: "none",
|
|
payload: {
|
|
version: 1,
|
|
questions: ["a", "b"].map((id) => ({
|
|
id,
|
|
prompt: "Duplicate title",
|
|
selectionMode: "single" as const,
|
|
required: true,
|
|
allowOther: true,
|
|
options: [{ id: "text", label: "Type an answer", freeText: true }],
|
|
})),
|
|
},
|
|
},
|
|
{ agentId: t.agentId },
|
|
);
|
|
await t.service.processPendingPublications();
|
|
const [binding] = await db
|
|
.select()
|
|
.from(chatActions)
|
|
.where(
|
|
and(
|
|
eq(chatActions.endpointId, t.endpoint.id),
|
|
eq(chatActions.kind, "photon_interaction"),
|
|
eq(
|
|
sql<string>`${chatActions.payload}->>'interactionId'`,
|
|
interaction.id,
|
|
),
|
|
),
|
|
);
|
|
const ref = binding.payload.reference;
|
|
await t.deliver(photonEvent(6, group, `/answer ${ref}.1 Alice A`));
|
|
await t.service.processPendingPublications();
|
|
await t.deliver(fromSecond(7, `/answer ${ref}.2 Bob B`));
|
|
await t.deliver(photonEvent(8, group, `/submit ${ref}`));
|
|
expect(
|
|
(
|
|
await issueThreadInteractionService(db).listForIssue(
|
|
conversation.issueId,
|
|
)
|
|
)[0].status,
|
|
).toBe("pending");
|
|
await t.service.processPendingPublications();
|
|
expect(t.f.client.messages.sendText.mock.calls.some((call) =>
|
|
call[1].includes(`Send /answer ${ref}.2 <answer> to correct it.`))).toBe(true);
|
|
await t.deliver(photonEvent(9, group, `/answer ${ref}.2 Alice B`));
|
|
await t.deliver(photonEvent(10, group, `/submit ${ref}`));
|
|
const resolved = (
|
|
await issueThreadInteractionService(db).listForIssue(conversation.issueId)
|
|
)[0];
|
|
expect(resolved.result).toMatchObject({
|
|
answers: [
|
|
{ questionId: "a", otherText: "Alice A" },
|
|
{ questionId: "b", otherText: "Alice B" },
|
|
],
|
|
});
|
|
expect(resolved.resolvedByUserId).toBe(t.userId);
|
|
const comments = await db
|
|
.select()
|
|
.from(issueComments)
|
|
.where(eq(issueComments.issueId, conversation.issueId));
|
|
expect(
|
|
comments.some(
|
|
(row) => row.body.includes("/answer") || row.body.includes("/submit"),
|
|
),
|
|
).toBe(false);
|
|
}, 30_000);
|
|
it("requires a correlated rejection reason and emits only one canonical continuation", async () => {
|
|
const t = await setup();
|
|
const conversation = await t.start();
|
|
await t.qualify();
|
|
const interaction = await issueThreadInteractionService(db).create(
|
|
{ id: conversation.issueId, companyId: t.companyId },
|
|
{
|
|
kind: "request_confirmation",
|
|
continuationPolicy: "wake_assignee",
|
|
payload: {
|
|
version: 1,
|
|
prompt: "Publish approved summary?",
|
|
rejectRequiresReason: true,
|
|
},
|
|
},
|
|
{ agentId: t.agentId },
|
|
);
|
|
await t.service.processPendingPublications();
|
|
const [binding] = await db
|
|
.select()
|
|
.from(chatActions)
|
|
.where(
|
|
and(
|
|
eq(chatActions.endpointId, t.endpoint.id),
|
|
eq(chatActions.kind, "photon_interaction"),
|
|
eq(
|
|
sql<string>`${chatActions.payload}->>'interactionId'`,
|
|
interaction.id,
|
|
),
|
|
),
|
|
);
|
|
const ref = binding.payload.reference;
|
|
await t.deliver(photonEvent(3, t.f.chat, `/answer ${ref} Reject`));
|
|
expect(
|
|
(
|
|
await issueThreadInteractionService(db).listForIssue(
|
|
conversation.issueId,
|
|
)
|
|
)[0].status,
|
|
).toBe("pending");
|
|
await t.service.processPendingPublications();
|
|
await t.deliver(
|
|
photonEvent(4, t.f.chat, `/answer ${ref} Reject Needs another review`),
|
|
);
|
|
await t.service.processPendingPublications();
|
|
expect(
|
|
(
|
|
await issueThreadInteractionService(db).listForIssue(
|
|
conversation.issueId,
|
|
)
|
|
)[0],
|
|
).toMatchObject({
|
|
status: "rejected",
|
|
result: { reason: "Needs another review" },
|
|
});
|
|
await t.deliver(photonEvent(5, t.f.chat, `/answer ${ref} Accept`));
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(chatActions)
|
|
.where(
|
|
and(
|
|
eq(chatActions.endpointId, t.endpoint.id),
|
|
eq(chatActions.kind, "interaction_wakeup"),
|
|
eq(
|
|
sql<string>`${chatActions.payload}->>'interactionId'`,
|
|
interaction.id,
|
|
),
|
|
),
|
|
),
|
|
).toHaveLength(1);
|
|
}, 30_000);
|
|
it("retries a delayed HEIC after restart without another comment or a premature wake", async () => {
|
|
const t = await setup();
|
|
const conversation = await t.start();
|
|
await t.qualify();
|
|
const body = await readFile(
|
|
new URL("./fixtures/synthetic.heic", import.meta.url),
|
|
);
|
|
const event = photonEvent(3, t.f.chat, "");
|
|
(event.message.content.attachments as Array<(typeof event.message.content.attachments)[number]>).push({
|
|
guid: "photo-guid",
|
|
fileName: "photo.heic",
|
|
mimeType: "image/heic",
|
|
totalBytes: body.length,
|
|
isHidden: false,
|
|
isSticker: false,
|
|
} as any);
|
|
t.f.client.attachments.downloadStream.mockImplementationOnce(() =>
|
|
stream([]),
|
|
);
|
|
await t.deliver(event);
|
|
expect(t.wakeup).toHaveBeenCalledTimes(1);
|
|
const [delivery] = await db
|
|
.select()
|
|
.from(chatDeliveries)
|
|
.where(
|
|
and(
|
|
eq(chatDeliveries.endpointId, t.endpoint.id),
|
|
eq(
|
|
sql<string>`${chatDeliveries.normalizedEvent}#>>'{message,providerMessageId}'`,
|
|
event.message.guid,
|
|
),
|
|
),
|
|
);
|
|
expect(delivery.state).toBe("retry");
|
|
expect(
|
|
(delivery.normalizedEvent.message as { attachments: Array<{ recovery: { locator: unknown } }> }).attachments[0]!.recovery.locator,
|
|
).toMatchObject({
|
|
kind: "photon_attachment",
|
|
messageGuid: event.message.guid,
|
|
attachmentGuid: "photo-guid",
|
|
});
|
|
const service = await t.restart();
|
|
t.f.client.attachments.downloadStream.mockImplementation(() =>
|
|
stream([
|
|
{
|
|
type: "header",
|
|
info: { guid: "photo-guid", totalBytes: body.length },
|
|
companionInfo: {
|
|
kind: "live-photo-video",
|
|
mimeType: "video/quicktime",
|
|
fileName: "photo.mov",
|
|
totalBytes: 9,
|
|
},
|
|
},
|
|
{ type: "primaryChunk", data: body },
|
|
{ type: "companionChunk", data: Buffer.from("companion") },
|
|
]),
|
|
);
|
|
await db
|
|
.update(chatDeliveries)
|
|
.set({ nextAttemptAt: new Date(0) })
|
|
.where(eq(chatDeliveries.id, delivery.id));
|
|
await service.processPendingDeliveries();
|
|
expect(t.wakeup).toHaveBeenCalledTimes(2);
|
|
const links = await db
|
|
.select()
|
|
.from(chatMessageLinks)
|
|
.where(
|
|
and(
|
|
eq(chatMessageLinks.endpointId, t.endpoint.id),
|
|
eq(chatMessageLinks.providerMessageId, event.message.guid),
|
|
),
|
|
);
|
|
expect(links).toHaveLength(1);
|
|
const files = await db
|
|
.select({ contentType: assets.contentType })
|
|
.from(issueAttachments)
|
|
.innerJoin(assets, eq(assets.id, issueAttachments.assetId))
|
|
.where(eq(issueAttachments.issueCommentId, links[0].commentId!));
|
|
expect(files.map((file) => file.contentType).sort()).toEqual([
|
|
"image/heic",
|
|
"image/jpeg",
|
|
"video/quicktime",
|
|
]);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(chatActions)
|
|
.where(
|
|
and(
|
|
eq(chatActions.endpointId, t.endpoint.id),
|
|
eq(chatActions.kind, "attachment_derivative"),
|
|
),
|
|
),
|
|
).toHaveLength(1);
|
|
}, 30_000);
|
|
|
|
it.each([false, true])("keeps completed DM replies on one task through restart and publishes committed comments live (shared=%s)", async (shared) => {
|
|
const t = await setup(shared);
|
|
const original = await t.start();
|
|
await t.qualify();
|
|
await issueService(db).update(original.issueId, { status: "done", actorUserId: t.userId });
|
|
// Recover rows that the previous implementation marked completed without
|
|
// an explicit control. A restart must not require an SDK chat cache.
|
|
await db.update(chatConversations).set({ state: "completed" }).where(eq(chatConversations.id, original.id));
|
|
const service = await t.restart();
|
|
const visibleComments: Promise<unknown>[] = [];
|
|
const unsubscribe = subscribeCompanyLiveEvents(t.companyId, (event) => {
|
|
if (event.type === "activity.logged" && event.payload.action === "issue.comment_added") {
|
|
expect(event.payload.entityId).toBe(original.issueId);
|
|
const details = event.payload.details as { commentId: string };
|
|
visibleComments.push(db.select().from(issueComments).where(eq(issueComments.id, details.commentId)));
|
|
}
|
|
});
|
|
try {
|
|
const followUp = photonEvent(3, t.f.chat, "Continue our conversation");
|
|
await t.deliver(followUp);
|
|
await t.deliver(followUp);
|
|
expect(await service.listConversations(t.endpoint.id)).toMatchObject([{ id: original.id, issueId: original.issueId, state: "active" }]);
|
|
expect((await db.select().from(issues).where(eq(issues.id, original.issueId)))[0].status).toBe("todo");
|
|
expect(t.wakeup).toHaveBeenCalledTimes(2);
|
|
expect(visibleComments).toHaveLength(1);
|
|
expect(await visibleComments[0]).toMatchObject([{ issueId: original.issueId, body: "Continue our conversation", metadata: { sourceChannel: "imessage-photon" } }]);
|
|
expect(await db.select().from(activityLog).where(and(eq(activityLog.entityId, original.issueId), eq(activityLog.action, "issue.comment_added")))).toHaveLength(2);
|
|
} finally {
|
|
unsubscribe();
|
|
}
|
|
await issueService(db).update(original.issueId, { status: "done", actorUserId: t.userId });
|
|
await t.deliver(photonEvent(4, t.f.chat, "/status"));
|
|
await service.processPendingPublications();
|
|
expect(t.f.client.messages.sendText.mock.calls.some((call) => call[1].includes(original.issueIdentifier!))).toBe(true);
|
|
await t.deliver(photonEvent(5, t.f.chat, "/new"));
|
|
await service.processPendingPublications();
|
|
await t.deliver(photonEvent(6, t.f.chat, "An explicitly new task"));
|
|
const conversations = await service.listConversations(t.endpoint.id);
|
|
expect(conversations).toHaveLength(2);
|
|
expect(conversations.find((row) => row.id !== original.id)?.issueId).not.toBe(original.issueId);
|
|
}, 30_000);
|
|
|
|
it("preserves reply context, rejects old quoted controls, and starts a new generation after close", async () => {
|
|
const t = await setup();
|
|
const original = await t.start();
|
|
await t.qualify();
|
|
const quoted = photonEvent(3, t.f.chat, "Follow up to that message");
|
|
Object.assign(quoted.message, {
|
|
replyTargetGuid: "message-2",
|
|
threadOriginatorPart: "0",
|
|
});
|
|
await t.deliver(quoted);
|
|
const [link] = await db
|
|
.select()
|
|
.from(chatMessageLinks)
|
|
.where(
|
|
and(
|
|
eq(chatMessageLinks.endpointId, t.endpoint.id),
|
|
eq(chatMessageLinks.providerMessageId, "message-3"),
|
|
),
|
|
);
|
|
const [comment] = await db
|
|
.select()
|
|
.from(issueComments)
|
|
.where(eq(issueComments.id, link.commentId!));
|
|
expect(JSON.stringify(comment.metadata)).toContain("Reply to message");
|
|
expect(JSON.stringify(comment.metadata)).toContain("message-2");
|
|
await t.deliver(photonEvent(4, t.f.chat, "/close"));
|
|
await t.service.processPendingPublications();
|
|
await t.deliver(photonEvent(5, t.f.chat, "Start the next task"));
|
|
const conversations = await t.service.listConversations(t.endpoint.id);
|
|
expect(conversations).toHaveLength(2);
|
|
const current = conversations.find((row) => row.id !== original.id)!;
|
|
const stale = photonEvent(6, t.f.chat, "/close");
|
|
Object.assign(stale.message, { replyTargetGuid: "message-2" });
|
|
await t.deliver(stale);
|
|
await t.service.processPendingPublications();
|
|
expect(
|
|
(await t.service.listConversations(t.endpoint.id)).find(
|
|
(row) => row.id === current.id,
|
|
)?.state,
|
|
).toBe("active");
|
|
await t.deliver(photonEvent(7, t.f.chat, "/status"));
|
|
await t.service.processPendingPublications();
|
|
expect(
|
|
t.f.client.messages.sendText.mock.calls.some((call) =>
|
|
call[1].includes("Start the next task"),
|
|
),
|
|
).toBe(true);
|
|
}, 30_000);
|
|
it("retains accepted pending input through pause and blocks publication after group removal", async () => {
|
|
const t = await setup();
|
|
await t.start();
|
|
await t.qualify();
|
|
await t.callbacks().onPhotonEvent!(
|
|
photonEvent(3, t.f.chat, "Accepted before pause"),
|
|
);
|
|
await t.service.configure(t.endpoint.id, { action: "pause" }, t.userId);
|
|
await t.service.processPendingDeliveries();
|
|
expect(t.wakeup).toHaveBeenCalledTimes(1);
|
|
await t.service.configure(t.endpoint.id, { action: "resume" }, t.userId);
|
|
await t.service.processPendingDeliveries();
|
|
expect(t.wakeup).toHaveBeenCalledTimes(2);
|
|
const group = photonChat("iMessage;+;remove-group", true);
|
|
t.chats.set(group.guid, group);
|
|
await t.deliver(photonEvent(4, group));
|
|
const resource = (await t.service.listResources(t.endpoint.id)).find(
|
|
(row) => row.type === "group_chat",
|
|
)!;
|
|
await t.service.replaceResources(
|
|
t.endpoint.id,
|
|
[{ id: resource.id, enabled: true }],
|
|
t.userId,
|
|
);
|
|
await t.deliver(photonEvent(5, group));
|
|
const get = t.f.client.chats.get;
|
|
get.mockRejectedValueOnce(new Error("Chat inaccessible after removal"));
|
|
await t.deliver({
|
|
type: "group.changed",
|
|
chatGuid: group.guid,
|
|
sequence: 6,
|
|
occurredAt: new Date(),
|
|
isFromMe: false,
|
|
change: {
|
|
type: "participantRemoved",
|
|
participant: { address: "+15555550100", service: "iMessage" },
|
|
},
|
|
} as LiveEvent);
|
|
expect(
|
|
(await t.service.listResources(t.endpoint.id)).find(
|
|
(row) => row.id === resource.id,
|
|
)?.availability,
|
|
).toBe("unavailable");
|
|
// Removal and late events need no now-inaccessible chat lookup.
|
|
const calls = get.mock.calls.length;
|
|
await t.deliver(photonEvent(7, group, "Late event after removal"));
|
|
expect(get).toHaveBeenCalledTimes(calls);
|
|
const undiscovered = photonChat("iMessage;+;undiscovered-removed-group", true);
|
|
await t.deliver({
|
|
type: "group.changed",
|
|
chatGuid: undiscovered.guid,
|
|
sequence: 8,
|
|
occurredAt: new Date(),
|
|
isFromMe: false,
|
|
change: {
|
|
type: "participantLeft",
|
|
participant: { address: "+15555550100", service: "iMessage" },
|
|
},
|
|
} as LiveEvent);
|
|
await t.deliver(photonEvent(9, undiscovered, "Late undiscovered event"));
|
|
expect(get).toHaveBeenCalledTimes(calls);
|
|
expect((await t.service.listResources(t.endpoint.id)).filter(
|
|
(row) => row.type === "group_chat" && row.availability === "unavailable",
|
|
)).toHaveLength(2);
|
|
}, 30_000);
|
|
it.each(["active", "verifying"] as const)("reconstructs native continuation authority for a linked group responder (%s)", async (endpointStatus) => {
|
|
const t = await setup();
|
|
await t.start();
|
|
await t.qualify();
|
|
const group = photonChat("iMessage;+;native-group", true);
|
|
(group.participants as Array<(typeof group.participants)[number]>).push({ address: "+15555550102", service: "iMessage" });
|
|
t.chats.set(group.guid, group);
|
|
await t.deliver(photonEvent(3, group));
|
|
const resource = (await t.service.listResources(t.endpoint.id)).find(
|
|
(row) => row.type === "group_chat",
|
|
)!;
|
|
await t.service.replaceResources(
|
|
t.endpoint.id,
|
|
[{ id: resource.id, enabled: true }],
|
|
t.userId,
|
|
);
|
|
await t.deliver(photonEvent(4, group));
|
|
const conversation = (
|
|
await t.service.listConversations(t.endpoint.id)
|
|
).find((row) => !row.isDirectMessage)!;
|
|
const second = randomUUID();
|
|
await db.insert(authUsers).values({
|
|
id: second,
|
|
name: "Responder",
|
|
email: `${second}@example.com`,
|
|
emailVerified: true,
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
});
|
|
await db.insert(companyMemberships).values({
|
|
companyId: t.companyId,
|
|
principalType: "user",
|
|
principalId: second,
|
|
status: "active",
|
|
membershipRole: "operator",
|
|
});
|
|
const discover = photonEvent(5, group);
|
|
Object.assign(discover.message, {
|
|
sender: { address: "+15555550102", service: "iMessage" },
|
|
});
|
|
await t.deliver(discover);
|
|
await t.link("+15555550102", second);
|
|
const [sourceLink] = await db
|
|
.select()
|
|
.from(chatMessageLinks)
|
|
.where(
|
|
and(
|
|
eq(chatMessageLinks.endpointId, t.endpoint.id),
|
|
eq(chatMessageLinks.providerMessageId, "message-4"),
|
|
),
|
|
);
|
|
const sourceRunId = randomUUID();
|
|
const sourceCommentId = sourceLink.commentId!;
|
|
await db.insert(heartbeatRuns).values({
|
|
id: sourceRunId,
|
|
companyId: t.companyId,
|
|
agentId: t.agentId,
|
|
status: "succeeded",
|
|
runtimeMode: "native",
|
|
nativeIssueId: conversation.issueId,
|
|
contextSnapshot: {
|
|
source: "chat:imessage-photon",
|
|
issueId: conversation.issueId,
|
|
wakeCommentId: sourceCommentId,
|
|
wakeCommentIds: [sourceCommentId],
|
|
paperclipExternalChatExecutionBound: true,
|
|
paperclipWake: {
|
|
externalChatProvider: "imessage-photon",
|
|
externalChatExecutionBound: true,
|
|
},
|
|
},
|
|
});
|
|
const interaction = await issueThreadInteractionService(db).create(
|
|
{ id: conversation.issueId, companyId: t.companyId },
|
|
{
|
|
kind: "ask_user_questions",
|
|
continuationPolicy: "wake_assignee",
|
|
sourceRunId,
|
|
sourceCommentId,
|
|
payload: {
|
|
version: 1,
|
|
questions: [
|
|
{
|
|
id: "priority",
|
|
prompt: "Priority?",
|
|
selectionMode: "single",
|
|
required: true,
|
|
allowOther: false,
|
|
options: [
|
|
{ id: "one", label: "One" },
|
|
{ id: "two", label: "Two" },
|
|
],
|
|
},
|
|
],
|
|
},
|
|
},
|
|
{ agentId: t.agentId, runId: sourceRunId },
|
|
);
|
|
await t.service.processPendingPublications();
|
|
if (endpointStatus === "verifying") {
|
|
await db.update(chatEndpoints).set({status: "verifying", setup: sql`jsonb_set(${chatEndpoints.setup}, '{step}', '"test"')`}).where(eq(chatEndpoints.id, t.endpoint.id));
|
|
}
|
|
const [action] = await db
|
|
.select()
|
|
.from(chatActions)
|
|
.where(
|
|
and(
|
|
eq(chatActions.endpointId, t.endpoint.id),
|
|
eq(chatActions.kind, "photon_interaction"),
|
|
eq(
|
|
sql<string>`${chatActions.payload}->>'interactionId'`,
|
|
interaction.id,
|
|
),
|
|
),
|
|
);
|
|
const reply = photonEvent(
|
|
6,
|
|
group,
|
|
`/answer ${action.payload.reference} 2`,
|
|
);
|
|
Object.assign(reply.message, {
|
|
sender: { address: "+15555550102", service: "iMessage" },
|
|
});
|
|
await t.deliver(reply);
|
|
expect(
|
|
(
|
|
await issueThreadInteractionService(db).listForIssue(
|
|
conversation.issueId,
|
|
)
|
|
)[0].resolvedByUserId,
|
|
).toBe(second);
|
|
const runId = randomUUID(),
|
|
wakeId = randomUUID();
|
|
const context = {
|
|
source: "issue.interaction.respond",
|
|
issueId: conversation.issueId,
|
|
wakeReason: "issue_commented",
|
|
interactionId: interaction.id,
|
|
interactionKind: "ask_user_questions",
|
|
interactionStatus: "answered",
|
|
sourceRunId,
|
|
sourceCommentId,
|
|
wakeCommentId: sourceCommentId,
|
|
wakeCommentIds: [sourceCommentId],
|
|
externalChatContinuation: true,
|
|
};
|
|
await db.insert(agentWakeupRequests).values({
|
|
id: wakeId,
|
|
companyId: t.companyId,
|
|
agentId: t.agentId,
|
|
source: "automation",
|
|
status: "running",
|
|
runId,
|
|
requestedByActorType: "user",
|
|
requestedByActorId: second,
|
|
idempotencyKey: `question-response:${interaction.id}`,
|
|
payload: context,
|
|
});
|
|
await db.insert(heartbeatRuns).values({
|
|
id: runId,
|
|
companyId: t.companyId,
|
|
agentId: t.agentId,
|
|
status: "running",
|
|
runtimeMode: "native",
|
|
nativeIssueId: conversation.issueId,
|
|
wakeupRequestId: wakeId,
|
|
contextSnapshot: context,
|
|
});
|
|
await db
|
|
.update(issueQuestionResponseDeliveries)
|
|
.set({
|
|
status: "fallback_queued",
|
|
deliveryMode: "wake_fallback",
|
|
targetRunId: runId,
|
|
})
|
|
.where(eq(issueQuestionResponseDeliveries.interactionId, interaction.id));
|
|
const proof = await resolveExternalChatQuestionResponse(
|
|
db,
|
|
{
|
|
companyId: t.companyId,
|
|
agentId: t.agentId,
|
|
issueId: conversation.issueId,
|
|
runId,
|
|
},
|
|
context,
|
|
"read",
|
|
true,
|
|
);
|
|
expect(proof).toMatchObject({
|
|
provider: "imessage-photon",
|
|
marker: { sourceCommentId, conversationId: conversation.id },
|
|
});
|
|
await db
|
|
.update(chatIdentityLinks)
|
|
.set({ status: "revoked" })
|
|
.where(
|
|
and(
|
|
eq(chatIdentityLinks.endpointId, t.endpoint.id),
|
|
eq(chatIdentityLinks.paperclipUserId, second),
|
|
),
|
|
);
|
|
expect(
|
|
await resolveExternalChatQuestionResponse(
|
|
db,
|
|
{
|
|
companyId: t.companyId,
|
|
agentId: t.agentId,
|
|
issueId: conversation.issueId,
|
|
runId,
|
|
},
|
|
context,
|
|
"read",
|
|
true,
|
|
),
|
|
).toBeNull();
|
|
}, 30_000);
|
|
it("fences checkpoint writes in the transaction that verifies receiver ownership", async () => {
|
|
const t = await setup();
|
|
await t.start();
|
|
await t.qualify();
|
|
const callback = t.callbacks().onPhotonCheckpoint!;
|
|
const key = `photon:${createHash("sha256").update("checkpoint").digest("hex")}`;
|
|
const before = await db
|
|
.select()
|
|
.from(chatSdkState)
|
|
.where(
|
|
and(
|
|
eq(chatSdkState.endpointId, t.endpoint.id),
|
|
eq(chatSdkState.stateKey, key),
|
|
),
|
|
);
|
|
await db
|
|
.update(chatEndpointLeases)
|
|
.set({ token: randomUUID() })
|
|
.where(
|
|
and(
|
|
eq(chatEndpointLeases.endpointId, t.endpoint.id),
|
|
eq(chatEndpointLeases.leaseKey, "photon_receiver_runtime"),
|
|
),
|
|
);
|
|
await expect(callback(100)).rejects.toThrow();
|
|
const after = await db
|
|
.select()
|
|
.from(chatSdkState)
|
|
.where(
|
|
and(
|
|
eq(chatSdkState.endpointId, t.endpoint.id),
|
|
eq(chatSdkState.stateKey, key),
|
|
),
|
|
);
|
|
expect(after.map((row) => row.value)).toEqual(
|
|
before.map((row) => row.value),
|
|
);
|
|
}, 30_000);
|
|
it("answers status without creating a task after a conversation closes", async () => {
|
|
const t = await setup();
|
|
await t.start();
|
|
await t.qualify();
|
|
await t.deliver(photonEvent(3, t.f.chat, "/close"));
|
|
await t.service.processPendingPublications();
|
|
const wakes = t.wakeup.mock.calls.length;
|
|
await t.deliver(photonEvent(4, t.f.chat, "/status"));
|
|
await t.service.processPendingPublications();
|
|
expect(t.wakeup).toHaveBeenCalledTimes(wakes);
|
|
expect(await t.service.listConversations(t.endpoint.id)).toHaveLength(1);
|
|
expect(t.f.client.messages.sendText.mock.calls.at(-1)?.[1]).toContain(
|
|
"No task is active",
|
|
);
|
|
}, 30_000);
|
|
});
|