Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add issue kanban workflow (#59)

Genere64817eb2d92
diff --git a/src/cli/commands/issue.test.ts b/src/cli/commands/issue.test.ts
new file mode 100644
index 000000000..2f0f7b85f
--- /dev/null
+++ b/src/cli/commands/issue.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from "vitest";
+import { issueCommand } from "./issue";
+
+describe("issueCommand", () => {
+ const cmd = issueCommand();
+
+ it("registers issue subcommands", () => {
+ const names = cmd.commands.map((c) => c.name());
+ expect(names).toContain("create");
+ expect(names).toContain("list");
+ expect(names).toContain("pull");
+ expect(names).toContain("show");
+ expect(names).toContain("update");
+ expect(names).toContain("comment");
+ });
+
+ it("create requires agent_id and title", () => {
+ const create = cmd.commands.find((c) => c.name() === "create")!;
+ const opts = (create as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
+ const mandatory = opts.filter((o) => o.mandatory).map((o) => o.long);
+ expect(mandatory).toContain("--agent_id");
+ expect(mandatory).toContain("--title");
+ });
+
+ it("show/update/comment require agent_id and issue_id", () => {
+ for (const name of ["show", "update", "comment"]) {
+ const sub = cmd.commands.find((c) => c.name() === name)!;
+ const opts = (sub as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
+ const mandatory = opts.filter((o) => o.mandatory).map((o) => o.long);
+ expect(mandatory).toContain("--agent_id");
+ expect(mandatory).toContain("--issue_id");
+ }
+ });
+
+ it("update supports status, title, description, and body-file", () => {
+ const update = cmd.commands.find((c) => c.name() === "update")!;
+ const opts = (update as unknown as { options: { long: string }[] }).options;
+ const longs = opts.map((o) => o.long);
+ expect(longs).toContain("--status");
+ expect(longs).toContain("--title");
+ expect(longs).toContain("--description");
+ expect(longs).toContain("--body-file");
+ });
+});
diff --git a/src/cli/commands/issue.ts b/src/cli/commands/issue.ts
new file mode 100644
index 000000000..497c33992
--- /dev/null
+++ b/src/cli/commands/issue.ts
@@ -0,0 +1,251 @@
+import { Command } from "commander";
+import { readFileSync } from "fs";
+import { APIClient } from "../lib/client.js";
+import { loadCLIConfigForProfile } from "../lib/config.js";
+import { printJSON } from "../lib/output.js";
+import { cmdPrefix } from "../lib/env.js";
+
+const VALID_STATUSES = ["todo", "in_progress", "review", "done", "closed", "canceled", "failed"];
+
+interface IssueResponse {
+ id: string;
+ workspace_id: string;
+ agent_id: string;
+ creator_user_id: string;
+ conversation_id: string;
+ latest_task_id: string | null;
+ title: string;
+ description: string;
+ status: string;
+ created_at: string;
+ updated_at: string;
+ completed_at: string | null;
+}
+
+interface MessageResponse {
+ id: string;
+ role: string;
+ content: string;
+ created_at: string;
+}
+
+function resolveClientOpts(command: Command, agentId: string) {
+ let root = command;
+ while (root.parent) root = root.parent;
+ const parentOpts = root.opts() || {};
+ const profile: string | undefined = parentOpts.profile;
+ const cfg = loadCLIConfigForProfile(profile);
+ const serverUrl = parentOpts.server || cfg.server_url;
+ const workspaces = cfg.watched_workspaces || [];
+
+ const ws = workspaces.find((w) => w.agent_ids?.includes(agentId));
+ if (!ws || !ws.token) {
+ console.error(
+ `Error: no registered workspace contains agent ${agentId}. Run '${cmdPrefix()} register --token <token>' first.`
+ );
+ process.exit(1);
+ }
+ return { serverUrl, token: ws.token, workspaceId: ws.id };
+}
+
+function readBody(opts: { body?: string; bodyFile?: string }): string {
+ if (opts.body && opts.bodyFile) {
+ console.error("Error: --body and --body-file are mutually exclusive");
+ process.exit(1);
+ }
+ if (opts.bodyFile) return readFileSync(opts.bodyFile, "utf-8");
+ return opts.body ?? "";
+}
+
+function printIssue(issue: IssueResponse): void {
+ console.log(`${issue.id} ${issue.status.padEnd(11)} ${issue.title}`);
+}
+
+function printIssueDetail(issue: IssueResponse, messages?: MessageResponse[]): void {
+ console.log(`id: ${issue.id}`);
+ console.log(`agent_id: ${issue.agent_id}`);
+ console.log(`status: ${issue.status}`);
+ console.log(`conversation_id: ${issue.conversation_id}`);
+ if (issue.latest_task_id) console.log(`latest_task_id: ${issue.latest_task_id}`);
+ console.log(`title: ${issue.title}`);
+ console.log("description:");
+ console.log(issue.description || "(no description)");
+ if (messages && messages.length > 0) {
+ console.log("\nconversation:");
+ for (const m of messages) {
+ console.log(`[${m.role}] ${m.content}`);
+ }
+ }
+}
+
+export function issueCommand(): Command {
+ const cmd = new Command("issue").description("Manage assigned issues");
+
+ cmd
+ .command("create")
+ .description("Create and dispatch an issue to an agent")
+ .requiredOption("--agent_id <id>", "Agent ID")
+ .requiredOption("--title <title>", "Issue title")
+ .option("--description <text>", "Issue description")
+ .option("--body-file <path>", "Read issue description from a file")
+ .option("--json", "Output as JSON")
+ .action(async (opts, command) => {
+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, opts.agent_id);
+ const client = new APIClient(serverUrl, token, workspaceId);
+ const description = readBody({ body: opts.description, bodyFile: opts.bodyFile });
+ try {
+ const res = await client.postJSON<{ issue: IssueResponse }>("/api/issues", {
+ agent_id: opts.agent_id,
+ title: opts.title,
+ description,
+ });
+ if (opts.json) return printJSON(res);
+ console.log(`Created ${res.issue.id} — ${res.issue.title}`);
+ } catch (err) {
+ console.error(`Error: ${err instanceof Error ? err.message : err}`);
+ process.exit(1);
+ }
+ });
+
+ cmd
+ .command("list")
+ .description("List issues for an agent")
+ .requiredOption("--agent_id <id>", "Agent ID")
+ .option("--status <status>", `Filter by status (${VALID_STATUSES.join(", ")})`)
+ .option("--completed", "Show completed/closed/canceled/failed issues")
+ .option("--all", "Show all issues")
+ .option("--json", "Output as JSON")
+ .action(async (opts, command) => {
+ if (opts.status && !VALID_STATUSES.includes(opts.status)) {
+ console.error(`Error: invalid status "${opts.status}"`);
+ process.exit(1);
+ }
+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, opts.agent_id);
+ const client = new APIClient(serverUrl, token, workspaceId);
+ const params = new URLSearchParams({ agentId: opts.agent_id });
+ if (opts.status) params.set("status", opts.status);
+ if (!opts.all && !opts.status) params.set("terminal", opts.completed ? "true" : "false");
+ try {
+ const issues = await client.getJSON<IssueResponse[]>(`/api/issues?${params}`);
+ if (opts.json) return printJSON(issues);
+ if (issues.length === 0) {
+ console.log("No issues found.");
+ return;
+ }
+ for (const issue of issues) printIssue(issue);
+ } catch (err) {
+ console.error(`Error: ${err instanceof Error ? err.message : err}`);
+ process.exit(1);
+ }
+ });
+
+ cmd
+ .command("pull")
+ .description("Show the next active issue for an agent")
+ .requiredOption("--agent_id <id>", "Agent ID")
+ .option("--json", "Output as JSON")
+ .action(async (opts, command) => {
+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, opts.agent_id);
+ const client = new APIClient(serverUrl, token, workspaceId);
+ try {
+ const issues = await client.getJSON<IssueResponse[]>(`/api/issues?agentId=${encodeURIComponent(opts.agent_id)}&terminal=false`);
+ const issue = issues[0] ?? null;
+ if (opts.json) return printJSON(issue);
+ if (!issue) {
+ console.log("No active issues.");
+ return;
+ }
+ printIssueDetail(issue);
+ } catch (err) {
+ console.error(`Error: ${err instanceof Error ? err.message : err}`);
+ process.exit(1);
+ }
+ });
+
+ cmd
+ .command("show")
+ .description("Show issue details and conversation")
+ .requiredOption("--agent_id <id>", "Agent ID")
+ .requiredOption("--issue_id <id>", "Issue ID")
+ .option("--json", "Output as JSON")
+ .action(async (opts, command) => {
+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, opts.agent_id);
+ const client = new APIClient(serverUrl, token, workspaceId);
+ try {
+ const res = await client.getJSON<{ issue: IssueResponse; messages: MessageResponse[] }>(`/api/issues/${opts.issue_id}?agentId=${encodeURIComponent(opts.agent_id)}`);
+ if (res.issue.agent_id !== opts.agent_id) {
+ console.error(`Error: issue ${res.issue.id} does not belong to agent ${opts.agent_id}`);
+ process.exit(1);
+ }
+ if (opts.json) return printJSON(res);
+ printIssueDetail(res.issue, res.messages);
+ } catch (err) {
+ console.error(`Error: ${err instanceof Error ? err.message : err}`);
+ process.exit(1);
+ }
+ });
+
+ cmd
+ .command("update")
+ .description("Update issue status or text")
+ .requiredOption("--agent_id <id>", "Agent ID")
+ .requiredOption("--issue_id <id>", "Issue ID")
+ .option("--status <status>", `New status (${VALID_STATUSES.join(", ")})`)
+ .option("--title <title>", "New title")
+ .option("--description <text>", "New description")
+ .option("--body-file <path>", "Read description from a file")
+ .option("--json", "Output as JSON")
+ .action(async (opts, command) => {
+ if (opts.status && !VALID_STATUSES.includes(opts.status)) {
+ console.error(`Error: invalid status "${opts.status}"`);
+ process.exit(1);
+ }
+ const description = readBody({ body: opts.description, bodyFile: opts.bodyFile });
+ const body: Record<string, string> = {};
+ if (opts.status) body.status = opts.status;
+ if (opts.title) body.title = opts.title;
+ if (description) body.description = description;
+ if (Object.keys(body).length === 0) {
+ console.error("Error: pass at least one of --status, --title, --description, --body-file");
+ process.exit(1);
+ }
+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, opts.agent_id);
+ const client = new APIClient(serverUrl, token, workspaceId);
+ try {
+ const issue = await client.patchJSON<IssueResponse>(`/api/issues/${opts.issue_id}?agentId=${encodeURIComponent(opts.agent_id)}`, body);
+ if (opts.json) return printJSON(issue);
+ printIssue(issue);
+ } catch (err) {
+ console.error(`Error: ${err instanceof Error ? err.message : err}`);
+ process.exit(1);
+ }
+ });
+
+ cmd
+ .command("comment")
+ .description("Append a comment to an issue")
+ .requiredOption("--agent_id <id>", "Agent ID")
+ .requiredOption("--issue_id <id>", "Issue ID")
+ .option("--body <text>", "Comment text")
+ .option("--body-file <path>", "Read comment from a file")
+ .option("--json", "Output as JSON")
+ .action(async (opts, command) => {
+ const content = readBody({ body: opts.body, bodyFile: opts.bodyFile }).trim();
+ if (!content) {
+ console.error("Error: pass --body or --body-file");
+ process.exit(1);
+ }
+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, opts.agent_id);
+ const client = new APIClient(serverUrl, token, workspaceId);
+ try {
+ const res = await client.postJSON<{ message: MessageResponse }>(`/api/issues/${opts.issue_id}?agentId=${encodeURIComponent(opts.agent_id)}`, { content });
+ if (opts.json) return printJSON(res);
+ console.log(`Commented on ${opts.issue_id}`);
+ } catch (err) {
+ console.error(`Error: ${err instanceof Error ? err.message : err}`);
+ process.exit(1);
+ }
+ });
+
+ return cmd;
+}
diff --git a/src/cli/daemon/prompt.test.ts b/src/cli/daemon/prompt.test.ts
index fae3b44c0..ded9b2472 100644
--- a/src/cli/daemon/prompt.test.ts
+++ b/src/cli/daemon/prompt.test.ts
@@ -99,6 +99,14 @@ describe("buildPrompt", () => {
expect(parsed.notice).toBeUndefined();
});
+ it("adds issue guidance for issue_event tasks", () => {
+ const task = makeTask("Issue iss_1: Fix import", "issue_event");
+ const parsed = JSON.parse(buildPrompt(task));
+ expect(parsed.notice).toContain("assigned issue");
+ expect(parsed.notice).toContain("alook issue update");
+ expect(parsed.notice).toContain("in_progress");
+ });
+
it("includes sender for DM tasks when sender is present", () => {
const task: Task = {
...makeTask("Fix the login bug"),
diff --git a/src/cli/daemon/prompt.ts b/src/cli/daemon/prompt.ts
index 824ca342b..7fbc37a78 100644
--- a/src/cli/daemon/prompt.ts
+++ b/src/cli/daemon/prompt.ts
@@ -11,6 +11,10 @@ const EMAIL_NOTICE =
" If you need more information or confirmation from the human, send them an email asking for it and then exit." +
" Do not wait — when the human replies, a new task will be triggered automatically and you will be woken up with their response.";
+const ISSUE_NOTICE =
+ "This task was triggered by an assigned issue. Use `alook issue show`, `alook issue update`, and `alook issue comment` to inspect and update the issue as you work." +
+ " Move the issue to in_progress when you begin, then to review, done, closed, canceled, or failed when appropriate.";
+
function buildDmNotice(name: string, email: string): string {
return (
`This task was triggered by an incoming email on a conversation with ${name} (${email}).` +
@@ -33,6 +37,9 @@ export function buildPrompt(task: Task, attachments?: Attachment[]): string {
obj.notice = EMAIL_NOTICE;
}
}
+ if (task.type === "issue_event") {
+ obj.notice = ISSUE_NOTICE;
+ }
if (task.sender) {
obj.sender = {
name: task.sender.name,
diff --git a/src/cli/src/index.ts b/src/cli/src/index.ts
index e73d94372..eb8d90c55 100644
--- a/src/cli/src/index.ts
+++ b/src/cli/src/index.ts
@@ -6,6 +6,7 @@ import { daemonCommand } from "../commands/daemon.js";
import { configCommand } from "../commands/config.js";
import { emailCommand } from "../commands/email.js";
import { calendarCommand } from "../commands/calendar.js";
+import { issueCommand } from "../commands/issue.js";
import { versionCommand } from "../commands/version.js";
import { updateCommand } from "../commands/update.js";
import { syncCommand } from "../commands/sync.js";
@@ -23,6 +24,7 @@ program.addCommand(statusCommand());
program.addCommand(daemonCommand());
program.addCommand(emailCommand());
program.addCommand(calendarCommand());
+program.addCommand(issueCommand());
program.addCommand(configCommand());
program.addCommand(versionCommand());
program.addCommand(updateCommand());
diff --git a/src/shared/src/api-types.ts b/src/shared/src/api-types.ts
index 4ef245c74..cde8f43fd 100644
--- a/src/shared/src/api-types.ts
+++ b/src/shared/src/api-types.ts
@@ -8,6 +8,7 @@ import type {
TaskMessage,
MachineToken,
CalendarEvent,
+ Issue,
} from "./types";
import type { TaskApi } from "./schemas";
@@ -49,6 +50,8 @@ export type ListMachineTokensResponse = ApiListResponse<MachineToken>;
export type ListCalendarEventsResponse = ApiListResponse<CalendarEvent>;
export type GetCalendarEventResponse = ApiResponse<CalendarEvent>;
+export type ListIssuesResponse = ApiListResponse<Issue>;
+export type GetIssueResponse = ApiResponse<Issue>;
export interface CreateCalendarEventRequest {
agent_id: string;
@@ -80,6 +83,22 @@ export interface DeleteCalendarEventRequest {
occurrence_at?: string;
}
+export interface CreateIssueRequest {
+ agent_id: string;
+ title: string;
+ description?: string;
+}
+
+export interface UpdateIssueRequest {
+ title?: string;
+ description?: string;
+ status?: Issue["status"];
+}
+
+export interface CreateIssueCommentRequest {
+ content: string;
+}
+
export interface CreateAgentLinkRequest {
source_agent_id: string;
target_agent_id: string;
diff --git a/src/shared/src/constants.ts b/src/shared/src/constants.ts
index cefa23eb3..41241b611 100644
--- a/src/shared/src/constants.ts
+++ b/src/shared/src/constants.ts
@@ -42,11 +42,41 @@ export const TASK_TYPES = {
USER_DM_MESSAGE: "user_dm_message",
EMAIL_NOTIFICATION: "email_notification",
CALENDAR_EVENT: "calendar_event",
+ ISSUE_EVENT: "issue_event",
KILL_TASK: "kill_task",
} as const;
export type TaskType = (typeof TASK_TYPES)[keyof typeof TASK_TYPES];
+export const IssueStatus = {
+ TODO: "todo",
+ IN_PROGRESS: "in_progress",
+ REVIEW: "review",
+ DONE: "done",
+ CLOSED: "closed",
+ CANCELED: "canceled",
+ FAILED: "failed",
+} as const;
+
+export type IssueStatusType = (typeof IssueStatus)[keyof typeof IssueStatus];
+
+export const ACTIVE_ISSUE_STATUSES: readonly IssueStatusType[] = [
+ IssueStatus.TODO,
+ IssueStatus.IN_PROGRESS,
+ IssueStatus.REVIEW,
+] as const;
+
+export const TERMINAL_ISSUE_STATUSES: readonly IssueStatusType[] = [
+ IssueStatus.DONE,
+ IssueStatus.CLOSED,
+ IssueStatus.CANCELED,
+ IssueStatus.FAILED,
+] as const;
+
+export function isTerminalIssueStatus(status: string): boolean {
+ return (TERMINAL_ISSUE_STATUSES as readonly string[]).includes(status);
+}
+
export const MessageRole = {
USER: "user",
ASSISTANT: "assistant",
diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.ts
index 020afa610..f27751938 100644
--- a/src/shared/src/db/queries-index.ts
+++ b/src/shared/src/db/queries-index.ts
@@ -25,3 +25,4 @@ export * as channel from "./queries/channel";
export * as workspaceFileRequest from "./queries/workspace-file-request";
export * as conversationMap from "./queries/conversation-map";
export * as agentLink from "./queries/agent-link";
+export * as issue from "./queries/issue";
diff --git a/src/shared/src/db/queries/issue.ts b/src/shared/src/db/queries/issue.ts
new file mode 100644
index 000000000..3d541ede9
--- /dev/null
+++ b/src/shared/src/db/queries/issue.ts
@@ -0,0 +1,136 @@
+import { and, asc, desc, eq, inArray } from "drizzle-orm";
+import { issue, message } from "../schema";
+import type { Database } from "../index";
+import { TERMINAL_ISSUE_STATUSES, type IssueStatusType } from "../../constants";
+
+const ACTIVE_STATUSES: IssueStatusType[] = ["todo", "in_progress", "review"];
+
+export async function createIssue(
+ db: Database,
+ data: {
+ workspaceId: string;
+ agentId: string;
+ creatorUserId: string;
+ conversationId: string;
+ title: string;
+ description: string;
+ status?: IssueStatusType;
+ }
+) {
+ const now = new Date().toISOString();
+ const rows = await db
+ .insert(issue)
+ .values({
+ workspaceId: data.workspaceId,
+ agentId: data.agentId,
+ creatorUserId: data.creatorUserId,
+ conversationId: data.conversationId,
+ title: data.title,
+ description: data.description,
+ status: data.status ?? "todo",
+ createdAt: now,
+ updatedAt: now,
+ })
+ .returning();
+ return rows[0]!;
+}
+
+export async function getIssue(db: Database, id: string, workspaceId: string) {
+ const rows = await db
+ .select()
+ .from(issue)
+ .where(and(eq(issue.id, id), eq(issue.workspaceId, workspaceId)));
+ return rows[0] ?? null;
+}
+
+export async function listIssues(
+ db: Database,
+ workspaceId: string,
+ opts: { agentId?: string; status?: IssueStatusType; terminal?: boolean } = {}
+) {
+ const conditions = [eq(issue.workspaceId, workspaceId)];
+ if (opts.agentId) conditions.push(eq(issue.agentId, opts.agentId));
+ if (opts.status) conditions.push(eq(issue.status, opts.status));
+ if (opts.terminal !== undefined) {
+ const terminal = [...TERMINAL_ISSUE_STATUSES];
+ conditions.push(
+ opts.terminal
+ ? inArray(issue.status, terminal)
+ : inArray(issue.status, ACTIVE_STATUSES)
+ );
+ }
+
+ return db
+ .select()
+ .from(issue)
+ .where(and(...conditions))
+ .orderBy(desc(issue.updatedAt));
+}
+
+export async function updateIssue(
+ db: Database,
+ id: string,
+ workspaceId: string,
+ patch: {
+ title?: string;
+ description?: string;
+ status?: IssueStatusType;
+ latestTaskId?: string | null;
+ }
+) {
+ const now = new Date().toISOString();
+ const terminal = patch.status
+ ? (TERMINAL_ISSUE_STATUSES as readonly string[]).includes(patch.status)
+ : undefined;
+ const values: {
+ title?: string;
+ description?: string;
+ status?: IssueStatusType;
+ latestTaskId?: string | null;
+ updatedAt: string;
+ completedAt?: string | null;
+ } = { updatedAt: now };
+ if (patch.title !== undefined) values.title = patch.title;
+ if (patch.description !== undefined) values.description = patch.description;
+ if (patch.status !== undefined) values.status = patch.status;
+ if (patch.latestTaskId !== undefined) values.latestTaskId = patch.latestTaskId;
+ if (terminal !== undefined) values.completedAt = terminal ? now : null;
+ const rows = await db
+ .update(issue)
+ .set(values)
+ .where(and(eq(issue.id, id), eq(issue.workspaceId, workspaceId)))
+ .returning();
+ return rows[0] ?? null;
+}
+
+export async function setLatestTask(
+ db: Database,
+ id: string,
+ workspaceId: string,
+ latestTaskId: string | null
+) {
+ return updateIssue(db, id, workspaceId, { latestTaskId });
+}
+
+export async function deleteIssue(db: Database, id: string, workspaceId: string) {
+ const rows = await db
+ .delete(issue)
+ .where(and(eq(issue.id, id), eq(issue.workspaceId, workspaceId)))
+ .returning();
+ return rows[0] ?? null;
+}
+
+export async function listIssueMessages(
+ db: Database,
+ issueId: string,
+ workspaceId: string
+) {
+ const row = await getIssue(db, issueId, workspaceId);
+ if (!row) return null;
+ const rows = await db
+ .select()
+ .from(message)
+ .where(and(eq(message.conversationId, row.conversationId), eq(message.status, "active")))
+ .orderBy(asc(message.createdAt), asc(message.id));
+ return rows;
+}
diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.ts
index 0d91bcae2..32c656c8a 100644
--- a/src/shared/src/db/schema.ts
+++ b/src/shared/src/db/schema.ts
@@ -378,6 +378,41 @@ export const agentTaskQueue = sqliteTable(
]
);
+export const issue = sqliteTable(
+ "issue",
+ {
+ id: text("id").primaryKey().$defaultFn(() => "iss_" + nanoid()),
+ workspaceId: text("workspace_id")
+ .notNull()
+ .references(() => workspace.id, { onDelete: "cascade" }),
+ agentId: text("agent_id").notNull(),
+ creatorUserId: text("creator_user_id")
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ conversationId: text("conversation_id")
+ .notNull()
+ .references(() => conversation.id, { onDelete: "cascade" }),
+ latestTaskId: text("latest_task_id").references(() => agentTaskQueue.id, {
+ onDelete: "set null",
+ }),
+ title: text("title").notNull(),
+ description: text("description").notNull().default(""),
+ status: text("status").notNull().default("todo"),
+ createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),
+ updatedAt: text("updated_at").notNull().$defaultFn(() => new Date().toISOString()),
+ completedAt: text("completed_at"),
+ },
+ (t) => [
+ index("idx_issue_workspace_status_agent").on(t.workspaceId, t.status, t.agentId),
+ index("idx_issue_workspace_updated").on(t.workspaceId, t.updatedAt),
+ unique("issue_conversation_unique").on(t.conversationId),
+ foreignKey({
+ columns: [t.agentId, t.workspaceId],
+ foreignColumns: [agent.id, agent.workspaceId],
+ }).onDelete("cascade"),
+ ]
+);
+
export const taskMessage = sqliteTable(
"task_message",
{
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index b207ae24b..8d6479266 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -17,6 +17,7 @@ export type {
LoginResponse,
CreateAgentRequest,
CalendarEvent,
+ Issue,
AgentLink,
MeetingSession,
Channel,
@@ -45,9 +46,14 @@ export type {
ListMachineTokensResponse,
ListCalendarEventsResponse,
GetCalendarEventResponse,
+ ListIssuesResponse,
+ GetIssueResponse,
CreateCalendarEventRequest,
UpdateCalendarEventRequest,
DeleteCalendarEventRequest,
+ CreateIssueRequest,
+ UpdateIssueRequest,
+ CreateIssueCommentRequest,
CreateAgentLinkRequest,
UpdateAgentLinkRequest,
CreateWorkspaceRequest,
@@ -65,6 +71,10 @@ export {
TERMINAL_TASK_STATUSES,
isTerminalTaskStatus,
TASK_TYPES,
+ IssueStatus,
+ ACTIVE_ISSUE_STATUSES,
+ TERMINAL_ISSUE_STATUSES,
+ isTerminalIssueStatus,
MessageRole,
POLL_INTERVAL_MS,
OFFLINE_THRESHOLD_MS,
@@ -83,6 +93,7 @@ export type {
RuntimeStatusType,
TaskStatusType,
TaskType,
+ IssueStatusType,
MessageRoleType,
MeetingStatusType,
} from "./constants";
@@ -112,6 +123,11 @@ export {
UpdateCalendarEventRequestSchema,
DeleteCalendarEventRequestSchema,
CalendarEventApiSchema,
+ IssueStatusSchema,
+ CreateIssueRequestSchema,
+ UpdateIssueRequestSchema,
+ CreateIssueCommentRequestSchema,
+ IssueApiSchema,
CreateAgentLinkRequestSchema,
UpdateAgentLinkRequestSchema,
AddWhitelistRequestSchema,
@@ -160,6 +176,10 @@ export type {
UpdateCalendarEventRequestInput,
DeleteCalendarEventRequestInput,
CalendarEventApi,
+ CreateIssueRequestInput,
+ UpdateIssueRequestInput,
+ CreateIssueCommentRequestInput,
+ IssueApi,
CreateAgentLinkRequestInput,
UpdateAgentLinkRequestInput,
AddWhitelistRequest,
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 00dc32f9a..65ab0081d 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -1,5 +1,5 @@
import { z } from "zod";
-import { TASK_TYPES } from "./constants";
+import { IssueStatus, TASK_TYPES } from "./constants";
// ---------------------------------------------------------------------------
// Task status
@@ -340,6 +340,63 @@ export const CalendarEventApiSchema = z.object({
});
export type CalendarEventApi = z.infer<typeof CalendarEventApiSchema>;
+// ---------------------------------------------------------------------------
+// Issue schemas
+// ---------------------------------------------------------------------------
+
+export const IssueStatusSchema = z.enum([
+ IssueStatus.TODO,
+ IssueStatus.IN_PROGRESS,
+ IssueStatus.REVIEW,
+ IssueStatus.DONE,
+ IssueStatus.CLOSED,
+ IssueStatus.CANCELED,
+ IssueStatus.FAILED,
+]);
+
+export const CreateIssueRequestSchema = z.object({
+ agent_id: z.string().min(1, "agent_id is required"),
+ title: z.string().min(1, "title is required").max(200),
+ description: z.string().max(20_000).optional().default(""),
+});
+export type CreateIssueRequestInput = z.infer<typeof CreateIssueRequestSchema>;
+
+export const UpdateIssueRequestSchema = z
+ .object({
+ title: z.string().min(1).max(200).optional(),
+ description: z.string().max(20_000).optional(),
+ status: IssueStatusSchema.optional(),
+ })
+ .refine(
+ (v) =>
+ v.title !== undefined ||
+ v.description !== undefined ||
+ v.status !== undefined,
+ { message: "at least one field is required" }
+ );
+export type UpdateIssueRequestInput = z.infer<typeof UpdateIssueRequestSchema>;
+
+export const CreateIssueCommentRequestSchema = z.object({
+ content: z.string().min(1, "content is required").max(20_000),
+});
+export type CreateIssueCommentRequestInput = z.infer<typeof CreateIssueCommentRequestSchema>;
+
+export const IssueApiSchema = z.object({
+ id: z.string(),
+ workspace_id: z.string(),
+ agent_id: z.string(),
+ creator_user_id: z.string(),
+ conversation_id: z.string(),
+ latest_task_id: z.string().nullable(),
+ title: z.string(),
+ description: z.string(),
+ status: IssueStatusSchema,
+ created_at: z.string(),
+ updated_at: z.string(),
+ completed_at: z.string().nullable(),
+});
+export type IssueApi = z.infer<typeof IssueApiSchema>;
+
// ---------------------------------------------------------------------------
// Agent link schemas
// ---------------------------------------------------------------------------
diff --git a/src/shared/src/types.ts b/src/shared/src/types.ts
index 3581cdb0b..c45dc8433 100644
--- a/src/shared/src/types.ts
+++ b/src/shared/src/types.ts
@@ -91,6 +91,21 @@ export interface CalendarEvent {
updated_at: string;
}
+export interface Issue {
+ id: string;
+ workspace_id: string;
+ agent_id: string;
+ creator_user_id: string;
+ conversation_id: string;
+ latest_task_id: string | null;
+ title: string;
+ description: string;
+ status: "todo" | "in_progress" | "review" | "done" | "closed" | "canceled" | "failed";
+ created_at: string;
+ updated_at: string;
+ completed_at: string | null;
+}
+
export interface Message {
id: string;
conversation_id: string;
diff --git a/src/web/migrations/0022_issues.sql b/src/web/migrations/0022_issues.sql
new file mode 100644
index 000000000..a297cf03d
--- /dev/null
+++ b/src/web/migrations/0022_issues.sql
@@ -0,0 +1,22 @@
+CREATE TABLE IF NOT EXISTS issue (
+ id TEXT PRIMARY KEY,
+ workspace_id TEXT NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,
+ agent_id TEXT NOT NULL,
+ creator_user_id TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,
+ conversation_id TEXT NOT NULL REFERENCES conversation(id) ON DELETE CASCADE,
+ latest_task_id TEXT REFERENCES agent_task_queue(id) ON DELETE SET NULL,
+ title TEXT NOT NULL,
+ description TEXT NOT NULL DEFAULT '',
+ status TEXT NOT NULL DEFAULT 'todo',
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),
+ completed_at TEXT,
+ UNIQUE(conversation_id),
+ FOREIGN KEY (agent_id, workspace_id) REFERENCES agent(id, workspace_id) ON DELETE CASCADE
+);
+
+CREATE INDEX IF NOT EXISTS idx_issue_workspace_status_agent
+ ON issue(workspace_id, status, agent_id);
+
+CREATE INDEX IF NOT EXISTS idx_issue_workspace_updated
+ ON issue(workspace_id, updated_at);
diff --git a/src/web/src/app/(app)/w/[slug]/issues/page.tsx b/src/web/src/app/(app)/w/[slug]/issues/page.tsx
new file mode 100644
index 000000000..276519952
--- /dev/null
+++ b/src/web/src/app/(app)/w/[slug]/issues/page.tsx
@@ -0,0 +1,671 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { Check, CheckCircle2, ExternalLink, File as FileIcon, Loader2, MessageSquare, Plus, Trash2, X } from "lucide-react";
+import Link from "next/link";
+import type { Agent, Artifact, Issue, Message, WsMessage } from "@alook/shared";
+import { useWorkspace } from "@/contexts/workspace-context";
+import { useAgentContext } from "@/contexts/agent-context";
+import { createIssue, deleteIssue, getIssue, listIssues } from "@/lib/api";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Badge } from "@/components/ui/badge";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import {
+ Dialog,
+ DialogContent,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { MarkdownEditor } from "@/components/ui/markdown-editor";
+import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";
+import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetBody } from "@/components/ui/sheet";
+import { AvatarRenderer, parseAvatarUrl } from "@/components/avatar";
+import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from "@/components/ui/context-menu";
+import { cn } from "@/lib/utils";
+import { toast } from "sonner";
+import { Streamdown } from "streamdown";
+
+// TODO: re-enable when Codex CLI fixes image_url serialization bug
+// const MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024;
+// const MAX_ATTACHMENTS = 10;
+
+const ACTIVE_COLUMNS = [
+ { id: "todo", label: "Todo" },
+ { id: "in_progress", label: "In Progress" },
+ { id: "review", label: "Review" },
+] as const;
+
+const TERMINAL_STATUSES = ["done", "closed", "canceled", "failed"];
+
+function statusLabel(status: string) {
+ return status.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
+}
+
+function formatDate(value: string | null) {
+ if (!value) return "";
+ return new Date(value).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });
+}
+
+function formatFileSize(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+}
+
+function AgentAvatar({ agent, size = 24 }: { agent?: Agent | null; size?: number }) {
+ const avatarConfig = parseAvatarUrl(agent?.avatar_url);
+ if (avatarConfig) {
+ return <AvatarRenderer config={avatarConfig} size={size} className="shrink-0 rounded-full" />;
+ }
+ return (
+ <span
+ className="flex shrink-0 items-center justify-center rounded-full border border-border bg-muted text-[11px] font-medium text-muted-foreground"
+ style={{ width: size, height: size }}
+ >
+ {(agent?.name ?? "?").slice(0, 1).toUpperCase()}
+ </span>
+ );
+}
+
+function AgentIdentity({ agent, muted = false }: { agent: Agent; muted?: boolean }) {
+ const email = agent.email_handle ? `${agent.email_handle}@alook.ai` : "";
+ return (
+ <div className="flex min-w-0 items-center gap-2">
+ <AgentAvatar agent={agent} />
+ <div className="flex min-w-0 flex-1 items-center gap-1.5">
+ <div className={cn("truncate text-sm font-medium", muted && "text-muted-foreground")}>{agent.name}</div>
+ {email ? (
+ <div className="truncate text-xs text-muted-foreground">{email}</div>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+function BoardAgentCell({
+ agent,
+}: {
+ agent: Agent;
+}) {
+ const email = agent.email_handle ? `${agent.email_handle}@alook.ai` : "";
+ const isOnline = agent.status === "working" || agent.status === "idle";
+
+ return (
+ <div className="flex min-w-0 items-center gap-3 bg-background/25 px-3 py-3">
+ <div className="relative shrink-0">
+ <AgentAvatar agent={agent} size={32} />
+ <span className={cn(
+ "absolute -bottom-0.5 -right-0.5 size-2.5 rounded-full ring-2 ring-background",
+ agent.status === "working" ? "bg-amber-400" : isOnline ? "bg-emerald-500" : "bg-muted-foreground/40"
+ )} />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-sm font-medium">{agent.name}</div>
+ {email ? (
+ <div className="truncate text-[11px] text-muted-foreground">{email}</div>
+ ) : agent.description ? (
+ <div className="line-clamp-1 text-[11px] text-muted-foreground">{agent.description}</div>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+function IssueCard({
+ issue,
+ selected,
+ onClick,
+ onDelete,
+ agentName,
+ compact = false,
+}: {
+ issue: Issue;
+ selected: boolean;
+ onClick: () => void;
+ onDelete?: () => void;
+ agentName?: string;
+ compact?: boolean;
+}) {
+ return (
+ <ContextMenu>
+ <ContextMenuTrigger
+ render={
+ <button
+ type="button"
+ onClick={onClick}
+ className={cn(
+ "w-full rounded-lg border bg-background/75 p-3 text-left transition-colors cursor-pointer",
+ "hover:bg-accent/70 hover:border-border focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
+ selected ? "border-foreground/30 bg-accent" : "border-border/60"
+ )}
+ />
+ }
+ >
+ <div className="min-w-0">
+ <div className="flex items-start justify-between gap-2">
+ <div className="line-clamp-2 min-w-0 text-sm font-medium leading-5 text-foreground">{issue.title}</div>
+ {issue.status === "in_progress" && (
+ <span className="flex shrink-0 items-center gap-0.5 rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary">
+ <Loader2 className="size-2.5 animate-spin" /> Working
+ </span>
+ )}
+ {issue.status === "review" && (
+ <span className="shrink-0 rounded bg-yellow-500/10 px-1.5 py-0.5 text-[10px] font-medium text-yellow-600 dark:text-yellow-400">Review</span>
+ )}
+ {issue.status === "failed" && (
+ <span className="shrink-0 rounded bg-destructive/10 px-1.5 py-0.5 text-[10px] font-medium text-destructive">Failed</span>
+ )}
+ </div>
+ {issue.description ? (
+ <div className={cn("mt-1 text-xs leading-4 text-muted-foreground", compact ? "line-clamp-1" : "line-clamp-2")}>
+ {issue.description}
+ </div>
+ ) : null}
+ <div className="mt-2 flex min-w-0 items-center justify-between gap-2 text-[11px] text-muted-foreground">
+ {agentName ? <span className="truncate">{agentName}</span> : <span />}
+ <span className="shrink-0">{formatDate(issue.updated_at)}</span>
+ </div>
+ </div>
+ </ContextMenuTrigger>
+ {onDelete && (
+ <ContextMenuContent>
+ <ContextMenuItem className="text-destructive" onClick={onDelete}>
+ <Trash2 className="size-3.5 mr-1.5" />
+ Delete
+ </ContextMenuItem>
+ </ContextMenuContent>
+ )}
+ </ContextMenu>
+ );
+}
+
+function MessageRow({ message }: { message: Message }) {
+ return (
+ <div className="rounded-lg border border-border/60 bg-background/55 p-3">
+ <div className="mb-1 flex items-center justify-between gap-2 text-xs text-muted-foreground">
+ <span className="capitalize">{message.role}</span>
+ <span>{new Date(message.created_at).toLocaleString()}</span>
+ </div>
+ <div className="prose prose-sm dark:prose-invert max-w-none text-sm">
+ <Streamdown>{message.content}</Streamdown>
+ </div>
+ </div>
+ );
+}
+
+function AttachmentList({ artifacts }: { artifacts: Artifact[] }) {
+ if (artifacts.length === 0) return null;
+
+ return (
+ <div>
+ <div className="flex flex-wrap gap-2">
+ {artifacts.map((artifact) => (
+ <div key={artifact.id} className="flex min-w-0 max-w-full items-center gap-2 rounded-lg border border-border/60 bg-background/55 px-3 py-2 text-sm sm:max-w-72">
+ <FileIcon className="size-4 shrink-0 text-muted-foreground" />
+ <div className="min-w-0 flex-1">
+ <div className="truncate font-medium">{artifact.filename}</div>
+ <div className="text-xs text-muted-foreground">{formatFileSize(artifact.size)}</div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+export default function IssuesPage() {
+ const { workspaceId, slug } = useWorkspace();
+ const { agents, loading: agentsLoading, subscribeWs } = useAgentContext();
+ const [issues, setIssues] = useState<Issue[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [creating, setCreating] = useState(false);
+ const [dialogOpen, setDialogOpen] = useState(false);
+ const [assigneeOpen, setAssigneeOpen] = useState(false);
+ const [selectedId, setSelectedId] = useState<string | null>(null);
+ const [detail, setDetail] = useState<{ issue: Issue; messages: Message[]; artifacts: Artifact[] } | null>(null);
+ const [detailLoading, setDetailLoading] = useState(false);
+ const [form, setForm] = useState({ title: "", description: "", agentId: "" });
+
+ const completedIssues = useMemo(
+ () => issues.filter((issue) => TERMINAL_STATUSES.includes(issue.status)),
+ [issues]
+ );
+ const activeIssues = useMemo(
+ () => issues.filter((issue) => !TERMINAL_STATUSES.includes(issue.status)),
+ [issues]
+ );
+ const selectedFormAgent = agents.find((agent) => agent.id === form.agentId) ?? null;
+
+ function agentName(agentId: string) {
+ return agents.find((agent) => agent.id === agentId)?.name ?? agentId;
+ }
+
+ async function reload() {
+ setLoading(true);
+ try {
+ const [active, completed] = await Promise.all([
+ listIssues(workspaceId, { terminal: false }),
+ listIssues(workspaceId, { terminal: true }),
+ ]);
+ setIssues([...active, ...completed]);
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "Failed to load issues");
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ useEffect(() => {
+ reload();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [workspaceId]);
+
+ useEffect(() => {
+ if (!form.agentId && agents.length > 0) {
+ setForm((prev) => ({ ...prev, agentId: agents[0].id }));
+ }
+ }, [agents, form.agentId]);
+
+ async function openIssue(issueId: string) {
+ setSelectedId(issueId);
+ setDetailLoading(true);
+ try {
+ const res = await getIssue(workspaceId, issueId);
+ setDetail(res);
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "Failed to load issue");
+ } finally {
+ setDetailLoading(false);
+ }
+ }
+
+ const detailConvId = detail?.issue.conversation_id ?? null;
+
+ useEffect(() => {
+ return subscribeWs((msg: WsMessage) => {
+ if (msg.type === "conversation.message" && detailConvId && msg.conversationId === detailConvId) {
+ setDetail((prev) => {
+ if (!prev) return prev;
+ if (prev.messages.some((m) => m.id === msg.message.id)) return prev;
+ return { ...prev, messages: [...prev.messages, msg.message] };
+ });
+ if (msg.message.role === "event" && msg.message.content.startsWith("Issue status changed:")) {
+ const match = msg.message.content.match(/-> (\w+)/);
+ if (match) {
+ const newStatus = match[1] as Issue["status"];
+ setDetail((prev) => prev ? { ...prev, issue: { ...prev.issue, status: newStatus } } : prev);
+ setIssues((prev) => prev.map((i) => i.conversation_id === detailConvId ? { ...i, status: newStatus, updated_at: msg.message.created_at } : i));
+ }
+ }
+ }
+ if (msg.type === "task.updated" && (msg.status === "running" || msg.status === "completed" || msg.status === "failed")) {
+ reload();
+ }
+ });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [detailConvId, subscribeWs]);
+
+ async function handleCreate() {
+ if (!form.title.trim() || !form.agentId) return;
+ setCreating(true);
+ try {
+ const res = await createIssue(workspaceId, {
+ agent_id: form.agentId,
+ title: form.title.trim(),
+ description: form.description.trim(),
+ // files: attachments, // TODO: disabled until Codex CLI fixes image_url serialization bug
+ });
+ setIssues((prev) => [res.issue, ...prev]);
+ setDialogOpen(false);
+ setForm({ title: "", description: "", agentId: form.agentId });
+ await openIssue(res.issue.id);
+ toast.success("Issue created");
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "Failed to create issue");
+ } finally {
+ setCreating(false);
+ }
+ }
+
+ const handleDeleteIssue = useCallback(async (issueId: string) => {
+ try {
+ await deleteIssue(workspaceId, issueId);
+ setIssues((prev) => prev.filter((i) => i.id !== issueId));
+ if (selectedId === issueId) {
+ setSelectedId(null);
+ setDetail(null);
+ }
+ toast.success("Issue deleted");
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "Failed to delete issue");
+ }
+ }, [workspaceId, selectedId]);
+
+ // TODO: attachment functions disabled until Codex CLI fixes image_url serialization bug
+ // function handleFileSelect(event: React.ChangeEvent<HTMLInputElement>) { ... }
+ // function removeAttachment(index: number) { ... }
+
+ function resetDraft(nextAgentId = form.agentId) {
+ setForm({ title: "", description: "", agentId: nextAgentId || agents[0]?.id || "" });
+ }
+
+ const boardLoading = loading || agentsLoading;
+ const activeCount = activeIssues.length;
+
+ return (
+ <div className="relative flex h-full min-h-0 flex-col bg-background/30">
+ <div className="flex shrink-0 flex-col gap-3 border-b border-border/60 px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:px-5 sm:py-4">
+ <div className="min-w-0">
+ <h1 className="text-base font-semibold tracking-normal">Issues</h1>
+ <div className="mt-1 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
+ <span>{activeCount} active</span>
+ <span className="text-border">/</span>
+ <span>{completedIssues.length} completed</span>
+ <span className="text-border">/</span>
+ <span>{agents.length} agents</span>
+ </div>
+ </div>
+ <Dialog
+ open={dialogOpen}
+ onOpenChange={(open) => {
+ setDialogOpen(open);
+ if (!open && !creating) resetDraft();
+ }}
+ >
+ <DialogTrigger render={<Button size="sm" className="w-full sm:w-auto" />}>
+ <Plus className="size-4" />
+ New issue
+ </DialogTrigger>
+ <DialogContent className="flex max-h-[min(720px,calc(100dvh-2rem))] grid-rows-none flex-col gap-0 overflow-hidden p-0 sm:max-w-2xl" showCloseButton={false}>
+ <div className="flex shrink-0 items-center border-b border-border/40 px-4 py-2">
+ <DialogTitle className="text-sm tracking-tight">New Issue</DialogTitle>
+ </div>
+
+ <div className="shrink-0 space-y-1 border-b border-border/30 px-4 py-2.5">
+ <div className="flex min-w-0 items-center gap-2 text-sm">
+ <span className="w-18 shrink-0 text-muted-foreground">Title</span>
+ <div className="-ml-1.5 min-w-0 flex-1 rounded-md bg-muted/40">
+ <Input
+ id="issue-title"
+ value={form.title}
+ onChange={(event) => setForm((prev) => ({ ...prev, title: event.target.value }))}
+ placeholder="Short, actionable summary"
+ className="h-7 border-0 bg-transparent px-1.5 text-sm shadow-none focus-visible:ring-0 placeholder:text-muted-foreground/50"
+ disabled={creating}
+ />
+ </div>
+ </div>
+ <div className="flex min-w-0 items-center gap-2 text-sm">
+ <span className="w-18 shrink-0 text-muted-foreground">Assign</span>
+ <Popover open={assigneeOpen} onOpenChange={setAssigneeOpen}>
+ <PopoverTrigger
+ render={
+ <button
+ type="button"
+ disabled={agents.length === 0 || creating}
+ className="-ml-1.5 flex h-7 min-w-0 flex-1 items-center rounded-md bg-muted/40 px-1.5 text-left outline-none transition-colors hover:bg-muted/60 focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50"
+ />
+ }
+ >
+ {selectedFormAgent ? (
+ <AgentIdentity agent={selectedFormAgent} />
+ ) : (
+ <span className="text-sm text-muted-foreground">Select an agent</span>
+ )}
+ </PopoverTrigger>
+ <PopoverContent align="start" className="max-h-64 w-72 overflow-y-auto p-1">
+ {agents.map((agent) => (
+ <button
+ key={agent.id}
+ type="button"
+ onClick={() => {
+ setForm((prev) => ({ ...prev, agentId: agent.id }));
+ setAssigneeOpen(false);
+ }}
+ className="flex w-full items-center justify-between gap-2 rounded-md px-2 py-2 text-left text-sm transition-colors hover:bg-accent hover:text-accent-foreground"
+ >
+ <AgentIdentity agent={agent} />
+ {form.agentId === agent.id ? <Check className="size-3.5 shrink-0" /> : null}
+ </button>
+ ))}
+ </PopoverContent>
+ </Popover>
+ </div>
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto thin-scrollbar px-4 py-3">
+ <MarkdownEditor
+ value={form.description}
+ onChange={(description) => setForm((prev) => ({ ...prev, description }))}
+ placeholder="Context, constraints, expected outcome"
+ minHeight="14rem"
+ variant="seamless"
+ contentType="markdown"
+ agents={agents}
+ className="min-h-full"
+ />
+ </div>
+
+ <div className="flex shrink-0 items-center justify-end gap-1 border-t border-border/30 px-3 py-2">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 px-2 text-xs text-muted-foreground"
+ onClick={() => {
+ setDialogOpen(false);
+ resetDraft();
+ }}
+ disabled={creating}
+ >
+ <X className="mr-1 size-3" />
+ Discard
+ </Button>
+ <Button
+ size="sm"
+ className="h-7 px-3 text-xs"
+ onClick={handleCreate}
+ disabled={creating || !form.title.trim() || !form.agentId}
+ >
+ {creating ? <Loader2 className="mr-1 size-3 animate-spin" /> : <Plus className="mr-1 size-3" />}
+ Create
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </div>
+
+ <div className="hidden min-h-0 flex-1 grid-cols-[minmax(0,1fr)_300px] lg:grid">
+ <div className="min-w-0 overflow-x-auto overflow-y-auto thin-scrollbar p-4">
+ <div className="min-w-190 overflow-hidden rounded-lg border border-border/60 bg-card/60">
+ <div className="grid grid-cols-[240px_repeat(3,minmax(180px,1fr))] border-b border-border/60 bg-muted/30 text-xs font-medium text-muted-foreground">
+ <div className="px-3 py-2">Agent</div>
+ {ACTIVE_COLUMNS.map((col) => (
+ <div key={col.id} className="flex items-center justify-between border-l border-border/60 px-3 py-2">
+ <span>{col.label}</span>
+ <span>{activeIssues.filter((issue) => issue.status === col.id).length}</span>
+ </div>
+ ))}
+ </div>
+ {boardLoading ? (
+ <div className="grid grid-cols-[240px_repeat(3,minmax(180px,1fr))] gap-0 p-3">
+ {Array.from({ length: 12 }).map((_, i) => <Skeleton key={i} className="m-2 h-20" />)}
+ </div>
+ ) : agents.length === 0 ? (
+ <div className="p-8 text-sm text-muted-foreground">No agents in this workspace.</div>
+ ) : (
+ agents.map((agent) => (
+ <div key={agent.id} className="grid min-h-24 grid-cols-[240px_repeat(3,minmax(180px,1fr))] border-b border-border/40 last:border-b-0">
+ <BoardAgentCell agent={agent} />
+ {ACTIVE_COLUMNS.map((col) => {
+ const columnIssues = activeIssues.filter((issue) => issue.agent_id === agent.id && issue.status === col.id);
+ return (
+ <div key={col.id} className="min-h-24 space-y-2 border-l border-border/40 p-2">
+ {columnIssues.length === 0 ? (
+ <div className="flex h-full min-h-14 items-center justify-center rounded-lg border border-dashed border-border/45 text-xs text-muted-foreground/70">
+ Empty
+ </div>
+ ) : (
+ columnIssues.map((issue) => (
+ <IssueCard key={issue.id} issue={issue} selected={selectedId === issue.id} onClick={() => openIssue(issue.id)} onDelete={() => handleDeleteIssue(issue.id)} />
+ ))
+ )}
+ </div>
+ );
+ })}
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+
+ <aside className="min-h-0 border-l border-border/60 bg-muted/20">
+ <div className="flex h-full flex-col">
+ <div className="shrink-0 border-b border-border/60 px-4 py-3">
+ <div className="flex items-center justify-between gap-2 text-sm font-medium">
+ <span className="flex items-center gap-2">
+ <CheckCircle2 className="size-4 text-muted-foreground" />
+ Completed
+ </span>
+ <span className="text-xs text-muted-foreground">{completedIssues.length}</span>
+ </div>
+ </div>
+ <div className="min-h-0 flex-1 space-y-2 overflow-y-auto thin-scrollbar p-3">
+ {completedIssues.length === 0 ? (
+ <div className="py-8 text-center text-xs text-muted-foreground">No completed issues.</div>
+ ) : (
+ completedIssues.map((issue) => (
+ <IssueCard key={issue.id} issue={issue} selected={selectedId === issue.id} onClick={() => openIssue(issue.id)} onDelete={() => handleDeleteIssue(issue.id)} agentName={agentName(issue.agent_id)} compact />
+ ))
+ )}
+ </div>
+ </div>
+ </aside>
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto thin-scrollbar p-3 lg:hidden">
+ {boardLoading ? (
+ <div className="space-y-3">
+ {Array.from({ length: 5 }).map((_, i) => <Skeleton key={i} className="h-28" />)}
+ </div>
+ ) : agents.length === 0 ? (
+ <div className="rounded-lg border border-border/60 bg-card/60 p-8 text-center text-sm text-muted-foreground">No agents in this workspace.</div>
+ ) : (
+ <div className="space-y-4">
+ {agents.map((agent) => {
+ const agentIssues = activeIssues.filter((issue) => issue.agent_id === agent.id);
+ return (
+ <section key={agent.id} className="rounded-lg border border-border/60 bg-card/60">
+ <div className="flex items-center justify-between gap-3 border-b border-border/50 px-3 py-2">
+ <div className="min-w-0 flex-1">
+ <AgentIdentity agent={agent} />
+ </div>
+ <Badge variant="outline" className="shrink-0">{agentIssues.length} active</Badge>
+ </div>
+ <div className="space-y-3 p-3">
+ {ACTIVE_COLUMNS.map((col) => {
+ const columnIssues = agentIssues.filter((issue) => issue.status === col.id);
+ return (
+ <div key={col.id} className="space-y-2">
+ <div className="flex items-center justify-between text-xs font-medium text-muted-foreground">
+ <span>{col.label}</span>
+ <span>{columnIssues.length}</span>
+ </div>
+ {columnIssues.length === 0 ? (
+ <div className="rounded-lg border border-dashed border-border/45 px-3 py-4 text-center text-xs text-muted-foreground/70">Empty</div>
+ ) : (
+ columnIssues.map((issue) => (
+ <IssueCard key={issue.id} issue={issue} selected={selectedId === issue.id} onClick={() => openIssue(issue.id)} onDelete={() => handleDeleteIssue(issue.id)} compact />
+ ))
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </section>
+ );
+ })}
+ <section className="rounded-lg border border-border/60 bg-card/60">
+ <div className="flex items-center justify-between border-b border-border/50 px-3 py-2 text-sm font-medium">
+ <span className="flex items-center gap-2"><CheckCircle2 className="size-4 text-muted-foreground" />Completed</span>
+ <Badge variant="outline">{completedIssues.length}</Badge>
+ </div>
+ <div className="space-y-2 p-3">
+ {completedIssues.length === 0 ? (
+ <div className="rounded-lg border border-dashed border-border/45 px-3 py-4 text-center text-xs text-muted-foreground/70">No completed issues.</div>
+ ) : (
+ completedIssues.map((issue) => (
+ <IssueCard key={issue.id} issue={issue} selected={selectedId === issue.id} onClick={() => openIssue(issue.id)} onDelete={() => handleDeleteIssue(issue.id)} agentName={agentName(issue.agent_id)} compact />
+ ))
+ )}
+ </div>
+ </section>
+ </div>
+ )}
+ </div>
+
+ <Sheet open={!!selectedId} onOpenChange={(open) => { if (!open) { setSelectedId(null); setDetail(null); } }}>
+ <SheetContent side="right" showCloseButton>
+ <SheetHeader>
+ <SheetTitle>
+ {detailLoading || !detail ? (
+ <Skeleton className="h-5 w-56" />
+ ) : (
+ <span className="flex items-center gap-1.5">
+ <Badge variant={detail.issue.status === "in_progress" ? "default" : "outline"} className="shrink-0 text-[10px] px-1.5 py-0">
+ {detail.issue.status === "in_progress" && <Loader2 className="mr-1 size-3 animate-spin" />}
+ {statusLabel(detail.issue.status)}
+ </Badge>
+ <span className="line-clamp-2 text-sm font-semibold">{detail.issue.title}</span>
+ </span>
+ )}
+ </SheetTitle>
+ </SheetHeader>
+ <SheetBody>
+ {detailLoading || !detail ? (
+ <div className="space-y-3">
+ <Skeleton className="h-24" />
+ <Skeleton className="h-16" />
+ </div>
+ ) : (
+ <div className="space-y-4">
+ <div className="prose prose-sm dark:prose-invert max-w-none rounded-lg border border-border/60 bg-background/55 p-3">
+ <Streamdown>{detail.issue.description || "No description."}</Streamdown>
+ </div>
+ <AttachmentList artifacts={detail.artifacts ?? []} />
+ <div className="space-y-2">
+ <div className="flex items-center justify-between gap-2 text-sm font-medium">
+ <span className="flex items-center gap-2">
+ <MessageSquare className="size-4 text-muted-foreground" />
+ Conversation
+ </span>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Link
+ href={`/w/${slug}/agents/${detail.issue.agent_id}?conv=${detail.issue.conversation_id}`}
+ aria-label="Open chat"
+ className="flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
+ />
+ }
+ >
+ <ExternalLink className="size-3.5" />
+ </TooltipTrigger>
+ <TooltipContent side="left">Open chat</TooltipContent>
+ </Tooltip>
+ </div>
+ {detail.messages.length === 0 ? (
+ <div className="text-xs text-muted-foreground">No messages yet.</div>
+ ) : (
+ detail.messages.map((message) => <MessageRow key={message.id} message={message} />)
+ )}
+ </div>
+ </div>
+ )}
+ </SheetBody>
+ </SheetContent>
+ </Sheet>
+ </div>
+ );
+}
diff --git a/src/web/src/app/api/agents/[id]/active-tasks/route.test.ts b/src/web/src/app/api/agents/[id]/active-tasks/route.test.ts
index e8aa57e60..7c548669f 100644
--- a/src/web/src/app/api/agents/[id]/active-tasks/route.test.ts
+++ b/src/web/src/app/api/agents/[id]/active-tasks/route.test.ts
@@ -48,6 +48,7 @@ describe("GET /api/agents/[id]/active-tasks", () => {
mockListActiveTasksByAgent.mockResolvedValue([
{ id: "t1", status: "running", type: "user_dm_message", conversationId: "c1", createdAt: "2026-01-01T00:00:00Z" },
{ id: "t2", status: "queued", type: "email_notification", conversationId: "c2", createdAt: "2026-01-01T00:01:00Z" },
+ { id: "t3", status: "running", type: "issue_event", conversationId: "c3", createdAt: "2026-01-01T00:02:00Z" },
]);
const res = await GET(
@@ -57,7 +58,7 @@ describe("GET /api/agents/[id]/active-tasks", () => {
const body = await res.json();
expect(res.status).toBe(200);
- expect(body.tasks).toHaveLength(2);
+ expect(body.tasks).toHaveLength(3);
expect(body.tasks[0]).toEqual({
id: "t1",
status: "running",
@@ -70,6 +71,12 @@ describe("GET /api/agents/[id]/active-tasks", () => {
type: "email_notification",
created_at: "2026-01-01T00:01:00Z",
});
+ expect(body.tasks[2]).toEqual({
+ id: "t3",
+ status: "running",
+ type: "issue_event",
+ created_at: "2026-01-01T00:02:00Z",
+ });
});
it("returns 404 when agent not found", async () => {
diff --git a/src/web/src/app/api/artifacts/[id]/content/route.test.ts b/src/web/src/app/api/artifacts/[id]/content/route.test.ts
new file mode 100644
index 000000000..dffa25617
--- /dev/null
+++ b/src/web/src/app/api/artifacts/[id]/content/route.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockGetArtifact = vi.fn();
+const mockBucketGet = vi.fn();
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({
+ env: {
+ DB: {},
+ EMAIL_BUCKET: { get: (...a: unknown[]) => mockBucketGet(...a) },
+ },
+ })),
+}));
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ artifact: { getArtifact: (...a: unknown[]) => mockGetArtifact(...a) },
+ },
+ };
+});
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", workspaceId: "w1", params });
+ },
+}));
+
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+
+import { GET } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+describe("GET /api/artifacts/[id]/content", () => {
+ it("downloads artifact content for machine-token workspace access", async () => {
+ mockGetArtifact.mockResolvedValue({
+ id: "art_1",
+ r2Key: "artifacts/w1/ag1/c1/art_1/brief.md",
+ filename: "brief.md",
+ contentType: "text/markdown",
+ size: 5,
+ });
+ mockBucketGet.mockResolvedValue({ body: new Blob(["hello"]).stream() });
+
+ const res = await GET(new NextRequest("http://localhost/api/artifacts/art_1/content?workspace_id=w1"), { params: { id: "art_1" } } as any);
+
+ expect(res.status).toBe(200);
+ expect(res.headers.get("Content-Type")).toBe("text/markdown");
+ expect(await res.text()).toBe("hello");
+ expect(mockBucketGet).toHaveBeenCalledWith("artifacts/w1/ag1/c1/art_1/brief.md");
+ });
+
+ it("serves non-ASCII filenames with RFC 5987 content disposition", async () => {
+ mockGetArtifact.mockResolvedValue({
+ id: "art_1",
+ r2Key: "artifacts/w1/ag1/c1/art_1/report.pdf",
+ filename: "深圳市小汽车增量指标证明文件.pdf",
+ contentType: "application/pdf",
+ size: 5,
+ });
+ mockBucketGet.mockResolvedValue({ body: new Blob(["hello"]).stream() });
+
+ const res = await GET(new NextRequest("http://localhost/api/artifacts/art_1/content?workspace_id=w1&download"), { params: { id: "art_1" } } as any);
+
+ expect(res.status).toBe(200);
+ expect(res.headers.get("Content-Disposition")).toContain("attachment; filename=");
+ expect(res.headers.get("Content-Disposition")).toContain("filename*=UTF-8''%E6%B7%B1%E5%9C%B3");
+ });
+});
diff --git a/src/web/src/app/api/artifacts/[id]/content/route.ts b/src/web/src/app/api/artifacts/[id]/content/route.ts
index 63a33ff66..7fa1df12f 100644
--- a/src/web/src/app/api/artifacts/[id]/content/route.ts
+++ b/src/web/src/app/api/artifacts/[id]/content/route.ts
@@ -6,6 +6,16 @@ import { withAuth } from "@/lib/middleware/auth";
import { withWorkspaceMember } from "@/lib/middleware/workspace";
import { writeError } from "@/lib/middleware/helpers";
+function asciiFallbackFilename(filename: string): string {
+ const fallback = filename.replace(/[^\x20-\x7E]/g, "_").replace(/["\\]/g, "_").trim();
+ return fallback || "download";
+}
+
+function contentDisposition(disposition: "inline" | "attachment", filename: string): string {
+ const fallback = asciiFallbackFilename(filename);
+ return `${disposition}; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(filename)}`;
+}
+
export const GET = withAuth(async (req: NextRequest, ctx) => {
const ws = await withWorkspaceMember(req, ctx);
if (ws instanceof Response) return ws;
@@ -31,9 +41,9 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
"Content-Length": String(row.size),
};
if (download !== null) {
- headers["Content-Disposition"] = `attachment; filename="${row.filename.replace(/"/g, '\\"')}"`;
+ headers["Content-Disposition"] = contentDisposition("attachment", row.filename);
} else {
- headers["Content-Disposition"] = `inline; filename="${row.filename.replace(/"/g, '\\"')}"`;
+ headers["Content-Disposition"] = contentDisposition("inline", row.filename);
}
return new Response(object.body, { headers });
diff --git a/src/web/src/app/api/artifacts/[id]/route.test.ts b/src/web/src/app/api/artifacts/[id]/route.test.ts
new file mode 100644
index 000000000..9b2e1a999
--- /dev/null
+++ b/src/web/src/app/api/artifacts/[id]/route.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockGetArtifact = vi.fn();
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ artifact: {
+ getArtifact: (...a: unknown[]) => mockGetArtifact(...a),
+ artifactToResponse: (row: any) => ({ id: row.id, filename: row.filename }),
+ },
+ },
+ };
+});
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", workspaceId: "w1", params });
+ },
+}));
+
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+
+import { GET } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+describe("GET /api/artifacts/[id]", () => {
+ it("returns artifact metadata for machine-token workspace access", async () => {
+ mockGetArtifact.mockResolvedValue({ id: "art_1", filename: "brief.md" });
+ const res = await GET(new NextRequest("http://localhost/api/artifacts/art_1?workspace_id=w1"), { params: { id: "art_1" } } as any);
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ id: "art_1", filename: "brief.md" });
+ expect(mockGetArtifact).toHaveBeenCalledWith({}, "art_1", "w1");
+ });
+});
diff --git a/src/web/src/app/api/issues/[id]/route.test.ts b/src/web/src/app/api/issues/[id]/route.test.ts
new file mode 100644
index 000000000..2011fc3e7
--- /dev/null
+++ b/src/web/src/app/api/issues/[id]/route.test.ts
@@ -0,0 +1,118 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockGetIssue = vi.fn();
+const mockListIssueMessages = vi.fn();
+const mockUpdateIssue = vi.fn();
+const mockDeleteIssue = vi.fn();
+const mockCreateMessage = vi.fn();
+const mockListArtifactsByConversation = vi.fn();
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ issue: {
+ getIssue: (...a: unknown[]) => mockGetIssue(...a),
+ listIssueMessages: (...a: unknown[]) => mockListIssueMessages(...a),
+ updateIssue: (...a: unknown[]) => mockUpdateIssue(...a),
+ deleteIssue: (...a: unknown[]) => mockDeleteIssue(...a),
+ },
+ message: { createMessage: (...a: unknown[]) => mockCreateMessage(...a) },
+ artifact: {
+ listArtifactsByConversation: (...a: unknown[]) => mockListArtifactsByConversation(...a),
+ artifactToResponse: (a: any) => ({ id: a.id, filename: a.filename }),
+ },
+ },
+ };
+});
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ },
+}));
+
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+
+vi.mock("@/lib/api/responses", () => ({
+ issueToResponse: (i: any) => ({ id: i.id, status: i.status, conversation_id: i.conversationId }),
+ messageToResponse: (m: any) => ({ id: m.id, role: m.role, content: m.content }),
+}));
+
+import { GET, PATCH, POST, DELETE } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+describe("GET /api/issues/[id]", () => {
+ it("returns issue and messages", async () => {
+ mockGetIssue.mockResolvedValue({ id: "iss_1", status: "todo", conversationId: "c1" });
+ mockListIssueMessages.mockResolvedValue([{ id: "m1", role: "event", content: "Created" }]);
+ mockListArtifactsByConversation.mockResolvedValue([{ id: "art_1", filename: "brief.md" }]);
+ const res = await GET(new NextRequest("http://localhost/api/issues/iss_1"), { params: { id: "iss_1" } } as any);
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({
+ issue: { id: "iss_1", status: "todo", conversation_id: "c1" },
+ messages: [{ id: "m1", role: "event", content: "Created" }],
+ artifacts: [{ id: "art_1", filename: "brief.md" }],
+ });
+ expect(mockListArtifactsByConversation).toHaveBeenCalledWith({}, "c1", "w1");
+ });
+});
+
+describe("PATCH /api/issues/[id]", () => {
+ it("updates status and records status transition", async () => {
+ mockGetIssue.mockResolvedValue({ id: "iss_1", status: "todo", conversationId: "c1" });
+ mockUpdateIssue.mockResolvedValue({ id: "iss_1", status: "in_progress", conversationId: "c1" });
+ const req = new NextRequest("http://localhost/api/issues/iss_1", {
+ method: "PATCH",
+ body: JSON.stringify({ status: "in_progress" }),
+ });
+ const res = await PATCH(req, { params: { id: "iss_1" } } as any);
+ expect(res.status).toBe(200);
+ expect(mockUpdateIssue).toHaveBeenCalledWith({}, "iss_1", "w1", { title: undefined, description: undefined, status: "in_progress" });
+ expect(mockCreateMessage).toHaveBeenCalledWith({}, expect.objectContaining({ role: "event", content: "Issue status changed: todo -> in_progress" }));
+ });
+});
+
+describe("POST /api/issues/[id]", () => {
+ it("adds a user comment for browser callers", async () => {
+ mockGetIssue.mockResolvedValue({ id: "iss_1", status: "todo", conversationId: "c1" });
+ mockCreateMessage.mockResolvedValue({ id: "m1", role: "user", content: "Looks good" });
+ mockUpdateIssue.mockResolvedValue({ id: "iss_1" });
+ const req = new NextRequest("http://localhost/api/issues/iss_1", {
+ method: "POST",
+ body: JSON.stringify({ content: "Looks good" }),
+ });
+ const res = await POST(req, { params: { id: "iss_1" } } as any);
+ expect(res.status).toBe(201);
+ expect(mockCreateMessage).toHaveBeenCalledWith({}, expect.objectContaining({ role: "user", content: "Looks good" }));
+ });
+});
+
+describe("DELETE /api/issues/[id]", () => {
+ it("deletes the issue and returns 204", async () => {
+ mockDeleteIssue.mockResolvedValue({ id: "iss_1" });
+ const req = new NextRequest("http://localhost/api/issues/iss_1", { method: "DELETE" });
+ const res = await DELETE(req, { params: { id: "iss_1" } } as any);
+ expect(res.status).toBe(204);
+ expect(mockDeleteIssue).toHaveBeenCalledWith({}, "iss_1", "w1");
+ });
+
+ it("returns 404 when issue does not exist", async () => {
+ mockDeleteIssue.mockResolvedValue(null);
+ const req = new NextRequest("http://localhost/api/issues/iss_999", { method: "DELETE" });
+ const res = await DELETE(req, { params: { id: "iss_999" } } as any);
+ expect(res.status).toBe(404);
+ });
+});
diff --git a/src/web/src/app/api/issues/[id]/route.ts b/src/web/src/app/api/issues/[id]/route.ts
new file mode 100644
index 000000000..08ecebaab
--- /dev/null
+++ b/src/web/src/app/api/issues/[id]/route.ts
@@ -0,0 +1,117 @@
+import { NextRequest } from "next/server";
+import { getCloudflareContext } from "@opennextjs/cloudflare";
+import {
+ CreateIssueCommentRequestSchema,
+ UpdateIssueRequestSchema,
+ queries,
+} from "@alook/shared";
+import { getDb } from "@/lib/db";
+import { withAuth } from "@/lib/middleware/auth";
+import { withWorkspaceMember } from "@/lib/middleware/workspace";
+import { parseBody, writeError, writeJSON } from "@/lib/middleware/helpers";
+import { issueToResponse, messageToResponse } from "@/lib/api/responses";
+
+export const GET = withAuth(async (req: NextRequest, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext();
+ const db = getDb((env as Env).DB);
+ const id = ctx.params?.id;
+ if (!id) return writeError("issue id is required", 400);
+
+ const issue = await queries.issue.getIssue(db, id, ws.workspaceId);
+ if (!issue) return writeError("issue not found", 404);
+ const agentId = req.nextUrl.searchParams.get("agentId");
+ if (agentId && issue.agentId !== agentId) return writeError("issue does not belong to agent", 403);
+
+ const messages = await queries.issue.listIssueMessages(db, id, ws.workspaceId);
+ const artifacts = await queries.artifact.listArtifactsByConversation(
+ db,
+ issue.conversationId,
+ ws.workspaceId,
+ );
+ return writeJSON({
+ issue: issueToResponse(issue),
+ messages: (messages ?? []).map(messageToResponse),
+ artifacts: artifacts.map(queries.artifact.artifactToResponse),
+ });
+});
+
+export const PATCH = withAuth(async (req: NextRequest, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext();
+ const db = getDb((env as Env).DB);
+ const id = ctx.params?.id;
+ if (!id) return writeError("issue id is required", 400);
+
+ const existing = await queries.issue.getIssue(db, id, ws.workspaceId);
+ if (!existing) return writeError("issue not found", 404);
+ const agentId = req.nextUrl.searchParams.get("agentId");
+ if (agentId && existing.agentId !== agentId) return writeError("issue does not belong to agent", 403);
+
+ const [body, err] = await parseBody(req, UpdateIssueRequestSchema);
+ if (err) return err;
+
+ const updated = await queries.issue.updateIssue(db, id, ws.workspaceId, {
+ title: body.title,
+ description: body.description,
+ status: body.status,
+ });
+ if (!updated) return writeError("issue not found", 404);
+
+ if (body.status && body.status !== existing.status) {
+ await queries.message.createMessage(db, {
+ conversationId: existing.conversationId,
+ role: "event",
+ content: `Issue status changed: ${existing.status} -> ${body.status}`,
+ });
+ }
+
+ return writeJSON(issueToResponse(updated));
+});
+
+export const DELETE = withAuth(async (req: NextRequest, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext();
+ const db = getDb((env as Env).DB);
+ const id = ctx.params?.id;
+ if (!id) return writeError("issue id is required", 400);
+
+ const deleted = await queries.issue.deleteIssue(db, id, ws.workspaceId);
+ if (!deleted) return writeError("issue not found", 404);
+
+ return new Response(null, { status: 204 });
+});
+
+export const POST = withAuth(async (req: NextRequest, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext();
+ const db = getDb((env as Env).DB);
+ const id = ctx.params?.id;
+ if (!id) return writeError("issue id is required", 400);
+
+ const issue = await queries.issue.getIssue(db, id, ws.workspaceId);
+ if (!issue) return writeError("issue not found", 404);
+ const agentId = req.nextUrl.searchParams.get("agentId");
+ if (agentId && issue.agentId !== agentId) return writeError("issue does not belong to agent", 403);
+
+ const [body, err] = await parseBody(req, CreateIssueCommentRequestSchema);
+ if (err) return err;
+
+ const message = await queries.message.createMessage(db, {
+ conversationId: issue.conversationId,
+ role: ctx.workspaceId ? "assistant" : "user",
+ content: body.content,
+ });
+
+ await queries.issue.updateIssue(db, id, ws.workspaceId, {});
+
+ return writeJSON({ message: messageToResponse(message) }, 201);
+});
diff --git a/src/web/src/app/api/issues/route.test.ts b/src/web/src/app/api/issues/route.test.ts
new file mode 100644
index 000000000..5b3e6bbcd
--- /dev/null
+++ b/src/web/src/app/api/issues/route.test.ts
@@ -0,0 +1,158 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockGetAgent = vi.fn();
+const mockListIssues = vi.fn();
+const mockCreateConversation = vi.fn();
+const mockCreateIssue = vi.fn();
+const mockCreateMessage = vi.fn();
+const mockSetLatestTask = vi.fn();
+const mockEnqueueTask = vi.fn();
+const mockCreateArtifact = vi.fn();
+const mockR2Put = vi.fn();
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({
+ env: {
+ DB: {},
+ EMAIL_BUCKET: { put: (...a: unknown[]) => mockR2Put(...a) },
+ },
+ })),
+}));
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },
+ issue: {
+ listIssues: (...a: unknown[]) => mockListIssues(...a),
+ createIssue: (...a: unknown[]) => mockCreateIssue(...a),
+ setLatestTask: (...a: unknown[]) => mockSetLatestTask(...a),
+ },
+ conversation: { createConversation: (...a: unknown[]) => mockCreateConversation(...a) },
+ message: { createMessage: (...a: unknown[]) => mockCreateMessage(...a) },
+ artifact: { createArtifact: (...a: unknown[]) => mockCreateArtifact(...a) },
+ },
+ };
+});
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ },
+}));
+
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+
+vi.mock("@/lib/services/task", () => ({
+ TaskService: function () {
+ return { enqueueTask: mockEnqueueTask };
+ },
+}));
+
+vi.mock("@/lib/broadcast", () => ({ broadcastToUser: vi.fn(() => Promise.resolve()) }));
+
+vi.mock("@/lib/api/responses", () => ({
+ issueToResponse: (i: any) => ({ id: i.id, agent_id: i.agentId, title: i.title, status: i.status }),
+ messageToResponse: (m: any) => ({ id: m.id, content: m.content }),
+ taskToResponse: (t: any) => ({ id: t.id, type: t.type }),
+}));
+
+import { GET, POST } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+describe("GET /api/issues", () => {
+ it("lists workspace issues with filters", async () => {
+ mockGetAgent.mockResolvedValue({ id: "ag_1" });
+ mockListIssues.mockResolvedValue([{ id: "iss_1", agentId: "ag_1", title: "Fix", status: "todo" }]);
+ const res = await GET(new NextRequest("http://localhost/api/issues?agentId=ag_1&terminal=false"), {} as any);
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual([{ id: "iss_1", agent_id: "ag_1", title: "Fix", status: "todo" }]);
+ expect(mockListIssues).toHaveBeenCalledWith({}, "w1", { agentId: "ag_1", status: undefined, terminal: false });
+ });
+
+ it("rejects invalid status", async () => {
+ const res = await GET(new NextRequest("http://localhost/api/issues?status=bad"), {} as any);
+ expect(res.status).toBe(400);
+ });
+});
+
+describe("POST /api/issues", () => {
+ it("creates issue conversation and dispatches issue task", async () => {
+ mockGetAgent.mockResolvedValue({ id: "ag_1", ownerId: "u1", runtimeId: "rt1" });
+ mockCreateConversation.mockResolvedValue({ id: "c1" });
+ mockCreateIssue.mockResolvedValue({ id: "iss_1", agentId: "ag_1", title: "Fix", description: "Body", status: "todo", conversationId: "c1" });
+ mockCreateMessage.mockResolvedValue({ id: "m1", content: "Issue created: Fix" });
+ mockEnqueueTask.mockResolvedValue({ id: "t1", agentId: "ag_1", type: "issue_event" });
+ mockSetLatestTask.mockResolvedValue({ id: "iss_1", agentId: "ag_1", title: "Fix", description: "Body", status: "todo", conversationId: "c1", latestTaskId: "t1" });
+
+ const req = new NextRequest("http://localhost/api/issues", {
+ method: "POST",
+ body: JSON.stringify({ agent_id: "ag_1", title: "Fix", description: "Body" }),
+ });
+ const res = await POST(req, {} as any);
+ expect(res.status).toBe(201);
+ expect(mockCreateConversation).toHaveBeenCalledWith({}, expect.objectContaining({ type: "issue_event", agentId: "ag_1" }));
+ expect(mockEnqueueTask).toHaveBeenCalledWith("ag_1", "c1", "w1", expect.stringContaining("Issue iss_1"), "issue_event", expect.objectContaining({ contextKey: "iss_1" }));
+ });
+
+ it("uploads attachments and includes attachment ids in the issue task context", async () => {
+ mockGetAgent.mockResolvedValue({ id: "ag_1", ownerId: "u1", runtimeId: "rt1" });
+ mockCreateConversation.mockResolvedValue({ id: "c1" });
+ mockCreateIssue.mockResolvedValue({ id: "iss_1", agentId: "ag_1", title: "Fix", description: "Body", status: "todo", conversationId: "c1" });
+ mockCreateMessage.mockResolvedValue({ id: "m1", content: "Issue created: Fix", attachmentIds: '["art_1"]' });
+ mockCreateArtifact.mockResolvedValue({ id: "art_1" });
+ mockR2Put.mockResolvedValue(undefined);
+ mockEnqueueTask.mockResolvedValue({ id: "t1", agentId: "ag_1", type: "issue_event" });
+ mockSetLatestTask.mockResolvedValue({ id: "iss_1", agentId: "ag_1", title: "Fix", description: "Body", status: "todo", conversationId: "c1", latestTaskId: "t1" });
+
+ const formData = new FormData();
+ formData.append("agent_id", "ag_1");
+ formData.append("title", "Fix");
+ formData.append("description", "Body");
+ formData.append("file", new File(["hello"], "note.md", { type: "text/markdown" }));
+
+ const req = new NextRequest("http://localhost/api/issues", {
+ method: "POST",
+ body: formData,
+ });
+ const res = await POST(req, {} as any);
+
+ expect(res.status).toBe(201);
+ expect(mockR2Put).toHaveBeenCalledTimes(1);
+ expect(mockCreateArtifact).toHaveBeenCalledWith({}, expect.objectContaining({
+ conversationId: "c1",
+ agentId: "ag_1",
+ workspaceId: "w1",
+ filename: "note.md",
+ contentType: "text/markdown",
+ size: 5,
+ source: "attachment",
+ }));
+ expect(mockCreateMessage).toHaveBeenCalledWith({}, expect.objectContaining({
+ attachmentIds: expect.stringContaining("art_"),
+ }));
+ expect(mockEnqueueTask).toHaveBeenCalledWith(
+ "ag_1",
+ "c1",
+ "w1",
+ expect.stringContaining("Issue iss_1"),
+ "issue_event",
+ expect.objectContaining({
+ contextKey: "iss_1",
+ context: expect.objectContaining({
+ issue_id: "iss_1",
+ attachment_ids: [expect.stringContaining("art_")],
+ }),
+ }),
+ );
+ });
+});
diff --git a/src/web/src/app/api/issues/route.ts b/src/web/src/app/api/issues/route.ts
new file mode 100644
index 000000000..a22a19a17
--- /dev/null
+++ b/src/web/src/app/api/issues/route.ts
@@ -0,0 +1,214 @@
+import { NextRequest } from "next/server";
+import { getCloudflareContext } from "@opennextjs/cloudflare";
+import { CreateIssueRequestSchema, IssueStatusSchema, queries, TASK_TYPES } from "@alook/shared";
+import { nanoid } from "nanoid";
+import { getDb } from "@/lib/db";
+import { withAuth } from "@/lib/middleware/auth";
+import { withWorkspaceMember } from "@/lib/middleware/workspace";
+import { parseBody, writeError, writeJSON } from "@/lib/middleware/helpers";
+import { issueToResponse, messageToResponse, taskToResponse } from "@/lib/api/responses";
+import { TaskService } from "@/lib/services/task";
+import { broadcastToUser } from "@/lib/broadcast";
+import type { IssueStatusType } from "@alook/shared";
+
+const MAX_FILE_SIZE = 10 * 1024 * 1024;
+const MAX_FILES = 10;
+
+function sanitizeFilename(name: string): string {
+ return name.replace(/[/\\]/g, "_").replace(/\.\./g, "_").slice(0, 255) || "file";
+}
+
+function buildIssuePrompt(issue: { id: string; title: string; description: string }) {
+ const description = issue.description.trim() || "(no description)";
+ return [
+ `Issue ${issue.id}: ${issue.title}`,
+ "",
+ description,
+ "",
+ "Use the issue CLI to keep this issue updated:",
+ `- alook issue show --agent_id <your_agent_id> --issue_id ${issue.id}`,
+ `- alook issue update --agent_id <your_agent_id> --issue_id ${issue.id} --status in_progress`,
+ `- alook issue comment --agent_id <your_agent_id> --issue_id ${issue.id} --body-file <path>`,
+ `- alook issue update --agent_id <your_agent_id> --issue_id ${issue.id} --status done`,
+ ].join("\n");
+}
+
+export const GET = withAuth(async (req: NextRequest, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext();
+ const db = getDb((env as Env).DB);
+
+ const agentId = req.nextUrl.searchParams.get("agentId") ?? undefined;
+ const status = req.nextUrl.searchParams.get("status") ?? undefined;
+ const terminalParam = req.nextUrl.searchParams.get("terminal");
+
+ let parsedStatus: IssueStatusType | undefined;
+ if (status) {
+ const parsed = IssueStatusSchema.safeParse(status);
+ if (!parsed.success) return writeError("invalid issue status", 400);
+ parsedStatus = parsed.data;
+ }
+
+ if (agentId) {
+ const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId);
+ if (!agent) return writeError("agent not found in workspace", 404);
+ }
+
+ const rows = await queries.issue.listIssues(db, ws.workspaceId, {
+ agentId,
+ status: parsedStatus,
+ terminal: terminalParam === null ? undefined : terminalParam === "true",
+ });
+
+ return writeJSON(rows.map(issueToResponse));
+});
+
+export const POST = withAuth(async (req: NextRequest, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext();
+ const db = getDb((env as Env).DB);
+ const bucket = (env as Env).EMAIL_BUCKET;
+
+ const contentType = req.headers.get("content-type") ?? "";
+ const isMultipart = contentType.includes("multipart/form-data");
+
+ let body: { agent_id: string; title: string; description: string };
+ const files: File[] = [];
+
+ if (isMultipart) {
+ let formData: FormData;
+ try {
+ formData = await req.formData();
+ } catch {
+ return writeError("invalid form data", 400);
+ }
+ const parsed = CreateIssueRequestSchema.safeParse({
+ agent_id: formData.get("agent_id"),
+ title: formData.get("title"),
+ description: formData.get("description") ?? "",
+ });
+ if (!parsed.success) {
+ return writeError("validation error", 400);
+ }
+ body = parsed.data;
+ for (const [key, value] of formData.entries()) {
+ if (key === "file" && value instanceof File) {
+ files.push(value);
+ }
+ }
+ } else {
+ const [parsedBody, err] = await parseBody(req, CreateIssueRequestSchema);
+ if (err) return err;
+ body = parsedBody;
+ }
+
+ if (files.length > MAX_FILES) {
+ return writeError(`too many files (max ${MAX_FILES})`, 400);
+ }
+ for (const file of files) {
+ if (file.size > MAX_FILE_SIZE) {
+ return writeError(`file "${file.name}" exceeds 10 MB limit`, 413);
+ }
+ }
+
+ const agent = await queries.agent.getAgent(db, body.agent_id, ws.workspaceId, ctx.userId);
+ if (!agent) return writeError("agent not found in workspace", 404);
+ if (!agent.ownerId) return writeError("agent has no owner", 400);
+
+ const conversation = await queries.conversation.createConversation(db, {
+ workspaceId: ws.workspaceId,
+ agentId: body.agent_id,
+ userId: ctx.userId,
+ title: `[Issue] ${body.title}`.slice(0, 120),
+ type: TASK_TYPES.ISSUE_EVENT,
+ });
+
+ const created = await queries.issue.createIssue(db, {
+ workspaceId: ws.workspaceId,
+ agentId: body.agent_id,
+ creatorUserId: ctx.userId,
+ conversationId: conversation.id,
+ title: body.title,
+ description: body.description,
+ });
+
+ const artifactIds: string[] = [];
+ for (const file of files) {
+ const filename = sanitizeFilename(file.name);
+ const fileContentType = file.type || "application/octet-stream";
+ const artifactId = "art_" + nanoid();
+ const r2Key = `artifacts/${ws.workspaceId}/${body.agent_id}/${conversation.id}/${artifactId}/${filename}`;
+
+ await bucket.put(r2Key, await file.arrayBuffer(), {
+ httpMetadata: { contentType: fileContentType },
+ });
+
+ await queries.artifact.createArtifact(db, {
+ id: artifactId,
+ conversationId: conversation.id,
+ agentId: body.agent_id,
+ workspaceId: ws.workspaceId,
+ filename,
+ contentType: fileContentType,
+ size: file.size,
+ r2Key,
+ source: "attachment",
+ });
+
+ artifactIds.push(artifactId);
+ }
+
+ const eventMessage = await queries.message.createMessage(db, {
+ conversationId: conversation.id,
+ role: "event",
+ content: `Issue created: ${created.title}`,
+ attachmentIds: artifactIds.length > 0 ? JSON.stringify(artifactIds) : null,
+ });
+
+ const prompt = buildIssuePrompt({
+ id: created.id,
+ title: created.title,
+ description: created.description,
+ });
+
+ const taskService = new TaskService(db);
+ try {
+ const task = await taskService.enqueueTask(
+ created.agentId,
+ conversation.id,
+ ws.workspaceId,
+ prompt,
+ TASK_TYPES.ISSUE_EVENT,
+ {
+ contextKey: created.id,
+ context: {
+ issue_id: created.id,
+ ...(artifactIds.length > 0 ? { attachment_ids: artifactIds } : {}),
+ },
+ traceId: "tr_" + nanoid(),
+ parentTaskId: null,
+ }
+ );
+ const issue = await queries.issue.setLatestTask(db, created.id, ws.workspaceId, task.id) ?? created;
+ broadcastToUser(ctx.userId, { type: "task.updated", taskId: task.id, agentId: task.agentId, status: "queued" }).catch(() => {});
+ return writeJSON(
+ {
+ issue: issueToResponse(issue),
+ message: messageToResponse(eventMessage),
+ task: taskToResponse(task),
+ },
+ 201
+ );
+ } catch (taskErr) {
+ await queries.message.createMessage(db, {
+ conversationId: conversation.id,
+ role: "event",
+ content: `Issue dispatch failed: ${taskErr instanceof Error ? taskErr.message : "unknown error"}`,
+ });
+ return writeError(taskErr instanceof Error ? taskErr.message : "failed to dispatch issue", 500);
+ }
+});
diff --git a/src/web/src/components/agent-chat/agent-chat-view.test.ts b/src/web/src/components/agent-chat/agent-chat-view.test.ts
index 978f46aa2..1851bb566 100644
--- a/src/web/src/components/agent-chat/agent-chat-view.test.ts
+++ b/src/web/src/components/agent-chat/agent-chat-view.test.ts
@@ -1,6 +1,6 @@
import { describe, it, expect } from "vitest";
import type { Message, Artifact } from "@alook/shared";
-import { sortMessages, mergeMessages, buildTimeline, addBufferedIfNew, replaceOptimisticBuffered } from "./agent-chat-view";
+import { sortMessages, mergeMessages, buildTimeline, addBufferedIfNew, replaceOptimisticBuffered, getEventIconType } from "./agent-chat-view";
import type { NapMarker } from "./agent-chat-view";
function msg(id: string, created_at: string, role: "user" | "assistant" | "event" = "user", content = ""): Message {
@@ -196,6 +196,25 @@ describe("mergeMessages", () => {
});
});
+describe("getEventIconType", () => {
+ it("uses the issue icon for issue conversations", () => {
+ expect(getEventIconType("Error: failed to download attachments", "issue_event")).toBe("issue");
+ });
+
+ it("uses the issue icon for issue event content", () => {
+ expect(getEventIconType("Issue status changed: todo -> done", "user_dm_message")).toBe("issue");
+ });
+
+ it("keeps email and calendar event icons for existing channels", () => {
+ expect(getEventIconType("New email from [email protected]", "email_notification")).toBe("email");
+ expect(getEventIconType("Calendar event started", "calendar_event")).toBe("calendar");
+ });
+
+ it("lets explicit channel type win over event content", () => {
+ expect(getEventIconType("Issue mentioned in an email subject", "email_notification")).toBe("email");
+ });
+});
+
function artifact(id: string, created_at: string): Artifact {
return {
id,
diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsx
index f1c727db0..592e2b632 100644
--- a/src/web/src/components/agent-chat/agent-chat-view.tsx
+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx
@@ -33,7 +33,7 @@ import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { Skeleton } from "@/components/ui/skeleton";
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { ArrowUp, BedDouble, Box, Calendar, FileText, Loader2, Mail, Mic, Paperclip, Square, X } from "lucide-react";
+import { ArrowUp, BedDouble, Box, Calendar, CircleDot, FileText, Loader2, Mail, Mic, Paperclip, Square, X } from "lucide-react";
import { useSpeechRecognition } from "@/hooks/use-speech-recognition";
import { useMentionPopup } from "@/hooks/use-mention-popup";
import { MentionPopup } from "@/components/agent-chat/mention-popup";
@@ -81,6 +81,28 @@ const MENTION_COMPONENTS: Record<string, React.ComponentType<Record<string, unkn
},
};
+type EventIconType = "issue" | "email" | "calendar";
+
+export function getEventIconType(content: string, conversationType?: string | null): EventIconType {
+ if (conversationType === "issue_event") return "issue";
+ if (conversationType === "email_notification") return "email";
+ if (conversationType === "calendar_event") return "calendar";
+
+ const lower = content.toLowerCase();
+ if (lower.startsWith("issue ") || lower.startsWith("issue:")) return "issue";
+ if (lower.includes("email")) return "email";
+ return "calendar";
+}
+
+function EventMessageIcon({ content, conversationType }: { content: string; conversationType?: string | null }) {
+ const iconType = getEventIconType(content, conversationType);
+ const className = "h-4 w-4 mt-0.5 shrink-0";
+
+ if (iconType === "issue") return <CircleDot className={className} />;
+ if (iconType === "email") return <Mail className={className} />;
+ return <Calendar className={className} />;
+}
+
/** Sort messages by (created_at, id) ascending — guarantees chronological order. */
export function sortMessages(msgs: Message[]): Message[] {
return msgs.slice().sort((a, b) => {
@@ -426,7 +448,7 @@ export function AgentChatView() {
});
async function load() {
try {
- if (targetConvId && scrollToTaskId) {
+ if (targetConvId) {
try {
const [conv, msgs, arts, buffered] = await Promise.all([
getConversation(targetConvId, workspaceId),
@@ -446,17 +468,19 @@ export function AgentChatView() {
.then((counts) => { if (!ignore) setStepCounts(counts); })
.catch(() => {});
}
- const task = await getTask(scrollToTaskId, workspaceId).catch(() => null);
- if (ignore) return;
- if (task && !["completed", "failed", "cancelled", "superseded"].includes(task.status)) {
- setActiveTask(task);
- const tmsgs = await getTaskMessages(scrollToTaskId, workspaceId).catch(() => [] as TaskMessage[]);
+ if (scrollToTaskId) {
+ const task = await getTask(scrollToTaskId, workspaceId).catch(() => null);
if (ignore) return;
- setTaskMessages(tmsgs);
- if (tmsgs.length > 0) {
- lastSeqRef.current = Math.max(...tmsgs.map((m) => m.seq));
+ if (task && !["completed", "failed", "cancelled", "superseded"].includes(task.status)) {
+ setActiveTask(task);
+ const tmsgs = await getTaskMessages(scrollToTaskId, workspaceId).catch(() => [] as TaskMessage[]);
+ if (ignore) return;
+ setTaskMessages(tmsgs);
+ if (tmsgs.length > 0) {
+ lastSeqRef.current = Math.max(...tmsgs.map((m) => m.seq));
+ }
+ startPollingRef.current?.(task.id, targetConvId, lastSeqRef.current);
}
- startPollingRef.current?.(task.id, targetConvId, lastSeqRef.current);
}
} catch {
const data = await chatInit(agentId, workspaceId, activeChannel);
@@ -1400,7 +1424,7 @@ export function AgentChatView() {
})() : msg.role === "event" ? (
<div className="flex justify-start">
<div className="w-full rounded-md border bg-muted/50 text-muted-foreground text-sm px-3 py-2 flex items-start gap-2">
- {msg.content.toLowerCase().includes("email") ? <Mail className="h-4 w-4 mt-0.5 shrink-0" /> : <Calendar className="h-4 w-4 mt-0.5 shrink-0" />}
+ <EventMessageIcon content={msg.content} conversationType={conversation?.type} />
<span>{msg.content}</span>
</div>
</div>
diff --git a/src/web/src/components/app-sidebar.tsx b/src/web/src/components/app-sidebar.tsx
index aafc3aff2..dc93a3d2c 100644
--- a/src/web/src/components/app-sidebar.tsx
+++ b/src/web/src/components/app-sidebar.tsx
@@ -7,7 +7,7 @@ import { useWorkspace } from "@/contexts/workspace-context";
import type { Agent } from "@alook/shared";
import { Logo } from "@/components/logo";
import { cn } from "@/lib/utils";
-import { Monitor, SunMoon, Plus, CalendarDays, GitBranch, Settings, PinIcon, PinOffIcon, ArrowLeftRight, Home } from "lucide-react";
+import { Monitor, SunMoon, Plus, CalendarDays, GitBranch, Settings, PinIcon, PinOffIcon, ArrowLeftRight, Home, CircleDot } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
import { useTheme } from "next-themes";
@@ -175,6 +175,7 @@ export function AppSidebar({ onNavigate }: { onNavigate?: () => void } = {}) {
const isRuntimes = pathname === `${prefix}/runtimes`;
const isCalendar = pathname === `${prefix}/calendar`;
const isTraces = pathname.startsWith(`${prefix}/threads`);
+ const isIssues = pathname.startsWith(`${prefix}/issues`);
const isSettings = pathname === `${prefix}/settings`;
const isCreateAgent = pathname === `${prefix}/agents/new`;
@@ -277,6 +278,23 @@ export function AppSidebar({ onNavigate }: { onNavigate?: () => void } = {}) {
</TooltipTrigger>
<TooltipContent side="right">Threads</TooltipContent>
</Tooltip>
+
+ <Tooltip>
+ <TooltipTrigger render={
+ <button
+ type="button"
+ onClick={() => { router.push(`${prefix}/issues`); onNavigate?.(); }}
+ className={cn(
+ "flex items-center justify-center size-10 rounded-xl transition-colors duration-200 cursor-pointer",
+ "text-muted-foreground hover:text-foreground hover:bg-accent",
+ isIssues && "bg-accent text-foreground"
+ )}
+ />
+ }>
+ <CircleDot className="size-4" />
+ </TooltipTrigger>
+ <TooltipContent side="right">Issues</TooltipContent>
+ </Tooltip>
</div>
{/* Agent avatars */}
diff --git a/src/web/src/components/mobile-top-bar.tsx b/src/web/src/components/mobile-top-bar.tsx
index 4407e7236..7614e3d09 100644
--- a/src/web/src/components/mobile-top-bar.tsx
+++ b/src/web/src/components/mobile-top-bar.tsx
@@ -1,7 +1,7 @@
"use client";
import { useRouter, usePathname } from "next/navigation";
-import { GitBranch, Home } from "lucide-react";
+import { CircleDot, GitBranch, Home } from "lucide-react";
import { useSidebarTrigger } from "@/components/workspace-shell";
import { useAgentContext } from "@/contexts/agent-context";
import { useWorkspace } from "@/contexts/workspace-context";
@@ -19,6 +19,7 @@ export function MobileTopBar() {
const isHomeActive = pathname === `/w/${slug}/home`;
const isTracesActive = pathname.includes("/threads");
+ const isIssuesActive = pathname.includes("/issues");
const activeAgentMatch = pathname.match(/^\/w\/[^/]+\/agents\/([^/]+)/);
const activeAgentId = activeAgentMatch?.[1] ?? null;
@@ -74,7 +75,7 @@ export function MobileTopBar() {
<button
onClick={() => router.push(`/w/${slug}/threads`)}
- aria-label="Traces"
+ aria-label="Threads"
className={cn(
"shrink-0 p-1 rounded-md transition-colors",
isTracesActive
@@ -85,6 +86,19 @@ export function MobileTopBar() {
<GitBranch className="size-4" />
</button>
+ <button
+ onClick={() => router.push(`/w/${slug}/issues`)}
+ aria-label="Issues"
+ className={cn(
+ "shrink-0 p-1 rounded-md transition-colors",
+ isIssuesActive
+ ? "text-foreground bg-muted"
+ : "text-muted-foreground hover:text-foreground"
+ )}
+ >
+ <CircleDot className="size-4" />
+ </button>
+
<div className="flex-1 overflow-x-auto flex items-center gap-1.5 py-1 px-0.5 scrollbar-none">
{loading ? (
<Skeleton className="size-7 rounded-full" />
diff --git a/src/web/src/components/ui/select.tsx b/src/web/src/components/ui/select.tsx
index c8c974315..189d1d953 100644
--- a/src/web/src/components/ui/select.tsx
+++ b/src/web/src/components/ui/select.tsx
@@ -15,8 +15,9 @@ function Select({
function SelectTrigger({
className,
children,
+ hideIcon = false,
...props
-}: SelectPrimitive.Trigger.Props) {
+}: SelectPrimitive.Trigger.Props & { hideIcon?: boolean }) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
@@ -27,9 +28,11 @@ function SelectTrigger({
{...props}
>
{children}
- <SelectPrimitive.Icon className="shrink-0">
- <ChevronDownIcon className="size-3.5 opacity-50" />
- </SelectPrimitive.Icon>
+ {!hideIcon && (
+ <SelectPrimitive.Icon className="shrink-0">
+ <ChevronDownIcon className="size-3.5 opacity-50" />
+ </SelectPrimitive.Icon>
+ )}
</SelectPrimitive.Trigger>
)
}
diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.ts
index 65eba89f0..2b3a66594 100644
--- a/src/web/src/lib/api.ts
+++ b/src/web/src/lib/api.ts
@@ -7,6 +7,7 @@ import type {
CalendarEvent,
Channel,
Conversation,
+ CreateIssueRequest,
CreateAgentLinkRequest,
CreateAgentRequest,
CreateCalendarEventRequest,
@@ -17,11 +18,13 @@ import type {
DeleteCalendarEventRequest,
UpdateAgentRequest,
Email,
+ Issue,
LoginResponse,
MeetingSession,
Message,
TaskApi,
TaskMessage,
+ UpdateIssueRequest,
User,
Workspace,
} from "@alook/shared";
@@ -632,6 +635,102 @@ export const deleteCalendarEvent = (
: {}),
});
+// Issues
+export interface IssueDetailResponse {
+ issue: Issue;
+ messages: Message[];
+ artifacts: Artifact[];
+}
+
+export const listIssues = (
+ workspaceId: string,
+ opts?: { agentId?: string; status?: string; terminal?: boolean }
+) => {
+ const extra: Record<string, string> = {};
+ if (opts?.agentId) extra.agentId = opts.agentId;
+ if (opts?.status) extra.status = opts.status;
+ if (opts?.terminal !== undefined) extra.terminal = String(opts.terminal);
+ return apiFetch<Issue[]>(`/api/issues${wsQuery(workspaceId, extra)}`);
+};
+
+export const createIssue = async (
+ workspaceId: string,
+ req: CreateIssueRequest & { files?: File[] },
+): Promise<{ issue: Issue; message: Message; task: TaskApi }> => {
+ if (!req.files || req.files.length === 0) {
+ return apiFetch<{ issue: Issue; message: Message; task: TaskApi }>(`/api/issues${wsQuery(workspaceId)}`, {
+ method: "POST",
+ body: JSON.stringify({
+ agent_id: req.agent_id,
+ title: req.title,
+ description: req.description,
+ }),
+ });
+ }
+
+ const fd = new FormData();
+ fd.append("agent_id", req.agent_id);
+ fd.append("title", req.title);
+ fd.append("description", req.description ?? "");
+ for (const file of req.files) {
+ fd.append("file", file);
+ }
+
+ let res: Response;
+ try {
+ res = await fetch(`/api/issues${wsQuery(workspaceId)}`, {
+ method: "POST",
+ credentials: "include",
+ body: fd,
+ });
+ } catch (err) {
+ if (err instanceof TypeError) {
+ throw new ApiError("Unable to connect — check your network", 0);
+ }
+ throw err;
+ }
+
+ if (res.status === 401) {
+ if (typeof window !== "undefined") window.location.href = "/sign-in";
+ throw new ApiError("Unauthorized", 401);
+ }
+
+ if (!res.ok) {
+ let serverError: string | undefined;
+ let details: string[] | undefined;
+ try {
+ const body = (await res.json()) as { error?: string; details?: string[] };
+ serverError = body.error;
+ details = body.details;
+ } catch {
+ // non-JSON body
+ }
+ if (res.status === 429) throw new ApiError("Please wait a moment before trying again", 429);
+ if (res.status >= 500) throw new ApiError(serverError || "Something went wrong — please try again", res.status, details);
+ throw new ApiError(serverError || "Something went wrong", res.status, details);
+ }
+
+ return res.json() as Promise<{ issue: Issue; message: Message; task: TaskApi }>;
+};
+
+export const getIssue = (workspaceId: string, issueId: string) =>
+ apiFetch<IssueDetailResponse>(`/api/issues/${issueId}${wsQuery(workspaceId)}`);
+
+export const updateIssue = (workspaceId: string, issueId: string, patch: UpdateIssueRequest) =>
+ apiFetch<Issue>(`/api/issues/${issueId}${wsQuery(workspaceId)}`, {
+ method: "PATCH",
+ body: JSON.stringify(patch),
+ });
+
+export const commentIssue = (workspaceId: string, issueId: string, content: string) =>
+ apiFetch<{ message: Message }>(`/api/issues/${issueId}${wsQuery(workspaceId)}`, {
+ method: "POST",
+ body: JSON.stringify({ content }),
+ });
+
+export const deleteIssue = (workspaceId: string, issueId: string) =>
+ apiFetch<void>(`/api/issues/${issueId}${wsQuery(workspaceId)}`, { method: "DELETE" });
+
// Whitelist
export interface WhitelistEntry {
id: string;
diff --git a/src/web/src/lib/api/responses.ts b/src/web/src/lib/api/responses.ts
index 1f10bf5c1..f91587f55 100644
--- a/src/web/src/lib/api/responses.ts
+++ b/src/web/src/lib/api/responses.ts
@@ -257,6 +257,23 @@ export function calendarEventToResponse(e: any) {
};
}
+export function issueToResponse(row: any) {
+ return {
+ id: row.id,
+ workspace_id: row.workspaceId,
+ agent_id: row.agentId,
+ creator_user_id: row.creatorUserId,
+ conversation_id: row.conversationId,
+ latest_task_id: row.latestTaskId ?? null,
+ title: row.title,
+ description: row.description ?? "",
+ status: row.status,
+ created_at: formatTimestamp(row.createdAt),
+ updated_at: formatTimestamp(row.updatedAt),
+ completed_at: formatTimestampNullable(row.completedAt),
+ };
+}
+
export function taskToActivityResponse(t: {
id: string;
conversationId: string;
diff --git a/src/web/src/lib/middleware/workspace.test.ts b/src/web/src/lib/middleware/workspace.test.ts
index d6ffb8339..bc465c2be 100644
--- a/src/web/src/lib/middleware/workspace.test.ts
+++ b/src/web/src/lib/middleware/workspace.test.ts
@@ -59,6 +59,12 @@ describe("withWorkspaceMember", () => {
expect(result).toBeInstanceOf(NextResponse);
expect((result as NextResponse).status).toBe(404);
});
+
+ it("allows machine token workspace access when auth workspace matches", async () => {
+ mockGetMemberByUserAndWorkspace.mockResolvedValue(null);
+ const result = await withWorkspaceMember(makeReq("w1"), { ...auth, workspaceId: "w1" });
+ expect(result).toEqual({ workspaceId: "w1", memberRole: "member" });
+ });
});
describe("withWorkspaceOwner", () => {
diff --git a/src/web/src/lib/middleware/workspace.ts b/src/web/src/lib/middleware/workspace.ts
index df792b8c2..4fd4e887c 100644
--- a/src/web/src/lib/middleware/workspace.ts
+++ b/src/web/src/lib/middleware/workspace.ts
@@ -40,6 +40,9 @@ export async function withWorkspaceMember(
auth.userId,
workspaceId
)
+ if (!membership && auth.workspaceId === workspaceId) {
+ return { workspaceId, memberRole: "member" }
+ }
if (!membership) {
return NextResponse.json(
{ error: "workspace not found" },
diff --git a/src/web/src/lib/services/task.test.ts b/src/web/src/lib/services/task.test.ts
index b97078d74..3e16a6a3a 100644
--- a/src/web/src/lib/services/task.test.ts
+++ b/src/web/src/lib/services/task.test.ts
@@ -7,6 +7,7 @@ vi.mock("@alook/shared", () => ({
USER_DM_MESSAGE: "user_dm_message",
EMAIL_NOTIFICATION: "email_notification",
CALENDAR_EVENT: "calendar_event",
+ ISSUE_EVENT: "issue_event",
KILL_TASK: "kill_task",
},
MAX_TASKS_PER_TRACE: 256,
@@ -41,6 +42,10 @@ vi.mock("@alook/shared", () => ({
conversation: {
getConversation: vi.fn(),
},
+ issue: {
+ getIssue: vi.fn(),
+ updateIssue: vi.fn(),
+ },
},
}));
@@ -73,6 +78,10 @@ const messageQ = queries.message as {
const conversationQ = (queries as any).conversation as {
getConversation: ReturnType<typeof vi.fn>;
};
+const issueQ = (queries as any).issue as {
+ getIssue: ReturnType<typeof vi.fn>;
+ updateIssue: ReturnType<typeof vi.fn>;
+};
const service = new TaskService({} as any);
@@ -286,6 +295,30 @@ describe("TaskService", () => {
expect(result).toEqual(task);
expect(taskQ.startTask).toHaveBeenCalledWith({}, "t1", "w1");
});
+
+ it("moves issue tasks to in_progress when they start", async () => {
+ const task = {
+ id: "t1",
+ type: "issue_event",
+ contextKey: "iss_1",
+ workspaceId: "w1",
+ conversationId: "c1",
+ status: "running",
+ };
+ taskQ.startTask.mockResolvedValue(task);
+ issueQ.getIssue.mockResolvedValue({ id: "iss_1", status: "todo", conversationId: "c1" });
+ issueQ.updateIssue.mockResolvedValue({ id: "iss_1", status: "in_progress", conversationId: "c1" });
+
+ await service.startTask("t1", "w1");
+
+ expect(issueQ.updateIssue).toHaveBeenCalledWith({}, "iss_1", "w1", { status: "in_progress" });
+ expect(messageQ.createMessage).toHaveBeenCalledWith({}, {
+ conversationId: "c1",
+ role: "event",
+ content: "Issue status changed: todo -> in_progress",
+ taskId: "t1",
+ });
+ });
});
// ── completeTask ─────────────────────────────────────────────────
@@ -356,6 +389,33 @@ describe("TaskService", () => {
"working"
);
});
+
+ it("moves issue tasks to done when they complete", async () => {
+ const task = {
+ id: "t1",
+ agentId: "a1",
+ workspaceId: "w1",
+ conversationId: "c1",
+ type: "issue_event",
+ contextKey: "iss_1",
+ status: "completed",
+ };
+ taskQ.completeTask.mockResolvedValue(task);
+ taskQ.countRunningTasks.mockResolvedValue(0);
+ agentQ.updateAgentStatus.mockResolvedValue(undefined);
+ issueQ.getIssue.mockResolvedValue({ id: "iss_1", status: "in_progress", conversationId: "c1" });
+ issueQ.updateIssue.mockResolvedValue({ id: "iss_1", status: "done", conversationId: "c1" });
+
+ await service.completeTask("t1", "w1", JSON.stringify({}), "sess-1");
+
+ expect(issueQ.updateIssue).toHaveBeenCalledWith({}, "iss_1", "w1", { status: "done" });
+ expect(messageQ.createMessage).toHaveBeenCalledWith({}, {
+ conversationId: "c1",
+ role: "event",
+ content: "Issue status changed: in_progress -> done",
+ taskId: "t1",
+ });
+ });
});
// ── failTask ─────────────────────────────────────────────────────
@@ -421,6 +481,33 @@ describe("TaskService", () => {
"working"
);
});
+
+ it("moves issue tasks to failed when they fail", async () => {
+ const task = {
+ id: "t1",
+ agentId: "a1",
+ workspaceId: "w1",
+ conversationId: "c1",
+ type: "issue_event",
+ contextKey: "iss_1",
+ status: "failed",
+ };
+ taskQ.failTask.mockResolvedValue(task);
+ taskQ.countRunningTasks.mockResolvedValue(0);
+ agentQ.updateAgentStatus.mockResolvedValue(undefined);
+ issueQ.getIssue.mockResolvedValue({ id: "iss_1", status: "in_progress", conversationId: "c1" });
+ issueQ.updateIssue.mockResolvedValue({ id: "iss_1", status: "failed", conversationId: "c1" });
+
+ await service.failTask("t1", "w1", "something went wrong");
+
+ expect(issueQ.updateIssue).toHaveBeenCalledWith({}, "iss_1", "w1", { status: "failed" });
+ expect(messageQ.createMessage).toHaveBeenCalledWith({}, {
+ conversationId: "c1",
+ role: "event",
+ content: "Issue status changed: in_progress -> failed",
+ taskId: "t1",
+ });
+ });
});
// ── reconcileAgentStatus ─────────────────────────────────────────
diff --git a/src/web/src/lib/services/task.ts b/src/web/src/lib/services/task.ts
index f41895054..03b1237f7 100644
--- a/src/web/src/lib/services/task.ts
+++ b/src/web/src/lib/services/task.ts
@@ -8,6 +8,7 @@ const taskQueries = queries.task;
const agentQueries = queries.agent;
const messageQueries = queries.message;
const conversationQueries = queries.conversation;
+const issueQueries = queries.issue;
export class TaskService {
constructor(private db: Database) {}
@@ -108,6 +109,7 @@ export class TaskService {
if (!task) {
throw new Error("task not in dispatched status");
}
+ await this.syncIssueStatusFromTask(task, "in_progress");
return task;
}
@@ -150,6 +152,7 @@ export class TaskService {
}
await this.reconcileAgentStatus(task.agentId, task.workspaceId);
+ await this.syncIssueStatusFromTask(task, "done");
await this.dispatchNextBufferedMessage(task.conversationId, task.workspaceId);
return task;
}
@@ -178,10 +181,31 @@ export class TaskService {
}
await this.reconcileAgentStatus(task.agentId, task.workspaceId);
+ await this.syncIssueStatusFromTask(task, "failed");
await this.dispatchNextBufferedMessage(task.conversationId, task.workspaceId);
return task;
}
+ private async syncIssueStatusFromTask(
+ task: { id: string; type?: string | null; contextKey?: string | null; workspaceId: string; conversationId: string },
+ status: "in_progress" | "done" | "failed",
+ ) {
+ if (task.type !== TASK_TYPES.ISSUE_EVENT || !task.contextKey) return;
+
+ const issue = await issueQueries.getIssue(this.db, task.contextKey, task.workspaceId);
+ if (!issue || issue.conversationId !== task.conversationId || issue.status === status) return;
+
+ const updated = await issueQueries.updateIssue(this.db, issue.id, task.workspaceId, { status });
+ if (!updated) return;
+
+ await messageQueries.createMessage(this.db, {
+ conversationId: issue.conversationId,
+ role: "event",
+ content: `Issue status changed: ${issue.status} -> ${status}`,
+ taskId: task.id,
+ });
+ }
+
async supersedeTask(taskId: string, workspaceId: string) {
const task = await taskQueries.supersedeTask(this.db, taskId, workspaceId);