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
This commit is contained in:
Amruth Pillai
2026-05-14 15:00:04 +02:00
committed by GitHub
parent 22c60c64b6
commit 6d8d8f6e55
115 changed files with 15623 additions and 2123 deletions
+46
View File
@@ -0,0 +1,46 @@
import { describe, expect, it } from "vitest";
import { getTableColumns, getTableName } from "drizzle-orm";
import { agentAction, agentAttachment, agentMessage, agentThread, aiProvider } from "./agent";
describe("aiProvider table definition", () => {
it("is named ai_providers and stores encrypted credentials metadata", () => {
expect(getTableName(aiProvider)).toBe("ai_providers");
const columns = getTableColumns(aiProvider);
for (const name of [
"id",
"userId",
"label",
"provider",
"model",
"baseUrl",
"encryptedApiKey",
"apiKeySalt",
"apiKeyHash",
"apiKeyPreview",
"testStatus",
"lastTestedAt",
"lastUsedAt",
"enabled",
"createdAt",
"updatedAt",
]) {
expect(columns[name as keyof typeof columns], name).toBeDefined();
}
});
});
describe("agent workspace table definitions", () => {
it("declares threads, messages, attachments, and actions", () => {
expect(getTableName(agentThread)).toBe("agent_threads");
expect(getTableName(agentMessage)).toBe("agent_messages");
expect(getTableName(agentAttachment)).toBe("agent_attachments");
expect(getTableName(agentAction)).toBe("agent_actions");
expect(getTableColumns(agentThread).workingResumeId).toBeDefined();
expect(getTableColumns(agentThread).lastMessageAt).toBeDefined();
expect(getTableColumns(agentMessage).uiMessage).toBeDefined();
expect(getTableColumns(agentAttachment).storageKey).toBeDefined();
expect(getTableColumns(agentAction).inverseOperations).toBeDefined();
});
});
+178
View File
@@ -0,0 +1,178 @@
import type { JsonPatchOperation } from "@reactive-resume/utils/resume/patch";
import * as pg from "drizzle-orm/pg-core";
import { generateId } from "@reactive-resume/utils/string";
import { user } from "./auth";
import { resume } from "./resume";
export type AgentUiMessage = Record<string, unknown>;
export const aiProvider = pg.pgTable(
"ai_providers",
{
id: pg
.text("id")
.notNull()
.primaryKey()
.$defaultFn(() => generateId()),
userId: pg
.text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
label: pg.text("label").notNull(),
provider: pg.text("provider").notNull(),
model: pg.text("model").notNull(),
baseUrl: pg.text("base_url"),
encryptedApiKey: pg.text("encrypted_api_key").notNull(),
apiKeySalt: pg.text("api_key_salt").notNull(),
apiKeyHash: pg.text("api_key_hash").notNull(),
apiKeyPreview: pg.text("api_key_preview").notNull(),
testStatus: pg.text("test_status").notNull().default("untested"),
testError: pg.text("test_error"),
lastTestedAt: pg.timestamp("last_tested_at", { withTimezone: true }),
lastUsedAt: pg.timestamp("last_used_at", { withTimezone: true }),
enabled: pg.boolean("enabled").notNull().default(false),
createdAt: pg.timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: pg
.timestamp("updated_at", { withTimezone: true })
.notNull()
.defaultNow()
.$onUpdate(() => /* @__PURE__ */ new Date()),
},
(t) => [
pg.index().on(t.userId, t.enabled),
pg.index().on(t.userId, t.lastUsedAt.desc()),
pg.index().on(t.userId, t.createdAt.asc()),
],
);
export const agentThread = pg.pgTable(
"agent_threads",
{
id: pg
.text("id")
.notNull()
.primaryKey()
.$defaultFn(() => generateId()),
userId: pg
.text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
aiProviderId: pg.text("ai_provider_id").references(() => aiProvider.id, { onDelete: "set null" }),
sourceResumeId: pg.text("source_resume_id").references(() => resume.id, { onDelete: "set null" }),
workingResumeId: pg.text("working_resume_id").references(() => resume.id, { onDelete: "set null" }),
title: pg.text("title").notNull(),
status: pg.text("status").notNull().default("active"),
activeRunId: pg.text("active_run_id"),
activeStreamId: pg.text("active_stream_id"),
activeRunStartedAt: pg.timestamp("active_run_started_at", { withTimezone: true }),
lastMessageAt: pg.timestamp("last_message_at", { withTimezone: true }).notNull().defaultNow(),
archivedAt: pg.timestamp("archived_at", { withTimezone: true }),
deletedAt: pg.timestamp("deleted_at", { withTimezone: true }),
createdAt: pg.timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: pg
.timestamp("updated_at", { withTimezone: true })
.notNull()
.defaultNow()
.$onUpdate(() => /* @__PURE__ */ new Date()),
},
(t) => [
pg.index().on(t.userId, t.status, t.lastMessageAt.desc()),
pg.index().on(t.workingResumeId),
pg.index().on(t.aiProviderId),
],
);
export const agentMessage = pg.pgTable(
"agent_messages",
{
id: pg
.text("id")
.notNull()
.primaryKey()
.$defaultFn(() => generateId()),
userId: pg
.text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
threadId: pg
.text("thread_id")
.notNull()
.references(() => agentThread.id, { onDelete: "cascade" }),
role: pg.text("role").notNull(),
status: pg.text("status").notNull().default("completed"),
sequence: pg.integer("sequence").notNull(),
uiMessage: pg.jsonb("ui_message").notNull().$type<AgentUiMessage>(),
error: pg.text("error"),
createdAt: pg.timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: pg
.timestamp("updated_at", { withTimezone: true })
.notNull()
.defaultNow()
.$onUpdate(() => /* @__PURE__ */ new Date()),
},
(t) => [pg.uniqueIndex().on(t.threadId, t.sequence), pg.index().on(t.userId, t.createdAt.desc())],
);
export const agentAttachment = pg.pgTable(
"agent_attachments",
{
id: pg
.text("id")
.notNull()
.primaryKey()
.$defaultFn(() => generateId()),
userId: pg
.text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
threadId: pg
.text("thread_id")
.notNull()
.references(() => agentThread.id, { onDelete: "cascade" }),
messageId: pg.text("message_id").references(() => agentMessage.id, { onDelete: "set null" }),
storageKey: pg.text("storage_key").notNull(),
filename: pg.text("filename").notNull(),
mediaType: pg.text("media_type").notNull(),
size: pg.integer("size").notNull(),
createdAt: pg.timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [pg.index().on(t.threadId), pg.index().on(t.messageId), pg.index().on(t.userId)],
);
export const agentAction = pg.pgTable(
"agent_actions",
{
id: pg
.text("id")
.notNull()
.primaryKey()
.$defaultFn(() => generateId()),
userId: pg
.text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
threadId: pg
.text("thread_id")
.notNull()
.references(() => agentThread.id, { onDelete: "cascade" }),
messageId: pg.text("message_id").references(() => agentMessage.id, { onDelete: "set null" }),
resumeId: pg.text("resume_id").references(() => resume.id, { onDelete: "set null" }),
kind: pg.text("kind").notNull(),
status: pg.text("status").notNull().default("applied"),
title: pg.text("title").notNull(),
summary: pg.text("summary"),
operations: pg.jsonb("operations").notNull().$type<JsonPatchOperation[]>(),
inverseOperations: pg.jsonb("inverse_operations").notNull().$type<JsonPatchOperation[]>(),
baseUpdatedAt: pg.timestamp("base_updated_at", { withTimezone: true }).notNull(),
appliedUpdatedAt: pg.timestamp("applied_updated_at", { withTimezone: true }).notNull(),
revertedAt: pg.timestamp("reverted_at", { withTimezone: true }),
revertMessage: pg.text("revert_message"),
createdAt: pg.timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: pg
.timestamp("updated_at", { withTimezone: true })
.notNull()
.defaultNow()
.$onUpdate(() => /* @__PURE__ */ new Date()),
},
(t) => [pg.index().on(t.threadId, t.createdAt.desc()), pg.index().on(t.resumeId), pg.index().on(t.messageId)],
);
+1
View File
@@ -1,2 +1,3 @@
export * from "./agent";
export * from "./auth";
export * from "./resume";