Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix: thread and stale sessions
Guse752e53c9b40
diff --git a/src/cli/daemon/execenv/__tests__/timeline.test.ts b/src/cli/daemon/execenv/__tests__/timeline.test.tsindex 72e3188c9..98aba24ab 100644--- a/src/cli/daemon/execenv/__tests__/timeline.test.ts+++ b/src/cli/daemon/execenv/__tests__/timeline.test.ts@@ -399,7 +399,7 @@ describe("timeline", () => {expect(findResumableSessionByContextKey(dir, "conv_1", "claude")).toBeNull();});- it("uses unified 72h max age for all context keys", () => {+ it("resumes sessions regardless of age", () => {const fourHoursAgo = new Date(Date.now() - 4 * 60 * 60 * 1000);writeEntry(_todayFilename(), makeEntry({task_id: "t_4h",@@ -409,24 +409,23 @@ describe("timeline", () => {datetime: fourHoursAgo.toISOString(),}));- // 4 hours ago is within 72h — should matchexpect(findResumableSessionByContextKey(dir, "conv_1", "claude")).toBe("sess_4h");});- it("expires after 72h", () => {- const seventyFourHoursAgo = new Date(Date.now() - 74 * 60 * 60 * 1000);- writeEntry(_filenameForDate(seventyFourHoursAgo), makeEntry({+ it("resumes old sessions within the scan window", () => {+ const threeDaysAgo = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000);+ writeEntry(_filenameForDate(threeDaysAgo), makeEntry({task_id: "t_old",status: "completed",session_id: "sess_old",context_key: "conv_1",- datetime: seventyFourHoursAgo.toISOString(),+ datetime: threeDaysAgo.toISOString(),}));- expect(findResumableSessionByContextKey(dir, "conv_1", "claude")).toBeNull();+ expect(findResumableSessionByContextKey(dir, "conv_1", "claude")).toBe("sess_old");});- it("does not use different max age for different context key types", () => {+ it("resumes sessions for all context key types equally", () => {const twentyFourHoursAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);writeEntry(_todayFilename(), makeEntry({@@ -444,7 +443,6 @@ describe("timeline", () => {datetime: twentyFourHoursAgo.toISOString(),}));- // Both 24h old — both within unified 72h windowexpect(findResumableSessionByContextKey(dir, "conv_dm", "claude")).toBe("sess_dm");expect(findResumableSessionByContextKey(dir, "conv_email", "claude")).toBe("sess_email");});diff --git a/src/cli/daemon/execenv/timeline.ts b/src/cli/daemon/execenv/timeline.tsindex cb5bf64a1..b8193642a 100644--- a/src/cli/daemon/execenv/timeline.ts+++ b/src/cli/daemon/execenv/timeline.ts@@ -223,17 +223,13 @@ export function createTimelineEntry(};}-const RESUME_MAX_AGE_MS = 72 * 60 * 60 * 1000; // 72 hours-export function findResumableSessionByContextKey(timelineDir: string,contextKey: string,provider: string,): string | null {- const now = new Date();- const cutoff = new Date(now.getTime() - RESUME_MAX_AGE_MS);const entries: ContextTimelineEntry[] = [];- for (const filename of recentFilenames(7)) {+ for (const filename of recentFilenames(90)) {entries.push(...readJsonl(join(timelineDir, filename)));}entries.sort((a, b) => new Date(b.datetime).getTime() - new Date(a.datetime).getTime());@@ -242,8 +238,7 @@ export function findResumableSessionByContextKey(entry.status !== "running" &&entry.context_key === contextKey &&entry.provider === provider &&- entry.session_id &&- new Date(entry.datetime) >= cutoff+ entry.session_id) {return entry.session_id;}diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.tsindex 126962be4..3b0eeeac1 100644--- a/src/shared/src/db/schema.ts+++ b/src/shared/src/db/schema.ts@@ -313,6 +313,7 @@ export const conversation = sqliteTable(.on(t.workspaceId, t.agentId, t.userId, t.type, t.channel, t.createdAt),index("idx_conversation_ws_user").on(t.workspaceId, t.userId, t.createdAt),index("idx_conversation_thread").on(t.parentMessageId),+ unique("uq_conversation_parent_message").on(t.parentMessageId, t.workspaceId),foreignKey({columns: [t.agentId, t.workspaceId],foreignColumns: [agent.id, agent.workspaceId],diff --git a/src/web/migrations/0040_thread_unique_constraint.sql b/src/web/migrations/0040_thread_unique_constraint.sqlnew file mode 100644index 000000000..8beb9bfce--- /dev/null+++ b/src/web/migrations/0040_thread_unique_constraint.sql@@ -0,0 +1,5 @@+-- Prevent duplicate threads for the same parent message within a workspace.+-- SQLite treats NULLs as distinct, so non-thread conversations are unaffected.+CREATE UNIQUE INDEX uq_conversation_parent_message+ ON conversation (parent_message_id, workspace_id)+ WHERE parent_message_id IS NOT NULL;diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/layout.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/layout.tsxindex b253d9f46..ff628e26f 100644--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/layout.tsx+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/layout.tsx@@ -257,7 +257,7 @@ export default function AgentDetailLayout({ children }: { children: ReactNode })}><GitBranch className="size-3.5" />- Threads+ Traces</DropdownMenuItem><DropdownMenuSeparator /><DropdownMenuItem onClick={() => setEditing(true)}>diff --git a/src/web/src/app/(app)/w/[slug]/traces/page.tsx b/src/web/src/app/(app)/w/[slug]/traces/page.tsxindex 0506a98a1..e65ff8147 100644--- a/src/web/src/app/(app)/w/[slug]/traces/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/traces/page.tsx@@ -274,7 +274,7 @@ export default function TracesPage() {<div className="flex flex-col h-full"><div className="flex items-center justify-between border-b border-border/50 px-3 md:px-5 py-2.5 gap-3"><div className="flex items-center gap-3 min-w-0">- <h1 className="text-sm font-medium">Threads</h1>+ <h1 className="text-sm font-medium">Traces</h1><p className="text-xs text-muted-foreground hidden md:block">Execution traces across your agents.</p>@@ -358,7 +358,7 @@ export default function TracesPage() {) : traces.length === 0 ? (<div className="flex flex-col items-center justify-center h-full animate-[fade-up_400ms_ease-out_both]"><GitBranch className="size-8 text-muted-foreground mb-3" />- <p className="text-sm text-muted-foreground">No threads yet</p>+ <p className="text-sm text-muted-foreground">No traces yet</p><p className="text-xs text-muted-foreground/60 mt-1">Only tasks involving multiple agents appear here.</p>diff --git a/src/web/src/app/api/conversations/[id]/threads/route.ts b/src/web/src/app/api/conversations/[id]/threads/route.tsindex f10e9fa03..4aeb9885a 100644--- a/src/web/src/app/api/conversations/[id]/threads/route.ts+++ b/src/web/src/app/api/conversations/[id]/threads/route.ts@@ -1,5 +1,5 @@import { getCloudflareContext } from "@opennextjs/cloudflare";-import { queries, TASK_TYPES, truncateTitle, CreateThreadRequestSchema } from "@alook/shared";+import { queries, TASK_TYPES, truncateTitle, CreateThreadRequestSchema, isUniqueConstraintError } from "@alook/shared";import { getDb } from "@/lib/db";import { nanoid } from "nanoid";import { withAuth } from "@/lib/middleware/auth";@@ -82,18 +82,28 @@ export const POST = withAuth(async (req, ctx) => {}}- // Create new thread conversation+ // Create new thread conversation (catch unique-violation from concurrent requests)const threadTitle = truncateTitle(rootMessage.content).slice(0, 80);- const threadConv = await queries.conversation.createConversation(db, {- workspaceId: ws.workspaceId,- agentId: parentConv.agentId,- userId: ctx.userId,- title: "",- type: TASK_TYPES.USER_DM_MESSAGE,- channel: parentConv.channel ?? "default",- parentMessageId: body.parent_message_id,- threadTitle,- });+ let threadConv;+ try {+ threadConv = await queries.conversation.createConversation(db, {+ workspaceId: ws.workspaceId,+ agentId: parentConv.agentId,+ userId: ctx.userId,+ title: "",+ type: TASK_TYPES.USER_DM_MESSAGE,+ channel: parentConv.channel ?? "default",+ parentMessageId: body.parent_message_id,+ threadTitle,+ });+ } catch (err) {+ if (!isUniqueConstraintError(err)) throw err;+ const raced = await queries.conversation.getThreadByParentMessage(+ db, body.parent_message_id, ws.workspaceId+ );+ if (!raced) throw err;+ threadConv = raced;+ }broadcastToUser(ctx.userId, {type: "thread.created",