⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat: scope agent memory threads and delete them with their owner (#42)
Croff28579704b98b
diff --git a/apps/api/src/agent-schedules/store.ts b/apps/api/src/agent-schedules/store.tsindex ba7b7444..985d4167 100644--- a/apps/api/src/agent-schedules/store.ts+++ b/apps/api/src/agent-schedules/store.ts@@ -1,6 +1,7 @@import { db, agentRun, agentSchedule, aiAgent, user } from '@repo/db';import { and, desc, eq, sql } from 'drizzle-orm';import { iso } from '../shared/lib';+import { deleteThreadsWhere } from '../ai-agents/runtime/memory';export type AgentScheduleStatus = 'active' | 'paused';@@ -148,10 +149,13 @@ export async function updateAgentSchedule(return getAgentSchedule(projectId, scheduleId);}+// Deletes a schedule and the conversation thread its runs shared, which lives outside+// the database cascades (see ai-agents/runtime/memory).export async function deleteAgentSchedule(projectId: number, scheduleId: number): Promise<boolean> {const current = await getAgentSchedule(projectId, scheduleId);if (!current) return false;await db.delete(agentSchedule).where(eq(agentSchedule.id, scheduleId));+ await deleteThreadsWhere({ scheduleId });return true;}diff --git a/apps/api/src/ai-agents/__tests__/integration/agent-threads.test.ts b/apps/api/src/ai-agents/__tests__/integration/agent-threads.test.tsindex 26c8a8e9..f1289130 100644--- a/apps/api/src/ai-agents/__tests__/integration/agent-threads.test.ts+++ b/apps/api/src/ai-agents/__tests__/integration/agent-threads.test.ts@@ -2,15 +2,19 @@ import { describe, it, expect, beforeEach } from 'bun:test';import { authedApi, type Api } from '../../../__tests__/helpers/app';import { signUpTestUser } from '../../../__tests__/helpers/auth';import { resetDb } from '../../../__tests__/helpers/db';-import { createChatThread, buildMemory } from '../../runtime/memory';+import { ensureThread, buildMemory } from '../../runtime/memory';// The chat-history endpoints:// GET /projects/:key/ai-agents/:agentId/threads — the caller's own chat// threads with the agent// GET .../ai-agents/:agentId/threads/:threadId/messages — one thread's transcript+// DELETE .../ai-agents/:agentId/threads/:threadId — delete one conversation+//+// plus the thread scoping of a chat run: the thread id names the agent and the user it+// was issued to, and a run may only continue one of the caller's own.//// Chat threads live in Mastra's memory store (mastra_threads / mastra_messages),-// bound to their agent and owner via createChatThread. The runtime (a live LLM call)+// bound to their agent and owner via ensureThread. The runtime (a live LLM call)// is not exercised: threads and messages are seeded directly through the memory// module so the endpoints can be tested without a model.@@ -29,7 +33,7 @@ async function createInternalAgent(asOwner: Api, name: string, username: string)}// Seeds a chat thread owned by resourceId, bound to the agent, with an optional-// transcript. Mirrors what a real run persists (createChatThread up front, then the+// transcript. Mirrors what a real run persists (ensureThread up front, then the// exchanged messages).async function seedThread(threadId: string,@@ -38,10 +42,10 @@ async function seedThread(title: string,turns: Array<{ role: 'user' | 'assistant'; text: string }> = [],) {- await createChatThread(+ await ensureThread(threadId,resourceId,- { agentId: agent.id, projectId: agent.projectId },+ { agentId: agent.id, projectId: agent.projectId, kind: 'chat' },title,);if (turns.length === 0) return;@@ -64,6 +68,12 @@ async function seedThread(});}+// Whether the thread is still in the memory store. Deletion has no read endpoint of+// its own for a thread the caller does not own, so it is checked through the store.+async function threadExists(threadId: string): Promise<boolean> {+ return (await buildMemory(20).getThreadById({ threadId })) != null;+}+describe('agent chat history', () => {beforeEach(async () => {await resetDb();@@ -216,4 +226,118 @@ describe('agent chat history', () => {.messages.get();expect(res.status).toBe(404);});++ it("deletes the caller's thread with its messages", async () => {+ const { owner, asOwner } = await setup();+ const agent = await createInternalAgent(asOwner, 'Design Bot', 'design');+ await seedThread('mine', owner.userId, agent, 'mine', [{ role: 'user', text: 'hello' }]);++ const res = await agents(asOwner)({ agentId: agent.id }).threads({ threadId: 'mine' }).delete();+ expect(res.status).toBe(204);++ const list = await agents(asOwner)({ agentId: agent.id }).threads.get();+ expect(list.data).toEqual([]);+ const messages = await agents(asOwner)({ agentId: agent.id })+ .threads({ threadId: 'mine' })+ .messages.get();+ expect(messages.status).toBe(404);+ });++ it("404s deleting another user's thread, leaving it readable for its owner", async () => {+ const { asOwner } = await setup();+ const agent = await createInternalAgent(asOwner, 'Design Bot', 'design');+ await seedThread('theirs', 'another-user-id', agent, 'theirs', [+ { role: 'user', text: 'secret' },+ ]);++ const res = await agents(asOwner)({ agentId: agent.id })+ .threads({ threadId: 'theirs' })+ .delete();+ expect(res.status).toBe(404);+ expect(await threadExists('theirs')).toBe(true);+ });++ it('404s deleting a thread that does not exist', async () => {+ const { asOwner } = await setup();+ const agent = await createInternalAgent(asOwner, 'Design Bot', 'design');++ const res = await agents(asOwner)({ agentId: agent.id }).threads({ threadId: 'nope' }).delete();+ expect(res.status).toBe(404);+ });++ it('denies a non-member the delete with 403', async () => {+ const { owner, asOwner } = await setup();+ const agent = await createInternalAgent(asOwner, 'Design Bot', 'design');+ await seedThread('mine', owner.userId, agent, 'mine');+ const outsider = await signUpTestUser({ name: 'Outsider' });++ const res = await agents(authedApi(outsider.cookie))({ agentId: agent.id })+ .threads({ threadId: 'mine' })+ .delete();+ expect(res.status).toBe(403);+ expect(await threadExists('mine')).toBe(true);+ });++ it("404s a run continuing another user's chat thread", async () => {+ const { asOwner } = await setup();+ const agent = await createInternalAgent(asOwner, 'Design Bot', 'design');+ await seedThread(`chat:${agent.id}:another-user-id:t1`, 'another-user-id', agent, 'theirs');++ const res = await agents(asOwner)({ agentId: agent.id }).run.post({+ prompt: 'what did they ask?',+ threadId: `chat:${agent.id}:another-user-id:t1`,+ });+ expect(res.status).toBe(404);+ });++ it("404s a streamed run continuing another user's chat thread", async () => {+ const { asOwner } = await setup();+ const agent = await createInternalAgent(asOwner, 'Design Bot', 'design');+ await seedThread(`chat:${agent.id}:another-user-id:t1`, 'another-user-id', agent, 'theirs');++ const res = await agents(asOwner)({ agentId: agent.id }).run.stream.post({+ prompt: 'what did they ask?',+ threadId: `chat:${agent.id}:another-user-id:t1`,+ });+ expect(res.status).toBe(404);+ });++ it("404s a run continuing another agent's chat thread of the same user", async () => {+ const { owner, asOwner } = await setup();+ const a = await createInternalAgent(asOwner, 'Bot A', 'bota');+ const b = await createInternalAgent(asOwner, 'Bot B', 'botb');+ await seedThread(`chat:${a.id}:${owner.userId}:t1`, owner.userId, a, 'with a');++ const res = await agents(asOwner)({ agentId: b.id }).run.post({+ prompt: 'what did I ask A?',+ threadId: `chat:${a.id}:${owner.userId}:t1`,+ });+ expect(res.status).toBe(404);+ });++ it('404s a run handed the thread of an autonomous run', async () => {+ const { asOwner } = await setup();+ const agent = await createInternalAgent(asOwner, 'Design Bot', 'design');++ for (const threadId of [`issue:1:${agent.id}`, 'schedule:1', 'run:1']) {+ const res = await agents(asOwner)({ agentId: agent.id }).run.post({+ prompt: 'what did you do?',+ threadId,+ });+ expect(res.status).toBe(404);+ }+ });++ it("accepts the caller's own chat thread id and fails later on the model config", async () => {+ const { owner, asOwner } = await setup();+ const agent = await createInternalAgent(asOwner, 'Design Bot', 'design');++ // The agent has no model credential, so the run stops at 400 — past the thread+ // check, which is what this asserts.+ const res = await agents(asOwner)({ agentId: agent.id }).run.post({+ prompt: 'hello',+ threadId: `chat:${agent.id}:${owner.userId}:t1`,+ });+ expect(res.status).toBe(400);+ });});diff --git a/apps/api/src/ai-agents/__tests__/integration/thread-cleanup.test.ts b/apps/api/src/ai-agents/__tests__/integration/thread-cleanup.test.tsnew file mode 100644index 00000000..346ebf76--- /dev/null+++ b/apps/api/src/ai-agents/__tests__/integration/thread-cleanup.test.ts@@ -0,0 +1,184 @@+import { describe, it, expect, beforeEach } from 'bun:test';+import { db } from '@repo/db';+import { sql } from 'drizzle-orm';+import { authedApi, type Api } from '../../../__tests__/helpers/app';+import { signUpTestUser } from '../../../__tests__/helpers/auth';+import { resetDb } from '../../../__tests__/helpers/db';+import { ensureThread, buildMemory } from '../../runtime/memory';++// Agent conversation threads live in Mastra's tables, which carry no foreign key of+// ours, so they are deleted explicitly when what they are bound to goes away: the+// agent, its project, or (for an issue run's thread) the issue being archived.+//+// The runtime is not exercised — a live model call would be needed to produce a thread+// — so threads are seeded through the memory module the same way a run creates them.++async function setup() {+ const owner = await signUpTestUser({ name: 'Owner' });+ const asOwner = authedApi(owner.cookie);+ await asOwner.projects.post({ key: 'MKT', name: 'Marketing' });+ const view = await asOwner.projects({ projectKey: 'MKT' }).get();+ return { owner, asOwner, columnId: view.data!.columns[0].id };+}++const agents = (api: Api) => api.projects({ projectKey: 'MKT' })['ai-agents'];++async function createInternalAgent(asOwner: Api, name: string, username: string) {+ const res = await agents(asOwner).post({ name, username, kind: 'internal' });+ return res.data!.agent;+}++async function createIssue(asOwner: Api, columnId: number, title: string) {+ const res = await asOwner.projects({ projectKey: 'MKT' }).issues.post({ columnId, title });+ return res.data!;+}++async function seedChatThread(+ threadId: string,+ resourceId: string,+ agent: { id: number; projectId: number },+) {+ await ensureThread(+ threadId,+ resourceId,+ { agentId: agent.id, projectId: agent.projectId, kind: 'chat' },+ 'chat',+ );+}++async function seedIssueThread(agent: { id: number; projectId: number }, issueId: number) {+ const threadId = `issue:${issueId}:${agent.id}`;+ await ensureThread(+ threadId,+ 'agent-bot',+ { agentId: agent.id, projectId: agent.projectId, kind: 'run', issueId },+ 'run',+ );+ return threadId;+}++async function seedScheduleThread(agent: { id: number; projectId: number }, scheduleId: number) {+ const threadId = `schedule:${scheduleId}`;+ await ensureThread(+ threadId,+ 'agent-bot',+ { agentId: agent.id, projectId: agent.projectId, kind: 'run', scheduleId },+ 'run',+ );+ return threadId;+}++const memory = () => buildMemory(20);++async function threadExists(threadId: string): Promise<boolean> {+ return (await memory().getThreadById({ threadId })) != null;+}++// Messages of a deleted thread cannot be read through the memory API (it resolves the+// thread first), so they are counted in Mastra's own table.+async function messageCount(threadId: string): Promise<number> {+ const rows = (await db.execute(+ sql`SELECT count(*)::int AS n FROM mastra_messages WHERE thread_id = ${threadId}`,+ )) as unknown as Array<{ n: number }>;+ return rows[0].n;+}++// Adds one message so the delete is seen to take the transcript with it.+async function seedMessage(threadId: string, resourceId: string) {+ await memory().saveMessages({+ messages: [+ {+ id: crypto.randomUUID(),+ role: 'user' as const,+ type: 'text' as const,+ threadId,+ resourceId,+ createdAt: new Date(),+ content: { format: 2 as const, parts: [{ type: 'text' as const, text: 'hi' }] },+ },+ ],+ });+}++describe('agent thread cleanup', () => {+ beforeEach(async () => {+ await resetDb();+ });++ it("deletes an agent's chat and run threads with their messages", async () => {+ const { owner, asOwner, columnId } = await setup();+ const agent = await createInternalAgent(asOwner, 'Design Bot', 'design');+ const other = await createInternalAgent(asOwner, 'Other Bot', 'other');+ const issue = await createIssue(asOwner, columnId, 'Ship it');+ await seedChatThread(`chat:${agent.id}:${owner.userId}:t1`, owner.userId, agent);+ const runThread = await seedIssueThread(agent, issue.id);+ await seedMessage(runThread, 'agent-bot');+ expect(await messageCount(runThread)).toBe(1);+ await seedChatThread(`chat:${other.id}:${owner.userId}:t1`, owner.userId, other);++ const res = await agents(asOwner)({ agentId: agent.id }).delete();+ expect(res.status).toBe(204);++ expect(await threadExists(`chat:${agent.id}:${owner.userId}:t1`)).toBe(false);+ expect(await threadExists(runThread)).toBe(false);+ expect(await messageCount(runThread)).toBe(0);+ // Another agent's threads are untouched.+ expect(await threadExists(`chat:${other.id}:${owner.userId}:t1`)).toBe(true);+ });++ it("deletes the threads of a project's agents when the project is deleted", async () => {+ const { owner, asOwner, columnId } = await setup();+ const agent = await createInternalAgent(asOwner, 'Design Bot', 'design');+ const issue = await createIssue(asOwner, columnId, 'Ship it');+ await seedChatThread(`chat:${agent.id}:${owner.userId}:t1`, owner.userId, agent);+ const runThread = await seedIssueThread(agent, issue.id);++ const res = await asOwner.projects({ projectKey: 'MKT' }).delete();+ expect(res.status).toBe(204);++ expect(await threadExists(`chat:${agent.id}:${owner.userId}:t1`)).toBe(false);+ expect(await threadExists(runThread)).toBe(false);+ });++ it("deletes a schedule's run thread when the schedule is deleted", async () => {+ const { asOwner } = await setup();+ const agent = await createInternalAgent(asOwner, 'Design Bot', 'design');+ const schedules = asOwner.projects({ projectKey: 'MKT' })['agent-schedules'];+ const created = await schedules.post({+ agentId: agent.id,+ name: 'Daily digest',+ prompt: 'Summarise the board',+ cron: '0 9 * * *',+ });+ const scheduleId = created.data!.id;+ const thread = await seedScheduleThread(agent, scheduleId);+ await seedMessage(thread, 'agent-bot');++ const res = await schedules({ scheduleId }).delete();+ expect(res.status).toBe(204);++ expect(await threadExists(thread)).toBe(false);+ expect(await messageCount(thread)).toBe(0);+ });++ it("deletes an issue's run threads when it is archived", async () => {+ const { asOwner, columnId } = await setup();+ const a = await createInternalAgent(asOwner, 'Bot A', 'bota');+ const b = await createInternalAgent(asOwner, 'Bot B', 'botb');+ const issue = await createIssue(asOwner, columnId, 'Ship it');+ const other = await createIssue(asOwner, columnId, 'Keep it');+ const threadA = await seedIssueThread(a, issue.id);+ const threadB = await seedIssueThread(b, issue.id);+ await seedMessage(threadA, 'agent-bot');+ expect(await messageCount(threadA)).toBe(1);+ const untouched = await seedIssueThread(a, other.id);++ const res = await asOwner.issues({ issueId: issue.id }).archive.post();+ expect(res.status).toBe(200);++ expect(await threadExists(threadA)).toBe(false);+ expect(await threadExists(threadB)).toBe(false);+ expect(await messageCount(threadA)).toBe(0);+ expect(await threadExists(untouched)).toBe(true);+ });+});diff --git a/apps/api/src/ai-agents/__tests__/unit/thread-ids.test.ts b/apps/api/src/ai-agents/__tests__/unit/thread-ids.test.tsnew file mode 100644index 00000000..214afda0--- /dev/null+++ b/apps/api/src/ai-agents/__tests__/unit/thread-ids.test.ts@@ -0,0 +1,57 @@+import { describe, it, expect } from 'bun:test';+import {+ newChatThreadId,+ isChatThreadId,+ isOwnChatThread,+ runThreadId,+} from '../../runtime/thread-ids';++describe('runThreadId', () => {+ const base = { id: 7, agentId: 3, issueId: null, scheduleId: null };++ it('scopes an issue run to the (issue, agent) pair', () => {+ expect(runThreadId({ ...base, issueId: 42 })).toBe('issue:42:3');+ });++ it('keeps two agents on the same issue apart', () => {+ expect(runThreadId({ ...base, issueId: 42, agentId: 4 })).not.toBe(+ runThreadId({ ...base, issueId: 42 }),+ );+ });++ it('scopes a scheduled run to its schedule, whatever triggered it', () => {+ expect(runThreadId({ ...base, scheduleId: 9 })).toBe('schedule:9');+ });++ it('prefers the issue over the schedule', () => {+ expect(runThreadId({ ...base, issueId: 42, scheduleId: 9 })).toBe('issue:42:3');+ });++ it('falls back to the run itself with neither', () => {+ expect(runThreadId(base)).toBe('run:7');+ });+});++describe('chat thread ids', () => {+ it('carries the agent and the user, and a unique id per conversation', () => {+ const first = newChatThreadId(3, 'user-1');+ expect(first.startsWith('chat:3:user-1:')).toBe(true);+ expect(newChatThreadId(3, 'user-1')).not.toBe(first);+ });++ it('recognises its own chat threads and rejects everything else', () => {+ const mine = newChatThreadId(3, 'user-1');+ expect(isOwnChatThread(mine, 3, 'user-1')).toBe(true);+ expect(isOwnChatThread(mine, 4, 'user-1')).toBe(false);+ expect(isOwnChatThread(mine, 3, 'user-2')).toBe(false);+ expect(isOwnChatThread('issue:42:3', 3, 'user-1')).toBe(false);+ expect(isOwnChatThread('schedule:9', 3, 'user-1')).toBe(false);+ });++ it('separates a chat thread from a run thread', () => {+ expect(isChatThreadId(newChatThreadId(3, 'user-1'))).toBe(true);+ expect(isChatThreadId('issue:42:3')).toBe(false);+ expect(isChatThreadId('schedule:9')).toBe(false);+ expect(isChatThreadId('run:7')).toBe(false);+ });+});diff --git a/apps/api/src/ai-agents/internal-routes.ts b/apps/api/src/ai-agents/internal-routes.tsindex 91191753..eaadd02e 100644--- a/apps/api/src/ai-agents/internal-routes.ts+++ b/apps/api/src/ai-agents/internal-routes.ts@@ -1,5 +1,7 @@import { Elysia, t } from 'elysia';import { runAgent } from './runtime';+import { deleteThreadsWhere } from './runtime/memory';+import { runThreadId } from './runtime/thread-ids';import { framePrompt, runModePreamble, peopleContext } from './prompt/framing';const runBody = t.Object({@@ -19,20 +21,44 @@ const runBody = t.Object({requesterName: t.Nullable(t.String()),});-export const internalAgentRunRoutes = new Elysia({ name: 'internal-agent-runs' }).post(- '/internal/agent-runs/execute',- async ({ body, headers, set }) => {- const expected = process.env.WORKER_INTERNAL_TOKEN;- if (!expected || headers['x-worker-token'] !== expected) {- set.status = 401;- return { error: 'Unauthorized' };- }- const result = await runAgent(body.agentId, body.projectId, framePrompt(body), {- callerUserId: body.agentUserId,- threadId: body.issueId != null ? `issue:${body.issueId}` : `run:${body.id}`,- contextPreamble: runModePreamble(body.trigger) + peopleContext(body),- });- return { output: result.text };- },- { body: runBody },-);+function workerTokenValid(headers: Record<string, string | undefined>): boolean {+ const expected = process.env.WORKER_INTERNAL_TOKEN;+ return !!expected && headers['x-worker-token'] === expected;+}++export const internalAgentRunRoutes = new Elysia({ name: 'internal-agent-runs' })+ .post(+ '/internal/agent-runs/execute',+ async ({ body, headers, set }) => {+ if (!workerTokenValid(headers)) {+ set.status = 401;+ return { error: 'Unauthorized' };+ }+ const result = await runAgent(body.agentId, body.projectId, framePrompt(body), {+ callerUserId: body.agentUserId,+ threadId: runThreadId(body),+ issueId: body.issueId,+ scheduleId: body.scheduleId,+ contextPreamble: runModePreamble(body.trigger) + peopleContext(body),+ });+ return { output: result.text };+ },+ { body: runBody },+ )++ // Deletes the agent memory of archived issues. The worker's auto-archive sweep+ // writes archived_at directly in the database and does not import Mastra, so it+ // asks the api to drop the threads the same way it asks it to run an agent.+ .post(+ '/internal/agent-threads/delete-for-issues',+ async ({ body, headers, set }) => {+ if (!workerTokenValid(headers)) {+ set.status = 401;+ return { error: 'Unauthorized' };+ }+ let deleted = 0;+ for (const issueId of body.issueIds) deleted += await deleteThreadsWhere({ issueId });+ return { deleted };+ },+ { body: t.Object({ issueIds: t.Array(t.Number()) }) },+ );diff --git a/apps/api/src/ai-agents/routes.ts b/apps/api/src/ai-agents/routes.tsindex 0c0dd71a..68fdbfe7 100644--- a/apps/api/src/ai-agents/routes.ts+++ b/apps/api/src/ai-agents/routes.ts@@ -18,9 +18,15 @@ import { runAgent, streamAgent, type RunOpts } from './runtime';import { peoplePreamble } from './prompt/run-context';import type { SessionUser } from '../shared/auth-context';import { listAgentRuns } from './run-queue';-import { listChatThreads, getChatThreadMessages } from './runtime/memory';+import { listChatThreads, getChatThreadMessages, deleteChatThread } from './runtime/memory';+import { isOwnChatThread } from './runtime/thread-ids';const agentParams = t.Object({ projectKey: t.String(), agentId: t.Numeric() });+const threadParams = t.Object({+ projectKey: t.String(),+ agentId: t.Numeric(),+ threadId: t.String(),+});// Body of the interactive run endpoints. threadId continues a conversation when the// agent has memory enabled; omit it to start a new thread (the id used is returned in@@ -31,9 +37,14 @@ const runBody = t.Object({});// Run options for an interactive chat run (the test chat): the caller owns the memory-// thread and is named to the agent as the requester.-function chatRunOpts(user: SessionUser | null, threadId?: string): RunOpts {+// thread and is named to the agent as the requester. A supplied thread id must be one+// issued to this caller for this agent — anyone else's chat, and the threads of the+// autonomous runs, read as not found.+function chatRunOpts(user: SessionUser | null, agentId: number, threadId?: string): RunOpts {const caller = requireUser(user);+ if (threadId != null && !isOwnChatThread(threadId, agentId, caller.id)) {+ throw new HttpError(404, 'Thread not found');+ }return {callerUserId: caller.id,threadId: threadId ?? null,@@ -373,7 +384,12 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A.post('/projects/:projectKey/ai-agents/:agentId/run',async ({ params, project, body, user }) =>- runAgent(params.agentId, project.id, body.prompt, chatRunOpts(user, body.threadId)),+ runAgent(+ params.agentId,+ project.id,+ body.prompt,+ chatRunOpts(user, params.agentId, body.threadId),+ ),{body: runBody,params: agentParams,@@ -404,7 +420,7 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['Aparams.agentId,project.id,body.prompt,- chatRunOpts(user, body.threadId),+ chatRunOpts(user, params.agentId, body.threadId),);const encoder = new TextEncoder();const stream = new ReadableStream<Uint8Array>({@@ -483,7 +499,7 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['Areturn messages;},{- params: t.Object({ projectKey: t.String(), agentId: t.Numeric(), threadId: t.String() }),+ params: threadParams,query: t.Object({ page: t.Optional(t.Numeric({ minimum: 0 })) }),permission: ['ai_agents', 'read'],response: {@@ -495,4 +511,31 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A},detail: { summary: 'Get thread messages' },},+ )++ // Deletes one of the caller's chat threads with its messages. Scoped the same way as+ // reading it: a thread owned by another user is a 404.+ .delete(+ '/projects/:projectKey/ai-agents/:agentId/threads/:threadId',+ async ({ params, project, user }) => {+ const caller = requireUser(user);+ const agent = await getAgentById(params.agentId, project.id);+ if (!agent) throw new HttpError(404, 'Agent not found');+ if (!(await deleteChatThread(params.threadId, caller.id))) {+ throw new HttpError(404, 'Thread not found');+ }+ return noContent();+ },+ {+ params: threadParams,+ permission: ['ai_agents', 'read'],+ response: {+ 204: t.Void(),+ 400: ErrorResponse,+ 401: ErrorResponse,+ 403: ErrorResponse,+ 404: ErrorResponse,+ },+ detail: { summary: 'Delete a chat thread' },+ },);diff --git a/apps/api/src/ai-agents/runtime/index.ts b/apps/api/src/ai-agents/runtime/index.tsindex 633655e4..9c6e06a5 100644--- a/apps/api/src/ai-agents/runtime/index.ts+++ b/apps/api/src/ai-agents/runtime/index.ts@@ -8,7 +8,8 @@ import { buildCustomTools } from './tools/custom-tools';import { buildRouteTools } from './tools/route-tools';import { buildLocalTools } from './tools/local';import { buildSkillTool, skillsPreamble } from './skill-runtime';-import { buildMemory, createChatThread, DEFAULT_LAST_MESSAGES } from './memory';+import { buildMemory, ensureThread, DEFAULT_LAST_MESSAGES } from './memory';+import { isChatThreadId, newChatThreadId } from './thread-ids';import { errorMessage } from '../helpers/errors';import { HttpError } from '../../shared/lib';@@ -195,31 +196,51 @@ async function prepareRun(}const agent = await buildAgent(row, opts.contextPreamble ?? '');- // Mastra's generate/stream have overloaded options; type the shape we use.+ // Mastra's generate/stream have overloaded options; type the shape we use. In+ // Mastra v1 the temperature belongs to the call's model settings — a flat+ // `temperature` option is only read by the legacy generate.const options: RunOptions = { maxSteps: row.maxSteps ?? DEFAULT_MAX_STEPS };+ if (row.temperature != null) options.modelSettings = { temperature: row.temperature };let threadId: string | null = null;if (row.memoryEnabled) {- // A new chat thread (no threadId supplied) is created up front with its- // agent/project binding and a title, so the chat history can list it. A- // supplied threadId continues an existing thread (chat or issue-triggered) and- // is left untouched. The threadId used is returned so the caller can continue.- const isNew = !opts.threadId;- threadId = opts.threadId ?? crypto.randomUUID();- if (isNew) {- await createChatThread(threadId, opts.callerUserId, { agentId: row.id, projectId }, prompt);- }+ // A chat run with no threadId starts a new conversation; every other run continues+ // the thread its caller named (see thread-ids). The thread is created up front with+ // what it is bound to and a title, so the chat history can list it and deleting the+ // agent, project or issue can find it. The threadId used is returned so the caller+ // can continue.+ threadId = opts.threadId ?? newChatThreadId(row.id, opts.callerUserId);+ await ensureThread(+ threadId,+ opts.callerUserId,+ {+ agentId: row.id,+ projectId,+ kind: isChatThreadId(threadId) ? 'chat' : 'run',+ ...(opts.issueId != null ? { issueId: opts.issueId } : {}),+ ...(opts.scheduleId != null ? { scheduleId: opts.scheduleId } : {}),+ },+ prompt,+ );options.memory = { thread: threadId, resource: opts.callerUserId };}return { agent, options, threadId };}// Options for a single run. callerUserId owns the memory thread; threadId continues a-// conversation (memory-enabled agents only); contextPreamble is the caller-assembled-// human-context block (see run-context.ts) prepended to the agent's instructions.+// conversation (memory-enabled agents only); issueId and scheduleId bind an autonomous+// run's thread to what it runs on, so deleting that deletes the thread; contextPreamble+// is the caller-assembled human-context block (see run-context.ts) prepended to the+// agent's instructions.export type RunOpts = {callerUserId: string;threadId?: string | null;+ issueId?: number | null;+ scheduleId?: number | null;contextPreamble?: string;};-type RunOptions = { maxSteps: number; memory?: { thread: string; resource: string } };+type RunOptions = {+ maxSteps: number;+ modelSettings?: { temperature: number };+ memory?: { thread: string; resource: string };+};diff --git a/apps/api/src/ai-agents/runtime/memory.ts b/apps/api/src/ai-agents/runtime/memory.tsindex 0df1f146..16c61e62 100644--- a/apps/api/src/ai-agents/runtime/memory.ts+++ b/apps/api/src/ai-agents/runtime/memory.ts@@ -8,12 +8,13 @@ import { toIso } from '../helpers/dates';// messages of the given thread. Only the recency window is used (no semantic// recall), so no vector store is required.//-// A chat thread carries metadata that binds it to the agent and project it belongs-// to (agentId, projectId, kind: "chat"), set when the thread is first created. This-// lets the chat UI list a user's own past conversations with one agent: the thread's-// resourceId is the caller's user id, so filtering by (resourceId, agentId) returns-// exactly that user's threads with that agent. Threads created by issue-triggered-// runs carry no such metadata and are owned by the agent bot, so they never appear.+// Every thread carries metadata binding it to what it belongs to: the agent and+// project always, the issue or schedule for an autonomous run, plus the kind (a UI+// chat or a run). Two things read it. The chat history lists a user's own+// conversations with one agent — the thread's resourceId is the caller's user id, so+// filtering by (resourceId, agentId, kind "chat") returns exactly those. And deleting+// any of those bindings deletes the threads bound to it, since Mastra's tables carry+// no foreign keys of ours.// Default recency window when an agent has memory enabled but no count set.export const DEFAULT_LAST_MESSAGES = 20;@@ -46,32 +47,59 @@ function getReadMemory(): Memory {return readMemory;}-// Metadata written on a chat thread when it is created. `kind: "chat"` marks the-// thread as a UI conversation (as opposed to an issue-triggered run thread).-type ChatThreadMeta = { agentId: number; projectId: number; kind: 'chat' };+// What a thread is bound to, written when it is created. `kind` separates a UI+// conversation from an autonomous run thread; `issueId` and `scheduleId` are set for+// an issue run and a scheduled run.+type ThreadMeta = {+ agentId: number;+ projectId: number;+ kind: 'chat' | 'run';+ issueId?: number;+ scheduleId?: number;+};-// Creates the chat thread up front with its agent/project binding and an initial-// title (the first prompt, truncated). Called only when a new chat thread starts,-// so continuing an existing thread does not overwrite its metadata or title.-export async function createChatThread(+// Creates the thread with its bindings and an initial title (the first prompt,+// truncated) unless it already exists, so continuing a conversation leaves its+// metadata and title alone.+export async function ensureThread(threadId: string,resourceId: string,- meta: { agentId: number; projectId: number },+ meta: ThreadMeta,title: string,): Promise<void> {- await getReadMemory().createThread({+ const memory = getReadMemory();+ if (await memory.getThreadById({ threadId })) return;+ await memory.createThread({threadId,resourceId,title: title.slice(0, 80),- metadata: {- agentId: meta.agentId,- projectId: meta.projectId,- kind: 'chat',- } satisfies ChatThreadMeta,+ metadata: meta,saveThread: true,});}+// Deletes one of the caller's chat threads with its messages. Returns false when the+// thread does not exist or belongs to someone else, so the caller maps it to a 404.+export async function deleteChatThread(threadId: string, resourceId: string): Promise<boolean> {+ const memory = getReadMemory();+ const thread = await memory.getThreadById({ threadId, resourceId });+ if (!thread) return false;+ await memory.deleteThread(threadId);+ return true;+}++// Deletes every thread bound to the given agent, project, issue or schedule, with its+// messages, and returns how many were deleted. Called when that binding goes away.+export async function deleteThreadsWhere(+ binding:+ { agentId: number } | { projectId: number } | { issueId: number } | { scheduleId: number },+): Promise<number> {+ const memory = getReadMemory();+ const { threads } = await memory.listThreads({ filter: { metadata: binding }, perPage: false });+ for (const thread of threads) await memory.deleteThread(thread.id);+ return threads.length;+}+// One chat thread in the history list.export type ChatThreadSummary = {id: string;diff --git a/apps/api/src/ai-agents/runtime/thread-ids.ts b/apps/api/src/ai-agents/runtime/thread-ids.tsnew file mode 100644index 00000000..7acb7425--- /dev/null+++ b/apps/api/src/ai-agents/runtime/thread-ids.ts@@ -0,0 +1,36 @@+// Conversation thread ids. The id says what the conversation is scoped to, so a run+// picks the thread it continues without a lookup, and a chat thread is checked against+// its caller by reading the id alone.++// A chat thread belongs to one (agent, user) pair; the uuid separates a user's several+// conversations with the same agent.+export function newChatThreadId(agentId: number, userId: string): string {+ return `chat:${agentId}:${userId}:${crypto.randomUUID()}`;+}++export function isChatThreadId(threadId: string): boolean {+ return threadId.startsWith('chat:');+}++// Whether the chat thread id was issued for this (agent, caller) pair. A caller can+// only mint an id carrying their own user id, so a mismatch means the thread is someone+// else's chat or an autonomous run thread, and the caller gets a 404.+export function isOwnChatThread(threadId: string, agentId: number, userId: string): boolean {+ return threadId.startsWith(`chat:${agentId}:${userId}:`);+}++// The thread an autonomous run continues: one per (agent, issue) for an issue run, one+// per schedule for a scheduled run (a schedule belongs to a single agent, so its id+// already names the agent). Repeated runs then build on what the agent did before, and+// a retry sees how the failed attempt ended. The run-scoped id is the fallback for a+// run with neither, which nothing enqueues today — both columns are nullable.+export function runThreadId(run: {+ id: number;+ agentId: number;+ issueId: number | null;+ scheduleId: number | null;+}): string {+ if (run.issueId != null) return `issue:${run.issueId}:${run.agentId}`;+ if (run.scheduleId != null) return `schedule:${run.scheduleId}`;+ return `run:${run.id}`;+}diff --git a/apps/api/src/ai-agents/store.ts b/apps/api/src/ai-agents/store.tsindex 0f7becf0..0bd6b23f 100644--- a/apps/api/src/ai-agents/store.ts+++ b/apps/api/src/ai-agents/store.ts@@ -13,6 +13,7 @@ import { auth } from '@repo/auth';import { iso, rethrowDuplicate } from '../shared/lib';import { encryptSecret, decryptSecret } from '@repo/crypto';import { normalizeToolKeys, ALWAYS_ON_ACTIONS } from './runtime/tools/catalog';+import { deleteThreadsWhere } from './runtime/memory';// Data access for AI agents. Each agent is backed by a hidden bot user// (ai_agent.user_id -> user.id): that user is what a work item is assigned to,@@ -473,12 +474,14 @@ export async function regenerateKey(id: number, projectId: number): Promise<strireturn apiKey;}-// Deletes an agent: its API key row(s), then the bot user. Deleting the user-// cascades to the ai_agent row (ON DELETE CASCADE on user_id), sets assignee_user_id-// to NULL on every issue the agent was on, and nulls the actor on its activity.+// Deletes an agent: its conversation threads, its API key row(s), then the bot user.+// Deleting the user cascades to the ai_agent row (ON DELETE CASCADE on user_id), sets+// assignee_user_id to NULL on every issue the agent was on, and nulls the actor on its+// activity.export async function deleteAgent(id: number, projectId: number): Promise<boolean> {const agent = await getAgentById(id, projectId);if (!agent) return false;+ await deleteThreadsWhere({ agentId: id });await db.delete(apikey).where(eq(apikey.referenceId, agent.userId));await db.delete(user).where(eq(user.id, agent.userId));return true;diff --git a/apps/api/src/issues/store.ts b/apps/api/src/issues/store.tsindex 46927280..71ae1129 100644--- a/apps/api/src/issues/store.ts+++ b/apps/api/src/issues/store.ts@@ -43,6 +43,7 @@ import { mapAttachment, type AttachmentRow } from '../attachments/store';import { notifyIssueChange } from '../notifications/store';import { emitWebhookEvent } from '../webhooks/emit';import { getAssignTriggerAgent, isProjectAgent } from '../ai-agents/store';+import { deleteThreadsWhere } from '../ai-agents/runtime/memory';import { getInitiativeProjectId } from '../initiatives/store';import { getMembership } from '../members/store';import { enqueueAgentRun } from '../ai-agents/run-queue';@@ -376,6 +377,9 @@ export async function searchIssues(// the row for restore. Idempotent (archiving an archived issue is a no-op re-stamp// avoided by the archived_at guard). Records a feed entry. Returns the updated// issue, or null if it does not exist.+//+// The agents' conversation threads for the issue are deleted with it. Archiving is+// reversible and this is not: a restored issue starts with empty agent memory.export async function archiveIssue(id: number,actorUserId?: string | null,@@ -390,6 +394,7 @@ export async function archiveIssue(return getIssue(id);}await recordActivity(id, [{ action: 'archived' }], actorUserId);+ await deleteThreadsWhere({ issueId: id });return getIssue(id);}diff --git a/apps/api/src/projects/store.ts b/apps/api/src/projects/store.tsindex 50e6de74..b7b00f5f 100644--- a/apps/api/src/projects/store.ts+++ b/apps/api/src/projects/store.ts@@ -16,6 +16,7 @@ import {type Permissions,} from '../shared/permissions';import { getProjectSetting, setProjectSetting } from '../settings/store';+import { deleteThreadsWhere } from '../ai-agents/runtime/memory';// Data access for projects: the top-level container that groups its own columns,// issue types, labels, assignees, custom fields, issues, saved views, and@@ -353,7 +354,10 @@ export async function setAutoArchiveSettings(// actions, which in turn cascade to their own dependents (an issue's labels, field// values/options, attachments, and activity; a custom field's values). The// issue.column_id foreign key is NO ACTION, checked at end of statement — both the-// issues and their columns are deleted by the same cascade, so it is satisfied.+// issues and their columns are deleted by the same cascade, so it is satisfied. The+// conversation threads of the project's agents are deleted first, since they live+// outside those cascades.export async function deleteProject(projectId: number): Promise<void> {+ await deleteThreadsWhere({ projectId });await db.delete(project).where(eq(project.id, projectId));}diff --git a/apps/web/src/features/ai-chat/AiChatPage.tsx b/apps/web/src/features/ai-chat/AiChatPage.tsxindex bd65b54b..b798145e 100644--- a/apps/web/src/features/ai-chat/AiChatPage.tsx+++ b/apps/web/src/features/ai-chat/AiChatPage.tsx@@ -27,6 +27,7 @@ export default function AiChatPage() {selectThread,startNewChat,handleThreadCreated,+ handleThreadDeleted,} = useAiChatSelection(project?.project.key ?? null);if (!project) return null;@@ -80,6 +81,7 @@ export default function AiChatPage() {agentId={selected.id}selectedThreadId={selectedThreadId}onSelect={selectThread}+ onDeleted={handleThreadDeleted}onNewChat={startNewChat}/><div className="flex min-h-0 flex-1 flex-col">diff --git a/apps/web/src/features/ai-chat/components/floating/FloatingChat.tsx b/apps/web/src/features/ai-chat/components/floating/FloatingChat.tsxindex 79518d8c..b8345df9 100644--- a/apps/web/src/features/ai-chat/components/floating/FloatingChat.tsx+++ b/apps/web/src/features/ai-chat/components/floating/FloatingChat.tsx@@ -36,6 +36,7 @@ export function FloatingChat({selectThread,startNewChat,handleThreadCreated,+ handleThreadDeleted,} = useAiChatSelection(project?.project.key ?? null);const [view, setView] = useState<'chat' | 'history'>('chat');@@ -104,6 +105,7 @@ export function FloatingChat({agentId={selected.id}selectedThreadId={selectedThreadId}onSelect={handleSelectThread}+ onDeleted={handleThreadDeleted}onBack={() => setView('chat')}/></div>diff --git a/apps/web/src/features/ai-chat/components/floating/FloatingChatHistory.tsx b/apps/web/src/features/ai-chat/components/floating/FloatingChatHistory.tsxindex b6cdc5ac..7fe31a71 100644--- a/apps/web/src/features/ai-chat/components/floating/FloatingChatHistory.tsx+++ b/apps/web/src/features/ai-chat/components/floating/FloatingChatHistory.tsx@@ -10,12 +10,14 @@ export function FloatingChatHistory({agentId,selectedThreadId,onSelect,+ onDeleted,onBack,}: {projectKey: string;agentId: number;selectedThreadId: string | null;onSelect: (threadId: string) => void;+ onDeleted: (threadId: string) => void;onBack: () => void;}) {return (@@ -39,6 +41,7 @@ export function FloatingChatHistory({agentId={agentId}selectedThreadId={selectedThreadId}onSelect={onSelect}+ onDeleted={onDeleted}/></div>);diff --git a/apps/web/src/features/ai-chat/components/page/AiChatThreadRail.tsx b/apps/web/src/features/ai-chat/components/page/AiChatThreadRail.tsxindex 35366889..b974d741 100644--- a/apps/web/src/features/ai-chat/components/page/AiChatThreadRail.tsx+++ b/apps/web/src/features/ai-chat/components/page/AiChatThreadRail.tsx@@ -11,12 +11,14 @@ export function AiChatThreadRail({agentId,selectedThreadId,onSelect,+ onDeleted,onNewChat,}: {projectKey: string;agentId: number;selectedThreadId: string | null;onSelect: (threadId: string) => void;+ onDeleted: (threadId: string) => void;onNewChat: () => void;}) {return (@@ -39,6 +41,7 @@ export function AiChatThreadRail({agentId={agentId}selectedThreadId={selectedThreadId}onSelect={onSelect}+ onDeleted={onDeleted}/></div>);diff --git a/apps/web/src/features/ai-chat/components/shared/AiChatThreadItem.tsx b/apps/web/src/features/ai-chat/components/shared/AiChatThreadItem.tsxnew file mode 100644index 00000000..c5c03bb3--- /dev/null+++ b/apps/web/src/features/ai-chat/components/shared/AiChatThreadItem.tsx@@ -0,0 +1,57 @@+'use client';++import { MessageCircle, Trash2 } from 'lucide-react';+import { formatShortDate } from '@/utils/dates';+import { cn } from '@/lib/utils';+import { Button } from '@/components/ui/button';+import type { AiChatThread } from '@/lib/api';++// One conversation in the chat history list. The delete control sits next to the row+// rather than inside it, so the row stays a single button.+export function AiChatThreadItem({+ thread,+ active,+ onSelect,+ onDelete,+}: {+ thread: AiChatThread;+ active: boolean;+ onSelect: () => void;+ onDelete: () => void;+}) {+ return (+ <div className="group relative">+ <button+ type="button"+ onClick={onSelect}+ aria-pressed={active}+ className={cn(+ 'flex w-full items-start gap-2 rounded-lg py-2 pr-9 pl-2.5 text-left transition-colors',+ active ? 'bg-accent' : 'hover:bg-accent/50',+ )}+ >+ <MessageCircle+ className={cn(+ 'mt-0.5 size-3.5 shrink-0',+ active ? 'text-foreground' : 'text-muted-foreground',+ )}+ />+ <div className="min-w-0 flex-1">+ <div className="truncate text-sm">{thread.title ?? 'New conversation'}</div>+ <div className="text-xs text-muted-foreground">{formatShortDate(thread.updatedAt)}</div>+ </div>+ </button>++ <Button+ variant="ghost"+ size="icon"+ title="Delete conversation"+ onClick={onDelete}+ className="absolute top-1/2 right-1 size-7 -translate-y-1/2 text-muted-foreground opacity-0 group-hover:opacity-100 focus-visible:opacity-100"+ >+ <Trash2 className="size-3.5" />+ <span className="sr-only">Delete conversation</span>+ </Button>+ </div>+ );+}diff --git a/apps/web/src/features/ai-chat/components/shared/AiChatThreadList.tsx b/apps/web/src/features/ai-chat/components/shared/AiChatThreadList.tsxindex 8b312130..01f4e3ee 100644--- a/apps/web/src/features/ai-chat/components/shared/AiChatThreadList.tsx+++ b/apps/web/src/features/ai-chat/components/shared/AiChatThreadList.tsx@@ -1,28 +1,42 @@'use client';-import { MessageCircle } from 'lucide-react';-import { useAgentThreadsQuery } from '@/services/aiAgents.service';-import { formatShortDate } from '@/utils/dates';-import { cn } from '@/lib/utils';+import { useState } from 'react';+import { useAgentThreadsQuery, useDeleteAgentThread } from '@/services/aiAgents.service';import { Skeleton } from '@/components/ui/skeleton';+import ConfirmDialog from '@/components/common/overlay/ConfirmDialog';+import type { AiChatThread } from '@/lib/api';+import { AiChatThreadItem } from './AiChatThreadItem';// The caller's own past conversations with one agent, newest first. Used by both the// AI Chat page's thread rail and the floating chat's history layer; each host supplies// its own header. `selectedThreadId` marks the conversation currently shown; a thread// that has not produced its first reply yet has no id and so is not in this list.+// Deleting a conversation removes it and its messages; `onDeleted` lets the host reset+// the chat when the deleted one was open.export function AiChatThreadList({projectKey,agentId,selectedThreadId,onSelect,+ onDeleted,}: {projectKey: string;agentId: number;selectedThreadId: string | null;onSelect: (threadId: string) => void;+ onDeleted: (threadId: string) => void;}) {const threadsQuery = useAgentThreadsQuery(projectKey, agentId);const threads = threadsQuery.data ?? [];+ const deleteThread = useDeleteAgentThread(projectKey, agentId);+ const [pending, setPending] = useState<AiChatThread | null>(null);++ async function confirmDelete() {+ if (!pending) return;+ await deleteThread.mutateAsync(pending.id);+ setPending(null);+ onDeleted(pending.id);+ }if (threadsQuery.isLoading) {return (@@ -49,35 +63,31 @@ export function AiChatThreadList({}return (- <div className="min-h-0 flex-1 space-y-0.5 overflow-y-auto p-2">- {threads.map((thread) => {- const active = thread.id === selectedThreadId;- return (- <button+ <>+ <div className="min-h-0 flex-1 space-y-0.5 overflow-y-auto p-2">+ {threads.map((thread) => (+ <AiChatThreadItemkey={thread.id}- type="button"- onClick={() => onSelect(thread.id)}- aria-pressed={active}- className={cn(- 'flex w-full items-start gap-2 rounded-lg px-2.5 py-2 text-left transition-colors',- active ? 'bg-accent' : 'hover:bg-accent/50',- )}- >- <MessageCircle- className={cn(- 'mt-0.5 size-3.5 shrink-0',- active ? 'text-foreground' : 'text-muted-foreground',- )}- />- <div className="min-w-0 flex-1">- <div className="truncate text-sm">{thread.title ?? 'New conversation'}</div>- <div className="text-xs text-muted-foreground">- {formatShortDate(thread.updatedAt)}- </div>- </div>- </button>- );- })}- </div>+ thread={thread}+ active={thread.id === selectedThreadId}+ onSelect={() => onSelect(thread.id)}+ onDelete={() => setPending(thread)}+ />+ ))}+ </div>++ {pending && (+ <ConfirmDialog+ title="Delete conversation"+ confirmLabel="Delete"+ onConfirm={confirmDelete}+ onClose={() => setPending(null)}+ >+ <div className="text-sm text-muted-foreground">+ “{pending.title ?? 'New conversation'}” and its messages are deleted permanently.+ </div>+ </ConfirmDialog>+ )}+ </>);}diff --git a/apps/web/src/features/ai-chat/hooks/useAiChatSelection.ts b/apps/web/src/features/ai-chat/hooks/useAiChatSelection.tsindex 1793487c..c5769a32 100644--- a/apps/web/src/features/ai-chat/hooks/useAiChatSelection.ts+++ b/apps/web/src/features/ai-chat/hooks/useAiChatSelection.ts@@ -44,6 +44,12 @@ export function useAiChatSelection(projectKey: string | null) {void qc.invalidateQueries({ queryKey: qk.agentThreads(projectKey, selected.id) });};+ // A deleted conversation cannot be shown: if it was the open one, fall back to a+ // fresh chat.+ const handleThreadDeleted = (threadId: string) => {+ if (threadId === selectedThreadId) startNewChat();+ };+return {agents,isLoading: agentsQuery.isLoading,@@ -55,5 +61,6 @@ export function useAiChatSelection(projectKey: string | null) {selectThread: setSelectedThreadId,startNewChat,handleThreadCreated,+ handleThreadDeleted,};}diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex 9848fb52..76b241d3 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -2167,6 +2167,11 @@ export const api = {request<AiChatMessagePage>(`/projects/${projectKey}/ai-agents/${agentId}/threads/${encodeURIComponent(threadId)}/messages?page=${page}`,),+ deleteAiAgentThread: (projectKey: string, agentId: number, threadId: string) =>+ request<void>(+ `/projects/${projectKey}/ai-agents/${agentId}/threads/${encodeURIComponent(threadId)}`,+ { method: 'DELETE' },+ ),// Integrations: stored credentials for LLM providers and tool integrations. The// secret is write-only — responses carry only a redacted view.diff --git a/apps/web/src/services/aiAgents.service.ts b/apps/web/src/services/aiAgents.service.tsindex c327f334..06020cca 100644--- a/apps/web/src/services/aiAgents.service.ts+++ b/apps/web/src/services/aiAgents.service.ts@@ -54,6 +54,19 @@ export function useAgentThreadMessagesQuery(});}+// Deletes one of the caller's chat threads with an agent and refreshes the history+// list it was in.+export function useDeleteAgentThread(projectKey: string | null, agentId: number | null) {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: (threadId: string) => api.deleteAiAgentThread(projectKey!, agentId!, threadId),+ onSuccess: () => {+ if (projectKey && agentId != null)+ void qc.invalidateQueries({ queryKey: qk.agentThreads(projectKey, agentId) });+ },+ });+}+// The capability-tool catalog for the internal-agent form. Static per project, so// it stays fresh for the session.export function useAgentToolsQuery(projectKey: string | null) {diff --git a/apps/worker/src/agent-runs.ts b/apps/worker/src/agent-runs.tsindex cbaa35db..dc6764c3 100644--- a/apps/worker/src/agent-runs.ts+++ b/apps/worker/src/agent-runs.ts@@ -88,6 +88,22 @@ async function processRun(run: ClaimedRun): Promise<void> {}}+// Drops the agent conversation threads of archived issues. The threads live in+// Mastra's tables, which only the api talks to, so the worker asks it over the same+// internal route it uses to run an agent. The api looks the threads up per issue, so+// the ids go in batches: the first sweep of an instance that just enabled auto-archive+// can carry thousands of them, and one request for all would run past the timeout.+export async function deleteIssueAgentThreads(issueIds: number[]): Promise<void> {+ for (let from = 0; from < issueIds.length; from += 200) {+ const response = await postInternal(+ '/internal/agent-threads/delete-for-issues',+ { issueIds: issueIds.slice(from, from + 200) },+ 30_000,+ );+ if (!response.ok) throw new Error(`Agent API returned ${response.status}`);+ }+}+async function executeRun(run: ClaimedRun): Promise<string> {const response = await postInternal('/internal/agent-runs/execute',diff --git a/apps/worker/src/store.ts b/apps/worker/src/store.tsindex fe7a4b77..a2c4ed87 100644--- a/apps/worker/src/store.ts+++ b/apps/worker/src/store.ts@@ -152,9 +152,10 @@ export async function cleanupOldDeliveries(): Promise<number> {// moving to a terminal column bumps it, and any later edit resets the clock, so an// issue is archived only after the full period with no activity. The ->> is guarded// by a numeric-string regex so a malformed or missing value is treated as disabled,-// never cast. Returns the number archived. Idempotent (archived_at IS NULL filter).-export async function archiveStaleIssues(): Promise<number> {- const res = await db.execute(sql`+// never cast. Returns the ids archived, which the caller uses to drop the agent+// conversation threads of those issues. Idempotent (archived_at IS NULL filter).+export async function archiveStaleIssues(): Promise<number[]> {+ const rows = await db.execute(sql`UPDATE issue iSET archived_at = now()FROM project_column c, project_setting s@@ -171,6 +172,7 @@ export async function archiveStaleIssues(): Promise<number> {AND (s.value->>'canceledDays') ~ '^[0-9]+$'AND i.updated_at < now() - make_interval(days => (s.value->>'canceledDays')::int)))+ RETURNING i.id`);- return (res as unknown as { count?: number }).count ?? 0;+ return (rows as unknown as Array<{ id: number }>).map((row) => row.id);}diff --git a/apps/worker/src/worker.ts b/apps/worker/src/worker.tsindex e587edca..2490f8d8 100644--- a/apps/worker/src/worker.ts+++ b/apps/worker/src/worker.ts@@ -2,6 +2,7 @@ import { workerConfig } from './config';import { deliver } from './delivery';import { processNotificationDeliveries } from './notification-delivery';import { equalJitterBackoffMs } from './backoff';+import { deleteIssueAgentThreads } from './agent-runs';import { startPollLoop, type WorkerHandle } from './poll-loop';import { TELEMETRY_CHECK_EVERY_TICKS, processTelemetry } from './telemetry';import {@@ -42,7 +43,16 @@ async function tick(): Promise<void> {if (++ticksSinceAutoArchive >= cfg.autoArchiveEveryTicks) {ticksSinceAutoArchive = 0;const archived = await archiveStaleIssues();- if (archived > 0) console.log(`[worker] auto-archived ${archived} stale issues`);+ if (archived.length > 0) {+ console.log(`[worker] auto-archived ${archived.length} stale issues`);+ // An unreachable api must not read as a failed tick: the issues are archived+ // either way, and their threads then stay until the agent or project goes.+ try {+ await deleteIssueAgentThreads(archived);+ } catch (error) {+ console.error('[worker] deleting agent threads of archived issues failed:', error);+ }+ }}if (++ticksSinceTelemetry >= TELEMETRY_CHECK_EVERY_TICKS) {ticksSinceTelemetry = 0;