Files
Reactive-Resume/packages/api/src/services/storage.test.ts
T
Amruth Pillai 6d8d8f6e55 feat: add AI agent workspace (#3062)
* chore(ai): remove local AI store now that providers live server-side

The Zustand-based useAIStore has been replaced by the server-side
aiProviders oRPC router (encrypted credentials persisted in DB).
Delete the dead store + tests, drop the ./store export, and remove
zustand/immer deps which are no longer referenced anywhere in
packages/ai/src/.

* feat(agent): archive/delete actions and read-only state for agent threads

- Backend: mark archived threads as read-only in threads.get and reject
  messages.send with CONFLICT when the thread is archived.
- Frontend: render archived threads in the sidebar with muted styling and
  an Archived badge; add a per-thread dropdown menu in the chat header
  with Archive (non-destructive) and Delete (with confirmation); show a
  read-only banner above the message list that disambiguates archived
  vs. missing-resource causes; suppress the Retry and Stop buttons in
  read-only mode.
- Tests: new packages/api/src/services/agent.test.ts covering the
  archived-thread isReadOnly flag and the archived-thread send refusal.

* fix(agent): abort run on archive and verify ownership before deleting thread

- threads.archive: before flipping status, abort any in-flight run controller
  and clear the active-run state on the thread; cleanup failures are logged
  but do not block the status update.
- threads.delete: assert thread ownership via getThread before destructive
  work so an authenticated user cannot wipe another user's attachment rows
  by passing a foreign threadId.

Adds focused tests for both behaviors.

* feat(agent): display patch diffs and surface revert conflicts

Render apply_resume_patch tool messages with a status-aware card (applied/
reverted/conflicted), expandable operation list, and a Revert button that
correctly handles RESUME_VERSION_CONFLICT responses. Adds unit tests for
the inverse-patch builder and the agentService.actions.revert flow.

* chore(agent): remove out-of-scope attachment tests accidentally added in Task 6

The Task 6 commit (73ef1acca) accidentally re-introduced three attachment-
related tests that belong to a separate task:

- `buildAttachmentModelParts > converts text, image, supported binary, and
  unsupported attachments into model parts`
- `agentService.messages.send > persists the user message with file UI parts
  and links selected attachments to it` (was failing — the `ToolLoopAgent`
  mock is not callable as a constructor)
- `agentService.messages.send > rejects attachments that are missing, foreign,
  or already linked before persisting a message`

These were likely re-added during a stash recovery and were not requested
for Task 6, whose scope was limited to the `agentService.actions.revert`
flow. Remove them along with the helpers/fixtures (`buildAttachment`,
`buildActiveThread`, `selectWhereResult`, `selectOrderByResult`) that they
were the only consumers of. `selectLimitResult` is preserved because it is
used by the revert tests.

* chore(agent): configure runtime dependencies

* feat(db): add agent workspace schema

* feat(api): add agent backend services

* feat(web): add agent workspace UI

* chore(agent): remove legacy builder assistant

* test(agent): make agent stream mocks constructible

* chore(web): remove unused resume replacement hook

* feat(api): add unsafe AI base URL flag

* chore(dev): expose local services in compose

* fix(web): normalize resume preview gaps

* feat(api): improve agent tool handling

* feat(web): polish agent workspace UI

* chore: update dependencies

* fix(api,web): address PR review feedback for agent workspace

Security/correctness:
- Restrict AI provider URLs to http/https even in unsafe mode
- Stop exposing Redis on host network by default
- Make .env.local optional and drop app profile in compose.dev.yml
- Store agent attachments with private ACL on S3
- Reset provider test status when provider/model/baseURL changes
- Decouple non-agent AI endpoints from REDIS_URL requirement
- Fix JSON Patch add inverse for existing object members
- Wrap resume patch + agent action insert in db transaction
- Validate partialMessage at runtime and rate-limit attachment uploads
- Add unique index on agent_messages (thread_id, sequence)

UX/bugs:
- Mark agent thread route as ssr: false and guard SSE chunk parsing
- Show config-specific banner only on known configuration error
- Gate AI provider checks behind loading state in resume import
- Fix relative-time formatter blank gap between 45-59 seconds
- Clarify thread delete confirmation message

Polish:
- Raise ENCRYPTION_SECRET minimum to 32 characters
- Bucket AI rate limits by resumeId/threadId/messageId
- Trim form values before submitting AI provider config
- Use single key identifier and nullish-coalesce baseURL display

* fix: address ai agent review feedback

* fix: preserve mobile agent chat state

* docs: add ai agent workspace guides

* feat: introduce design system for Reactive Resume
2026-05-14 15:00:04 +02:00

127 lines
4.3 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
const envMock = vi.hoisted(() => ({
APP_URL: "https://example.com",
LOCAL_STORAGE_PATH: "",
S3_ACCESS_KEY_ID: undefined as string | undefined,
S3_SECRET_ACCESS_KEY: undefined as string | undefined,
S3_REGION: "us-east-1",
S3_ENDPOINT: undefined as string | undefined,
S3_BUCKET: undefined as string | undefined,
S3_FORCE_PATH_STYLE: false,
FLAG_DISABLE_IMAGE_PROCESSING: false,
}));
vi.mock("@reactive-resume/env/server", () => ({ env: envMock }));
// sharp is exercised by processImageForUpload; keep it out of the import graph entirely
// because resolving it loads native bindings we can't rely on in CI.
vi.mock("sharp", () => {
const chain = {
resize: () => chain,
jpeg: () => chain,
rotate: () => chain,
toBuffer: async () => Buffer.from("processed"),
metadata: async () => ({ width: 100, height: 100 }),
};
return { default: () => chain };
});
vi.mock("@aws-sdk/client-s3", () => ({
S3Client: vi.fn(),
PutObjectCommand: vi.fn(),
GetObjectCommand: vi.fn(),
DeleteObjectCommand: vi.fn(),
ListObjectsV2Command: vi.fn(),
}));
const { getStorageService, inferContentType, isImageFile, processImageForUpload } = await import("./storage");
const makeFile = (bytes: Uint8Array, type = "image/png") =>
({
arrayBuffer: async () => bytes.buffer,
type,
}) as unknown as File;
describe("inferContentType", () => {
it("maps common image extensions to their MIME types", () => {
expect(inferContentType("photo.jpg")).toBe("image/jpeg");
expect(inferContentType("photo.jpeg")).toBe("image/jpeg");
expect(inferContentType("photo.png")).toBe("image/png");
expect(inferContentType("animated.gif")).toBe("image/gif");
expect(inferContentType("logo.svg")).toBe("image/svg+xml");
expect(inferContentType("photo.webp")).toBe("image/webp");
});
it("maps .pdf to application/pdf", () => {
expect(inferContentType("doc.pdf")).toBe("application/pdf");
});
it("is case-insensitive on the extension", () => {
expect(inferContentType("PHOTO.JPG")).toBe("image/jpeg");
expect(inferContentType("Document.PDF")).toBe("application/pdf");
});
it("falls back to application/octet-stream for unknown extensions", () => {
expect(inferContentType("data.xyz")).toBe("application/octet-stream");
expect(inferContentType("README")).toBe("application/octet-stream");
});
it("uses just the file extension regardless of path depth", () => {
expect(inferContentType("/nested/dir/file.png")).toBe("image/png");
});
});
describe("processImageForUpload", () => {
it("returns the file untouched when image processing is disabled", async () => {
envMock.FLAG_DISABLE_IMAGE_PROCESSING = true;
const file = makeFile(new Uint8Array([1, 2, 3, 4]), "image/png");
const result = await processImageForUpload(file);
expect(result.contentType).toBe("image/png");
expect(Array.from(result.data)).toEqual([1, 2, 3, 4]);
});
it("re-encodes to JPEG via sharp when processing is enabled", async () => {
envMock.FLAG_DISABLE_IMAGE_PROCESSING = false;
const file = makeFile(new Uint8Array([5, 6, 7, 8]), "image/png");
const result = await processImageForUpload(file);
expect(result.contentType).toBe("image/jpeg");
// Sharp mock returns "processed" — ensure we got something not equal to the input.
expect(result.data.length).toBeGreaterThan(0);
expect(Array.from(result.data)).not.toEqual([5, 6, 7, 8]);
});
});
describe("isImageFile", () => {
it("returns true for supported image mime types", () => {
for (const type of ["image/gif", "image/png", "image/jpeg", "image/webp"]) {
expect(isImageFile(type), type).toBe(true);
}
});
it("returns false for image/svg+xml (not in the upload allowlist)", () => {
expect(isImageFile("image/svg+xml")).toBe(false);
});
it("returns false for application/pdf and other non-image types", () => {
expect(isImageFile("application/pdf")).toBe(false);
expect(isImageFile("text/plain")).toBe(false);
expect(isImageFile("")).toBe(false);
});
});
describe("LocalStorageService", () => {
it("rejects private writes instead of silently storing them on the local filesystem", async () => {
await expect(
getStorageService().write({
key: "uploads/user/agent/thread/file.txt",
data: new TextEncoder().encode("private"),
contentType: "text/plain",
private: true,
}),
).rejects.toThrow("Private storage writes are not supported by the local filesystem backend.");
});
});