Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8043: feat(issues): include sub-issue runs in execution logs and timelines (#9283)
Woodd6a9f0ec161b
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex dfad578fc4..870f0d2422 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -959,6 +959,21 @@ describe("ApiClient Inbox response schemas", () => {});describe("ApiClient", () => {+ it("requests recursive issue history and tolerates malformed issue labels", async () => {+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify([+ { id: "child-run", issue_id: "child", issue_identifier: "MUL-2", issue_title: "Child", usage: [{ model: "test", input_tokens: 10 }] },+ { id: "deep-run", issue_id: "grandchild", issue_identifier: 42, issue_title: { malformed: true } },+ ]), { status: 200, headers: { "Content-Type": "application/json" } }));+ vi.stubGlobal("fetch", fetchMock);+ const client = new ApiClient("https://api.example.test");+ const tasks = await client.listTasksByIssue("parent", true);+ expect(fetchMock.mock.calls[0]?.[0]).toBe("https://api.example.test/api/issues/parent/task-runs?scope=subtree");+ expect(tasks).toHaveLength(2);+ expect(tasks[0]).toMatchObject({ issue_id: "child", issue_identifier: "MUL-2", issue_title: "Child" });+ expect(tasks[0]?.usage?.[0]?.input_tokens).toBe(10);+ expect(tasks[1]?.issue_identifier).toBeUndefined();+ expect(tasks[1]?.issue_title).toBeUndefined();+ });it("preserves HTTP status on failed requests", async () => {vi.stubGlobal("fetch",diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 5f8aa54753..35febb5a9f 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -2912,8 +2912,10 @@ export class ApiClient {});}- async listTasksByIssue(issueId: string): Promise<AgentTask[]> {- const raw = await this.fetch<unknown>(`/api/issues/${issueId}/task-runs`);+ async listTasksByIssue(issueId: string, includeDescendants = false): Promise<AgentTask[]> {+ const raw = await this.fetch<unknown>(+ `/api/issues/${issueId}/task-runs${includeDescendants ? "?scope=subtree" : ""}`,+ );return parseWithFallback<AgentTask[]>(raw, AgentTaskListSchema, [], {endpoint: "GET /api/issues/:id/task-runs",});diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 6a363a6798..6791fd2393 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -2095,6 +2095,8 @@ export const AgentTaskSchema = z.object({agent_id: z.string().default(""),runtime_id: z.string().default(""),issue_id: z.string().default(""),+ issue_identifier: z.string().optional().catch(undefined),+ issue_title: z.string().optional().catch(undefined),status: z.string().default("cancelled"),priority: z.number().default(0),dispatched_at: z.string().nullable().default(null),diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.tsindex 8cc1e0357f..3aa367a566 100644--- a/packages/core/issues/queries.ts+++ b/packages/core/issues/queries.ts@@ -23,10 +23,10 @@ import type { SidebarIssuesRequest } from "./sidebar-list";import { ALL_STATUSES } from "./config";import { issueColumnCategory } from "./status-category";-export function issueTasksOptions(issueId: string) {+export function issueTasksOptions(issueId: string, includeDescendants = false) {return queryOptions({- queryKey: issueKeys.tasks(issueId),- queryFn: () => api.listTasksByIssue(issueId),+ queryKey: includeDescendants ? issueKeys.subtreeTasks(issueId) : issueKeys.tasks(issueId),+ queryFn: () => api.listTasksByIssue(issueId, includeDescendants),enabled: !!issueId,staleTime: 30_000,refetchOnWindowFocus: true,@@ -203,6 +203,7 @@ export const issueKeys = {tasksAll: () => ["issues", "tasks"] as const,/** Per-issue task list (issue-detail Execution log section). */tasks: (issueId: string) => [...issueKeys.tasksAll(), issueId] as const,+ subtreeTasks: (issueId: string) => [...issueKeys.tasks(issueId), "subtree"] as const,sourceContextPreview: (wsId: string, anchorCommentId: string) =>["source-context", "preview", wsId, anchorCommentId] as const,};diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsxindex fc6ed89a2b..d4fc13aa07 100644--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx@@ -23,7 +23,7 @@ import {} from "../workspace/pending-delete";import { setApiInstance } from "../api";import type { ApiClient } from "../api/client";-import type { IssueTableQuerySpec } from "../types";+import type { AgentTask, IssueTableQuerySpec } from "../types";import { getCurrentWsId } from "../platform/workspace-storage";import { forgetLocalSearchIndex } from "../search-index/instance";import { useRealtimeSync, type RealtimeSyncStores } from "./use-realtime-sync";@@ -329,6 +329,72 @@ describe("useRealtimeSync — ws instance change", () => {expect(calls).toContainEqual(["task-messages"]);});+ function subtreeEvents() {+ const ws = createMockWs();+ renderHook(() => useRealtimeSync(ws, stores), { wrapper: createWrapper(qc) });+ const rows = [+ { id: "run", issue_id: "child", issue_title: "Old title" },+ { id: "other-run", issue_id: "other", issue_title: "Other title" },+ ] as AgentTask[];+ qc.setQueryData(issueKeys.tasks("parent"), rows);+ qc.setQueryData(issueKeys.subtreeTasks("parent"), rows);+ qc.setQueryData(issueKeys.subtreeTasks("another-parent"), rows);+ return (event: string, payload: unknown) => {+ const handler = vi.mocked(ws.on).mock.calls.find(([name]) => name === event)?.[1];+ expect(handler).toBeDefined();+ handler!(payload as never);+ };+ }++ it.each([+ { status_changed: true, issue: { id: "child", status: "in_progress" } },+ { assignee_changed: true, issue: { id: "child" } },+ { priority_changed: true, issue: { id: "child" } },+ { parent_changed: false, issue: { id: "child", parent_issue_id: "parent" } },+ ])("does not refetch subtree history for an unrelated issue update: %j", (payload) => {+ const emit = subtreeEvents();+ emit("issue:updated", payload);+ expect(qc.getQueryState(issueKeys.subtreeTasks("parent"))?.isInvalidated).toBe(false);+ expect(qc.getQueryState(issueKeys.tasks("parent"))?.isInvalidated).toBe(false);+ });++ it("patches matching owning-issue titles across subtree caches without refetching", () => {+ const emit = subtreeEvents();+ const fetchRuns = vi.fn(async () => []);+ const observer = new QueryObserver(qc, {+ queryKey: issueKeys.subtreeTasks("parent"), queryFn: fetchRuns, staleTime: Infinity,+ });+ const unsubscribe = observer.subscribe(() => {});+ try {+ emit("issue:updated", { issue: { id: "child", title: "New title" }, title_changed: true });+ for (const root of ["parent", "another-parent"]) {+ expect(qc.getQueryData(issueKeys.subtreeTasks(root))).toMatchObject([+ { issue_id: "child", issue_title: "New title" },+ { issue_id: "other", issue_title: "Other title" },+ ]);+ expect(qc.getQueryState(issueKeys.subtreeTasks(root))?.isInvalidated).toBe(false);+ }+ expect(qc.getQueryData<AgentTask[]>(issueKeys.tasks("parent"))?.[0]?.issue_title).toBe("Old title");+ expect(fetchRuns).not.toHaveBeenCalled();+ } finally {+ unsubscribe();+ }+ });++ it.each(["issue:updated", "issue:deleted"])("invalidates subtree history for a hierarchy change: %s", (event) => {+ const emit = subtreeEvents();+ emit(event, { issue: { id: "child", parent_issue_id: "new-parent" }, parent_changed: true, prev_parent_issue_id: "parent", issue_id: "child" });+ expect(qc.getQueryState(issueKeys.subtreeTasks("parent"))?.isInvalidated).toBe(true);+ expect(qc.getQueryState(issueKeys.subtreeTasks("another-parent"))?.isInvalidated).toBe(true);+ expect(qc.getQueryState(issueKeys.tasks("parent"))?.isInvalidated).toBe(false);+ });++ it("does not invalidate subtree history when an issue is created", () => {+ const emit = subtreeEvents();+ emit("issue:created", { issue: { id: "child", parent_issue_id: "parent" } });+ expect(qc.getQueryState(issueKeys.subtreeTasks("parent"))?.isInvalidated).toBe(false);+ });+it("invalidates per-chat-session caches after an established ws reconnects", () => {const ws = createMockWs();renderHook(() => useRealtimeSync(ws, stores), {diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 00bb2d9d2d..393d75d733 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -64,6 +64,7 @@ import {type SystemNotificationPayload,} from "../platform/system-notification";import type { Workspace } from "../types/workspace";+import type { AgentTask } from "../types/agent";import {chatKeys,isTaskMessageTimelineHeld,@@ -1135,6 +1136,17 @@ export function useRealtimeSync(const payload = p as IssueUpdatedPayload;const { issue } = payload;if (!issue?.id) return;+ const subtreeFilter = {+ queryKey: issueKeys.tasksAll(),+ predicate: (q: { queryKey: readonly unknown[] }) => q.queryKey[3] === "subtree",+ };+ if (payload.parent_changed) {+ qc.invalidateQueries(subtreeFilter);+ } else if (payload.title_changed) {+ qc.setQueriesData<AgentTask[]>(subtreeFilter, (tasks) => tasks?.map((task) =>+ task.issue_id === issue.id ? { ...task, issue_title: issue.title } : task,+ ));+ }const wsId = getCurrentWsId();if (wsId) {onIssueUpdated(qc, wsId, issue, {@@ -1165,6 +1177,7 @@ export function useRealtimeSync(const unsubIssueDeleted = ws.on("issue:deleted", (p) => {const { issue_id } = p as IssueDeletedPayload;if (!issue_id) return;+ qc.invalidateQueries({ queryKey: issueKeys.tasksAll(), predicate: (q) => q.queryKey[3] === "subtree" });const wsId = getCurrentWsId();if (wsId) {onIssueDeleted(qc, wsId, issue_id);diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 0565b051ad..3eb8cd9828 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -309,6 +309,9 @@ export interface TaskCancellationActor {}export interface AgentTask {+ /** Owning issue labels supplied by subtree execution-history reads. */+ issue_identifier?: string;+ issue_title?: string;wakeup_id?: string;id: string;agent_id: string;diff --git a/packages/core/types/events.ts b/packages/core/types/events.tsindex b05e45cb41..e7478dc291 100644--- a/packages/core/types/events.ts+++ b/packages/core/types/events.ts@@ -123,6 +123,9 @@ export interface IssueUpdatedPayload {assignee_changed?: boolean;status_changed?: boolean;project_changed?: boolean;+ title_changed?: boolean;+ parent_changed?: boolean;+ prev_parent_issue_id?: string | null;// Both ends of a duplicate-mark change (MUL-7349). The mark is not on Issue,// so these tell the realtime layer whose duplicate relations to refresh.duplicate_of_issue_id?: string | null;diff --git a/packages/views/issues/components/execution-log-section.test.tsx b/packages/views/issues/components/execution-log-section.test.tsxindex 40cd3780a8..7e8f436308 100644--- a/packages/views/issues/components/execution-log-section.test.tsx+++ b/packages/views/issues/components/execution-log-section.test.tsx@@ -1,6 +1,6 @@// @vitest-environment jsdom-import { cleanup, fireEvent, screen } from "@testing-library/react";+import { cleanup, fireEvent, screen, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { AgentTask } from "@multica/core/types";import { renderWithI18n } from "../../test/i18n";@@ -24,7 +24,8 @@ vi.mock("../../common/task-transcript", () => ({}));vi.mock("./terminate-task-confirm-dialog", () => ({- TerminateTaskConfirmDialog: () => null,+ TerminateTaskConfirmDialog: ({ open, onConfirm }: { open: boolean; onConfirm: () => void }) =>+ open ? <button type="button" onClick={onConfirm}>Confirm stop</button> : null,}));vi.mock("@multica/core/workspace/hooks", () => ({@@ -46,6 +47,7 @@ import { act, within } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { issueKeys } from "@multica/core/issues/queries";import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";+import { ApiClient, setApiInstance } from "@multica/core/api";function makeTask(overrides: Partial<AgentTask> = {}): AgentTask {return {@@ -75,6 +77,213 @@ beforeEach(() => {afterEach(() => {vi.useRealTimers();+ vi.restoreAllMocks();+});++describe("subtree execution log", () => {+ function renderParent(own: AgentTask[], subtree: AgentTask[]) {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ queryClient.setQueryData(issueKeys.tasks("issue-1"), own);+ queryClient.setQueryData(issueKeys.subtreeTasks("issue-1"), subtree);+ return renderWithI18n(+ <QueryClientProvider client={queryClient}>+ <ExecutionLogSection issueId="issue-1" identifier="MUL-1" hasChildren />+ </QueryClientProvider>,+ );+ }++ it("switches counts, cost, active status, rows, and the full timeline together", () => {+ const own = makeTask({ id: "own", status: "completed", completed_at: "2026-06-08T08:02:00Z", trigger_summary: "Parent run", usage: [usageSlice({ cost_usd_ticks: 1e10 })] });+ const child = makeTask({ id: "child", issue_id: "child-issue", issue_identifier: "MUL-2", issue_title: "Child", status: "completed", completed_at: "2026-06-08T08:03:00Z", trigger_summary: "Child run", usage: [usageSlice({ cost_usd_ticks: 2e10 })] });+ const grandchild = makeTask({ id: "grandchild", issue_id: "deep-issue", issue_identifier: "MUL-3", issue_title: "Grandchild", trigger_summary: "Grandchild run" });+ renderParent([own], [own, child, grandchild]);+ const toggle = screen.getByRole("checkbox", { name: "Include sub-issues" });+ expect(toggle).not.toBeChecked();+ expect(screen.getByRole("button", { name: "Execution log 1" })).toBeInTheDocument();+ expect(screen.getAllByText("$1.00").length).toBeGreaterThan(0);+ expect(screen.queryByText("Child run")).not.toBeInTheDocument();+ fireEvent.click(toggle);+ expect(toggle).toBeChecked();+ expect(screen.getByRole("button", { name: "Execution log 3" })).toBeInTheDocument();+ expect(screen.getAllByText("$3.00").length).toBeGreaterThan(0);+ expect(screen.getByText("Child run")).toBeInTheDocument();+ expect(screen.getByText("Grandchild run")).toBeInTheDocument();+ expect(screen.getByText("MUL-2")).toHaveAttribute("title", "Child");+ expect(screen.getByText("MUL-3")).toBeInTheDocument();+ const header = screen.getByText("Execution log").closest("div")!;+ expect(within(header).getByText("1 active")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Open timeline" }));+ const dialog = screen.getByRole("dialog");+ const dialogToggle = within(dialog).getByRole("checkbox", { name: "Include sub-issues" });+ expect(dialogToggle).toBeChecked();+ expect(within(dialog).getByRole("img", { name: "Run activity: $3.00 across 3 runs" })).toBeInTheDocument();+ expect(within(dialog).getByText("MUL-3")).toBeInTheDocument();+ fireEvent.click(within(dialog).getByRole("button", { name: "Cumulative" }));+ expect(within(dialog).getByRole("img", { name: "Cumulative cost over time: $3.00 across 3 runs" })).toBeInTheDocument();+ fireEvent.click(within(dialog).getByRole("button", { name: "Per run" }));+ fireEvent.click(dialogToggle);+ expect(dialogToggle).not.toBeChecked();+ expect(toggle).toBeChecked();+ expect(within(dialog).getByText("Spent").parentElement).toHaveTextContent("$1.00");+ expect(within(dialog).getByRole("img", { name: "Run activity: $1.00 across 1 run" })).toBeInTheDocument();+ expect(within(dialog).getByText("Parent run")).toBeInTheDocument();+ expect(within(dialog).queryByText("Grandchild run")).not.toBeInTheDocument();+ expect(within(dialog).queryByText("MUL-2")).not.toBeInTheDocument();+ expect(within(dialog).queryByText(/1 running/)).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Close" }));+ fireEvent.click(screen.getByRole("button", { name: "Open timeline" }));+ expect(within(screen.getByRole("dialog")).getByRole("checkbox", { name: "Include sub-issues" })).toBeChecked();+ expect(within(screen.getByRole("dialog")).getByText("Grandchild run")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Close" }));+ fireEvent.click(toggle);+ expect(screen.getByRole("button", { name: "Execution log 1" })).toBeInTheDocument();+ expect(screen.queryByText("Grandchild run")).not.toBeInTheDocument();+ });++ it("keeps descendant scope while using the shared disclosure and scrolling active list", () => {+ const own = makeTask({ id: "own", status: "completed", completed_at: "2026-06-08T08:02:00Z" });+ const descendants = Array.from({ length: 8 }, (_, index) => makeTask({+ id: `child-${index}`, issue_id: `child-issue-${index}`, issue_identifier: `MUL-${index + 2}`,+ status: "queued", trigger_summary: `Descendant ${index}`,+ }));+ renderParent([own], [own, ...descendants]);+ fireEvent.click(screen.getByRole("checkbox", { name: "Include sub-issues" }));+ const active = screen.getByRole("region", { name: "8 active" });+ expect(within(active).queryByText(/^Descendant /)).not.toBeInTheDocument();+ fireEvent.click(within(active).getByRole("button", { name: /8 queued/ }));+ expect(within(active).getAllByText(/^Descendant /)).toHaveLength(8);+ expect(within(active).getByText("MUL-9")).toBeInTheDocument();+ expect(active).toHaveClass("max-h-48", "overflow-y-auto");+ const disclosure = screen.getByRole("button", { name: "Execution log 9" });+ fireEvent.click(disclosure);+ expect(disclosure).toHaveAttribute("aria-expanded", "false");+ expect(screen.queryByRole("checkbox", { name: "Include sub-issues" })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Open timeline" }));+ const dialog = screen.getByRole("dialog");+ expect(within(dialog).getByRole("checkbox", { name: "Include sub-issues" })).toBeChecked();+ expect(within(dialog).getByText("MUL-9")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Close" }));+ fireEvent.click(disclosure);+ expect(screen.getByRole("checkbox", { name: "Include sub-issues" })).toBeChecked();+ });++ it("can expand only the dialog when the sidebar excludes descendants", async () => {+ vi.useRealTimers();+ const own = makeTask({ status: "completed", completed_at: "2026-06-08T08:02:00Z", trigger_summary: "Parent run" });+ const child = makeTask({ id: "child", issue_id: "child-issue", issue_identifier: "MUL-2", trigger_summary: "Child run" });+ const client = new ApiClient("https://api.example.test");+ setApiInstance(client);+ let rejectRequest!: (error: Error) => void;+ const list = vi.spyOn(client, "listTasksByIssue").mockImplementation(() =>+ new Promise((_, reject) => { rejectRequest = reject; }),+ );+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ queryClient.setQueryData(issueKeys.tasks("issue-1"), [own]);+ renderWithI18n(+ <QueryClientProvider client={queryClient}>+ <ExecutionLogSection issueId="issue-1" hasChildren />+ </QueryClientProvider>,+ );+ const outerToggle = screen.getByRole("checkbox", { name: "Include sub-issues" });+ fireEvent.click(screen.getByRole("button", { name: "Open timeline" }));+ const dialog = screen.getByRole("dialog");+ const toggle = within(dialog).getByRole("checkbox", { name: "Include sub-issues" });+ expect(toggle).not.toBeChecked();+ fireEvent.click(toggle);+ expect(list).toHaveBeenCalledWith("issue-1", true);+ expect(within(dialog).getByRole("status", { name: "Loading runs..." })).toBeInTheDocument();+ expect(within(dialog).queryByRole("img")).not.toBeInTheDocument();+ await act(async () => { rejectRequest(new Error("unavailable")); });+ const retry = await within(dialog).findByRole("button", { name: "Could not load runs. Retry" });+ list.mockResolvedValue([own, child]);+ fireEvent.click(retry);+ expect(await within(dialog).findByText("Child run")).toBeInTheDocument();+ expect(outerToggle).not.toBeChecked();+ fireEvent.click(screen.getByRole("button", { name: "Close" }));+ expect(screen.queryByText("Child run")).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Open timeline" }));+ expect(within(screen.getByRole("dialog")).getByRole("checkbox", { name: "Include sub-issues" })).not.toBeChecked();+ queryClient.clear();+ });++ it("shows an empty dialog scope when only descendants have runs", () => {+ renderParent([], [makeTask({ id: "child", issue_id: "child-issue" })]);+ const outerToggle = screen.getByRole("checkbox", { name: "Include sub-issues" });+ fireEvent.click(outerToggle);+ fireEvent.click(screen.getByRole("button", { name: "Open timeline" }));+ const dialog = screen.getByRole("dialog");+ fireEvent.click(within(dialog).getByRole("checkbox", { name: "Include sub-issues" }));+ expect(within(dialog).getByText("No runs in this scope.")).toBeInTheDocument();+ expect(within(dialog).queryByRole("img")).not.toBeInTheDocument();+ expect(outerToggle).toBeChecked();+ });++ it("offers subtree history even when the parent has no runs, and retries the owning child", async () => {+ const child = makeTask({ id: "child", issue_id: "child-issue", issue_identifier: "MUL-2", status: "failed", completed_at: "2026-06-08T08:03:00Z" });+ renderParent([], [child]);+ expect(screen.getByText("No runs in this scope.")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("checkbox", { name: "Include sub-issues" }));+ const client = new ApiClient("https://api.example.test");+ setApiInstance(client);+ const retry = vi.spyOn(client, "rerunIssue").mockResolvedValue({} as never);+ await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Retry run" })); });+ expect(retry).toHaveBeenCalledWith("child-issue", "child");+ });++ it("stops a descendant run through its owning issue", async () => {+ renderParent([], [makeTask({ id: "deep-run", issue_id: "grandchild-issue" })]);+ fireEvent.click(screen.getByRole("checkbox", { name: "Include sub-issues" }));+ const client = new ApiClient("https://api.example.test");+ setApiInstance(client);+ const stop = vi.spyOn(client, "cancelTask").mockResolvedValue({} as never);+ fireEvent.click(screen.getByRole("button", { name: "Cancel run" }));+ await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Confirm stop" })); });+ expect(stop).toHaveBeenCalledWith("grandchild-issue", "deep-run");+ });++ it("stops an expanded queued descendant through its owning issue", async () => {+ renderParent([], [+ makeTask({ id: "child-queued", issue_id: "child-issue", issue_identifier: "MUL-2", status: "queued" }),+ makeTask({ id: "deep-queued", issue_id: "grandchild-issue", issue_identifier: "MUL-3", status: "queued" }),+ ]);+ fireEvent.click(screen.getByRole("checkbox", { name: "Include sub-issues" }));+ fireEvent.click(screen.getByRole("button", { name: /2 queued/ }));+ const row = screen.getByText("MUL-3").parentElement!;+ const client = new ApiClient("https://api.example.test");+ setApiInstance(client);+ const stop = vi.spyOn(client, "cancelTask").mockResolvedValue({} as never);+ fireEvent.click(within(row).getByRole("button", { name: "Cancel run" }));+ await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Confirm stop" })); });+ expect(stop).toHaveBeenCalledWith("grandchild-issue", "deep-queued");+ });++ it("shows loading and a retryable error instead of keeping the parent's partial totals", async () => {+ vi.useRealTimers();+ const client = new ApiClient("https://api.example.test");+ setApiInstance(client);+ let rejectRequest!: (error: Error) => void;+ const list = vi.spyOn(client, "listTasksByIssue").mockImplementation(() =>+ new Promise((_, reject) => { rejectRequest = reject; }),+ );+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ queryClient.setQueryData(issueKeys.tasks("issue-1"), [makeTask()]);+ renderWithI18n(+ <QueryClientProvider client={queryClient}>+ <ExecutionLogSection issueId="issue-1" hasChildren />+ </QueryClientProvider>,+ );+ fireEvent.click(screen.getByRole("checkbox", { name: "Include sub-issues" }));+ expect(screen.getByRole("status", { name: "Loading runs..." })).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Execution log 1" })).not.toBeInTheDocument();+ expect(list).toHaveBeenCalledWith("issue-1", true);+ await act(async () => { rejectRequest(new Error("unavailable")); });+ const retry = await screen.findByRole("button", { name: "Could not load runs. Retry" });+ list.mockResolvedValue([makeTask({ id: "deep", issue_id: "deep-issue" })]);+ fireEvent.click(retry);+ await waitFor(() => expect(screen.getByRole("button", { name: "Execution log 1" })).toBeInTheDocument());+ expect(list).toHaveBeenCalledTimes(2);+ queryClient.clear();+ });});describe("ActiveTaskRow", () => {diff --git a/packages/views/issues/components/execution-log-section.tsx b/packages/views/issues/components/execution-log-section.tsxindex 8843888813..552b512691 100644--- a/packages/views/issues/components/execution-log-section.tsx+++ b/packages/views/issues/components/execution-log-section.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useMemo, useState } from "react";+import { useEffect, useId, useMemo, useState } from "react";import { useQuery } from "@tanstack/react-query";import { ChevronRight, Loader2, Maximize2, Square } from "@multica/ui/icons";import { toast } from "sonner";@@ -11,6 +11,8 @@ import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-stoimport type { AgentTask } from "@multica/core/types";import { IconButton } from "@multica/ui/components/common/icon-button";import { cn } from "@multica/ui/lib/utils";+import { Checkbox } from "@multica/ui/components/ui/checkbox";+import { Skeleton } from "@multica/ui/components/ui/skeleton";import { useTimeAgo } from "../../i18n";import {Tooltip,@@ -67,6 +69,7 @@ interface ExecutionLogSectionProps {/** Shown in the Runs dialog's subtitle so it names the issue it lays out. */identifier?: string;issueTitle?: string;+ hasChildren?: boolean;}// The sidebar lists this many rows; everything else is in the Runs dialog.@@ -86,10 +89,18 @@ const PAST_STATUS_RANK: Record<string, number> = {completed: 2,};-export function ExecutionLogSection({ issueId, identifier, issueTitle }: ExecutionLogSectionProps) {+export function ExecutionLogSection({+ issueId,+ identifier,+ issueTitle,+ hasChildren = false,+}: ExecutionLogSectionProps) {const { t } = useT("issues");const [open, setOpen] = useState(true);const [runsOpen, setRunsOpen] = useState(false);+ const [includeChildren, setIncludeChildren] = useState(false);+ const scopeLabelId = useId();+ const includeDescendants = hasChildren && includeChildren;const pricings = useCustomPricingStore((s) => s.pricings);// Cache key registered in `issueKeys.tasks` (packages/core/issues/queries.ts)@@ -97,7 +108,9 @@ export function ExecutionLogSection({ issueId, identifier, issueTitle }: Executi// a `["issues", "tasks"]` prefix-match — no local WS subscriptions// needed, and the cache stays fresh even when this component isn't// mounted (e.g. user cancels from agent-side, then navigates here).- const { data: tasks = [] } = useQuery(issueTasksOptions(issueId));+ const { data: tasks = [], isPending, isError, refetch } = useQuery(+ issueTasksOptions(issueId, includeDescendants),+ );const activeTasks = useMemo(() =>@@ -140,7 +153,7 @@ export function ExecutionLogSection({ issueId, identifier, issueTitle }: Executi[tasks, pricings],);- if (activeTasks.length === 0 && pastTasks.length === 0) return null;+ if (!hasChildren && activeTasks.length === 0 && pastTasks.length === 0) return null;const queuedTasks = activeTasks.filter((task) => task.status === "queued");const startedTasks = activeTasks.filter((task) => task.status !== "queued");@@ -176,17 +189,44 @@ export function ExecutionLogSection({ issueId, identifier, issueTitle }: Executi)}{activeTasks.length > 0 && (<div className="max-h-48 space-y-0.5 overflow-y-auto overscroll-contain rounded-md focus-visible:outline-2 focus-visible:outline-ring" role="region" aria-label={t(($) => $.runs_timeline.count_active, { count: activeTasks.length })} tabIndex={0}>- {startedTasks.map((task) => <ActiveTaskRow key={task.id} task={task} issueId={issueId} />)}+ {startedTasks.map((task) => <ActiveTaskRow key={task.id} task={task} issueId={task.issue_id || issueId} showIssue={includeDescendants} />)}{groupQueued ? (- <QueuedTasksGroup tasks={queuedTasks} issueId={issueId} />+ <QueuedTasksGroup tasks={queuedTasks} issueId={issueId} showIssue={includeDescendants} />) : (- queuedTasks.map((task) => <ActiveTaskRow key={task.id} task={task} issueId={issueId} />)+ queuedTasks.map((task) => <ActiveTaskRow key={task.id} task={task} issueId={task.issue_id || issueId} showIssue={includeDescendants} />))}</div>)}- {latest.length > 0 && <div className="space-y-0.5">- {latest.map((task) => <PastRow key={task.id} task={task} issueId={issueId} />)}- </div>}+ {hasChildren && (+ <div className="flex min-h-7 items-center justify-between gap-2 px-2 text-micro text-muted-foreground">+ <span>{t(($) => $.execution_log.latest)}</span>+ <label className="flex shrink-0 cursor-pointer items-center gap-1.5 whitespace-nowrap">+ <Checkbox+ aria-labelledby={scopeLabelId}+ checked={includeDescendants}+ onCheckedChange={setIncludeChildren}+ className="size-3 [&_svg]:size-2.5"+ />+ <span id={scopeLabelId}>{t(($) => $.execution_log.include_children)}</span>+ </label>+ </div>+ )}+ {isPending ? (+ <div role="status" aria-label={t(($) => $.execution_log.loading)} className="space-y-2 px-2 py-1">+ <Skeleton className="h-6 w-full" />+ <Skeleton className="h-6 w-3/4" />+ </div>+ ) : isError ? (+ <button type="button" onClick={() => void refetch()} className="px-2 py-1 text-caption text-destructive underline">+ {t(($) => $.execution_log.load_failed_retry)}+ </button>+ ) : tasks.every((task) => task.status === "deferred") ? (+ <p className="px-2 py-1 text-caption text-muted-foreground">{t(($) => $.execution_log.empty)}</p>+ ) : latest.length > 0 && (+ <div className="space-y-0.5">+ {latest.map((task) => <PastRow key={task.id} task={task} issueId={task.issue_id || issueId} showIssue={includeDescendants} />)}+ </div>+ )}</div>)}<IssueRunsDialog@@ -195,7 +235,8 @@ export function ExecutionLogSection({ issueId, identifier, issueTitle }: ExecutiissueId={issueId}identifier={identifier ?? ""}issueTitle={issueTitle}- tasks={tasks}+ hasChildren={hasChildren}+ includeDescendants={includeDescendants}/></div>);@@ -334,6 +375,7 @@ function RunBarSummary({ run }: { run: TimelineRun }) {</RunTriggerLabel><span className="text-micro text-muted-foreground">{[+ run.task.issue_identifier,// A run still going has not reported usage yet — that is not "none".run.usage? formatSpend(run.usage)@@ -459,11 +501,13 @@ export function ActiveTaskRow({task,issueId,onTranscriptOpenChange,+ showIssue = false,onJump,}: {task: AgentTask;issueId: string;onTranscriptOpenChange?: (open: boolean, fromKeyboard?: boolean) => void;+ showIssue?: boolean;/** Turns the trigger into a button that takes the reader to this run's block. */onJump?: () => void;}) {@@ -524,7 +568,7 @@ export function ActiveTaskRow({<TriggerText text={trigger} />);return (- <RowShell task={task}>+ <RowShell task={task} showIssue={showIssue}>{onJump ? (<buttontype="button"@@ -600,7 +644,7 @@ export function ActiveTaskRow({// Several queued runs as one row: who is waiting and how many. Expanding it// lists each run in place, with its cancel action.-function QueuedTasksGroup({ tasks, issueId }: { tasks: AgentTask[]; issueId: string }) {+function QueuedTasksGroup({ tasks, issueId, showIssue }: { tasks: AgentTask[]; issueId: string; showIssue: boolean }) {const { t } = useT("issues");const { getActorName } = useActorName();const [expanded, setExpanded] = useState(false);@@ -627,14 +671,14 @@ function QueuedTasksGroup({ tasks, issueId }: { tasks: AgentTask[]; issueId: str<ChevronRight aria-hidden="true" className={cn("size-3 text-faint-foreground transition-transform motion-reduce:transition-none", expanded && "rotate-90")} /></span></button>- {expanded && tasks.map((task) => <ActiveTaskRow key={task.id} task={task} issueId={issueId} />)}+ {expanded && tasks.map((task) => <ActiveTaskRow key={task.id} task={task} issueId={task.issue_id || issueId} showIssue={showIssue} />)}</>);}// ─── Past row ──────────────────────────────────────────────────────────────-function PastRow({ task, issueId }: { task: AgentTask; issueId: string }) {+function PastRow({ task, issueId, showIssue = false }: { task: AgentTask; issueId: string; showIssue?: boolean }) {const { t } = useT("issues");const formatSpend = useFormatSpend();const { t: tAgents } = useT("agents");@@ -685,7 +729,7 @@ function PastRow({ task, issueId }: { task: AgentTask; issueId: string }) {].filter(Boolean).join(" · ");return (- <RowShell task={task} title={rowTitle} multiline={Boolean(reason)}>+ <RowShell task={task} title={rowTitle} multiline={Boolean(reason)} showIssue={showIssue}><div className="min-w-0 flex-1"><div className="flex min-w-0 items-center gap-2">{task.wakeup_id ? (@@ -731,6 +775,7 @@ function RowShell({title,multiline = false,children,+ showIssue = false,}: {task: AgentTask;/** Carries the details the right column no longer has room for (time,@@ -741,6 +786,7 @@ function RowShell({/** Top-aligns the avatar with the first of several lines. */multiline?: boolean;children: React.ReactNode;+ showIssue?: boolean;}) {return (<div@@ -762,6 +808,11 @@ function RowShell({<span className="inline-block h-5 w-5 rounded-full bg-muted" />)}</span>+ {showIssue && (+ <span className="max-w-20 shrink-0 truncate font-mono text-micro text-muted-foreground" title={task.issue_title}>+ {task.issue_identifier || task.issue_id}+ </span>+ )}{children}</div>);diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 24c037df46..4a2ec188d3 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -3157,7 +3157,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr<DeliverablesSection files={deliverableFiles} onOpenOverview={openOverview} />{/* Execution summary owns its query, realtime updates and disclosure. */}- <ExecutionLogSection issueId={id} identifier={issue.identifier} issueTitle={issue.title} />+ <ExecutionLogSection key={id} issueId={id} identifier={issue.identifier} issueTitle={issue.title} hasChildren={childIssues.length > 0} />{/* Details — creator and timestamps. Sits below the execution logbecause it is the least-read block in the sidebar: the valuesdiff --git a/packages/views/issues/components/issue-runs-cumulative-chart.tsx b/packages/views/issues/components/issue-runs-cumulative-chart.tsxindex 0ee0627233..181140c743 100644--- a/packages/views/issues/components/issue-runs-cumulative-chart.tsx+++ b/packages/views/issues/components/issue-runs-cumulative-chart.tsx@@ -402,7 +402,7 @@ function PeakLabel({><span className="font-medium text-foreground">+{formatUsd(run.usage?.cost ?? 0)}</span><RunTriggerLabel task={run.task} fallback={trigger}>- {(label) => <span className="truncate text-muted-foreground">{label}</span>}+ {(label) => <span className="truncate text-muted-foreground">{[run.task.issue_identifier, label].filter(Boolean).join(" · ")}</span>}</RunTriggerLabel></span>);@@ -430,7 +430,7 @@ function CumulativeRunCard({ run }: { run: TimelineRun }) {return (<div className="flex min-w-0 flex-col gap-1"><RunTriggerLabel task={run.task} fallback={trigger}>- {(label) => <span className="truncate font-medium">{label}</span>}+ {(label) => <span className="truncate font-medium">{[run.task.issue_identifier, label].filter(Boolean).join(" · ")}</span>}</RunTriggerLabel><span className="flex min-w-0 items-center gap-1.5 text-micro text-muted-foreground"><ActorAvatar actorType="agent" actorId={run.task.agent_id} size="xs" />diff --git a/packages/views/issues/components/issue-runs-dialog.test.tsx b/packages/views/issues/components/issue-runs-dialog.test.tsxindex 2bfcc95b52..4908a77a77 100644--- a/packages/views/issues/components/issue-runs-dialog.test.tsx+++ b/packages/views/issues/components/issue-runs-dialog.test.tsx@@ -3,6 +3,8 @@import { act, cleanup, fireEvent, screen, within } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { AgentTask, TaskUsage } from "@multica/core/types";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { issueKeys } from "@multica/core/issues/queries";import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";import { renderWithI18n } from "../../test/i18n";@@ -61,15 +63,18 @@ function usage(overrides: Partial<TaskUsage> = {}): TaskUsage {}function open(tasks: AgentTask[], locale?: "zh-Hans") {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ queryClient.setQueryData(issueKeys.tasks("issue-1"), tasks);return renderWithI18n(- <IssueRunsDialog- open- onOpenChange={() => {}}- issueId="issue-1"- identifier="MUL-7680"- issueTitle="Issue wakeups v2"- tasks={tasks}- />,+ <QueryClientProvider client={queryClient}>+ <IssueRunsDialog+ open+ onOpenChange={() => {}}+ issueId="issue-1"+ identifier="MUL-7680"+ issueTitle="Issue wakeups v2"+ />+ </QueryClientProvider>,{ locale },);}diff --git a/packages/views/issues/components/issue-runs-dialog.tsx b/packages/views/issues/components/issue-runs-dialog.tsxindex a51a3b78f5..6396d62633 100644--- a/packages/views/issues/components/issue-runs-dialog.tsx+++ b/packages/views/issues/components/issue-runs-dialog.tsx@@ -1,9 +1,12 @@"use client";-import { useMemo, useRef, useState } from "react";+import { useId, useMemo, useRef, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { issueTasksOptions } from "@multica/core/issues/queries";import { ArrowRight, Ban, ChevronRight, XCircle } from "@multica/ui/icons";import type { AgentTask } from "@multica/core/types";import { cn } from "@multica/ui/lib/utils";+import { Checkbox } from "@multica/ui/components/ui/checkbox";import {Dialog,DialogContent,@@ -54,8 +57,8 @@ import { useFormatSpend, useStatusLabel, useTriggerText } from "./task-run-label// newest first — it is also the chart's accessible, exact-value view. The// cumulative cost curve over time is the chart's second view.//-// Every figure comes from the same `summarizeTaskUsage` helpers the sidebar-// uses, so the total here can never disagree with the total that opened it.+// Every figure uses the same pricing helpers as the sidebar, but the dialog+// can independently narrow or expand the scope after opening.// Cost categories in the order and colours the runtime usage charts stack them// (`costStackConfig` in runtimes/components/charts/daily-cost-chart.tsx), so a@@ -108,35 +111,51 @@ function usePercent(): (share: number) => string {return (share) => fmt.format(share);}-export function IssueRunsDialog({- open,- onOpenChange,- issueId,- identifier,- issueTitle,- tasks,-}: {+type IssueRunsDialogProps = {open: boolean;onOpenChange: (open: boolean) => void;issueId: string;identifier: string;issueTitle?: string;- tasks: AgentTask[];-}) {+ hasChildren?: boolean;+ includeDescendants?: boolean;+};++export function IssueRunsDialog({ open, onOpenChange, ...props }: IssueRunsDialogProps) {+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ {/* Each opening inherits the sidebar scope; edits remain local to this session. */}+ {open && <IssueRunsDialogContent key={props.issueId} {...props} />}+ </Dialog>+ );+}++function IssueRunsDialogContent({+ issueId,+ identifier,+ issueTitle,+ hasChildren = false,+ includeDescendants = false,+}: Omit<IssueRunsDialogProps, "open" | "onOpenChange">) {const { t } = useT("issues");+ const [includeChildren, setIncludeChildren] = useState(includeDescendants);+ const scopeLabelId = useId();+ const { data: tasks = [], isPending, isError, refetch } = useQuery(+ issueTasksOptions(issueId, includeChildren),+ );// `estimateCost` reads custom rates imperatively out of the Zustand store,// so nothing re-renders this dialog when the user saves a new rate. Subscribe// to the snapshot and carry it into every memo that prices usage — same// reason the runtime usage page subscribes in usage-section.tsx.const pricings = useCustomPricingStore((s) => s.pricings);// Active runs stretch to "now". The clock is re-read when the task list- // changes or the dialog reopens rather than ticking: the bars move by+ // changes or the dialog mounts rather than ticking: the bars move by// minutes, and a live timer already runs in the sidebar row.const timeline = useMemo(() => buildRunTimeline(tasks, Date.now()),- // `pricings` re-prices on a saved custom rate; `open` re-reads the clock.+ // `pricings` re-prices on a saved custom rate.// eslint-disable-next-line react-hooks/exhaustive-deps- [tasks, pricings, open],+ [tasks, pricings],);// Models with no rate-table entry and no provider-reported cost: their tokens// are counted but their spend is not, so the totals understate reality.@@ -147,19 +166,42 @@ export function IssueRunsDialog({);return (- <Dialog open={open} onOpenChange={onOpenChange}>+ <>{/* DialogContent's base is `sm:max-w-sm`, which a same-specificity`max-w-5xl` does not beat — `!` wins it, matching the transcriptdialog. Fixed height so the chart stays put while the list scrolls. */}<DialogContent className="flex !h-[min(56rem,calc(100dvh-4rem))] !w-[calc(100vw-4rem)] !max-w-5xl flex-col !gap-0 overflow-hidden !p-0"><DialogHeader className="px-6 pt-5 pb-4"><DialogTitle>{t(($) => $.runs_timeline.title)}</DialogTitle>- <DialogDescription>- {issueTitle ? `${identifier} · ${issueTitle}` : identifier}- </DialogDescription>+ <div className="flex min-w-0 items-start justify-between gap-3">+ <DialogDescription className="min-w-0 break-words">+ {issueTitle ? `${identifier} · ${issueTitle}` : identifier}+ </DialogDescription>+ {(hasChildren || includeDescendants) && (+ <label className="ml-auto flex min-h-5 shrink-0 cursor-pointer items-center gap-1.5 whitespace-nowrap text-micro text-muted-foreground">+ <Checkbox+ className="size-3 [&_svg]:size-2.5"+ checked={includeChildren}+ onCheckedChange={setIncludeChildren}+ aria-labelledby={scopeLabelId}+ />+ <span id={scopeLabelId}>{t(($) => $.execution_log.include_children)}</span>+ </label>+ )}+ </div></DialogHeader>- {timeline.runs.length > 0 && (+ {isPending ? (+ <p role="status" aria-label={t(($) => $.execution_log.loading)} className="px-6 py-4 text-body text-muted-foreground">+ {t(($) => $.execution_log.loading)}+ </p>+ ) : isError ? (+ <button type="button" onClick={() => void refetch()} className="mx-6 my-4 self-start text-body text-muted-foreground hover:text-foreground">+ {t(($) => $.execution_log.load_failed_retry)}+ </button>+ ) : timeline.runs.length === 0 ? (+ <p className="px-6 py-4 text-body text-muted-foreground">{t(($) => $.execution_log.empty)}</p>+ ) : (<><RunStats timeline={timeline} /><RunCharts timeline={timeline} />@@ -167,7 +209,7 @@ export function IssueRunsDialog({{/* `min-h-0`: the dialog is a flex column; without it this flexitem sizes to its content and the list never scrolls. */}<div className="min-h-0 flex-1 overflow-y-auto px-6 pb-5">- <RunDayList timeline={timeline} issueId={issueId} />+ <RunDayList timeline={timeline} issueId={issueId} showIssue={includeChildren} /><div className="mt-4 space-y-1 text-micro text-muted-foreground">{unmapped.length > 0 && (<p>{t(($) => $.runs_timeline.note_unmapped, { models: unmapped.join(", ") })}</p>@@ -178,7 +220,7 @@ export function IssueRunsDialog({</>)}</DialogContent>- </Dialog>+ </>);}@@ -608,6 +650,7 @@ function RunHoverCard({ run, parts }: { run: TimelineRun; parts: boolean }) {hour12: false,}).format(run.startMs);const facts = [+ run.task.issue_identifier,when,run.task.status === "completed" && run.durationMs != null? formatDuration(run.durationMs / 1000, UNDER_A_SECOND)@@ -747,7 +790,7 @@ const COL = {toggle: "w-6 shrink-0",} as const;-function RunDayList({ timeline, issueId }: { timeline: RunTimeline; issueId: string }) {+function RunDayList({ timeline, issueId, showIssue }: { timeline: RunTimeline; issueId: string; showIssue: boolean }) {const { t } = useT("issues");const formatSpend = useFormatSpend();const locale = useLocale();@@ -807,7 +850,7 @@ function RunDayList({ timeline, issueId }: { timeline: RunTimeline; issueId: str</span></div>{group.runs.map((run) => (- <RunListRow key={run.task.id} run={run} issueId={issueId} costWidth={costWidth} />+ <RunListRow key={run.task.id} run={run} issueId={run.task.issue_id || issueId} showIssue={showIssue} costWidth={costWidth} />))}</section>);@@ -828,7 +871,7 @@ function useStatusReason(task: AgentTask): string | null {return [cancelledBy, reason].filter(Boolean).join(" · ") || null;}-function RunListRow({ run, issueId, costWidth }: { run: TimelineRun; issueId: string; costWidth: string }) {+function RunListRow({ run, issueId, showIssue, costWidth }: { run: TimelineRun; issueId: string; showIssue: boolean; costWidth: string }) {const { t } = useT("issues");const formatSpend = useFormatSpend();const locale = useLocale();@@ -872,6 +915,11 @@ function RunListRow({ run, issueId, costWidth }: { run: TimelineRun; issueId: strun.usage || run.active ? "text-foreground" : "text-muted-foreground",)}>+ {showIssue && (+ <span className="mr-2 font-mono text-micro text-muted-foreground" title={task.issue_title}>+ {task.issue_identifier || task.issue_id}+ </span>+ )}{text}</span></TruncatedTooltip>diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 64abb5bba5..c047a11d6b 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -812,6 +812,11 @@"cancel_failed": "Failed to cancel run"},"execution_log": {+ "latest": "Latest",+ "include_children": "Include sub-issues",+ "loading": "Loading runs...",+ "load_failed_retry": "Could not load runs. Retry",+ "empty": "No runs in this scope.","section": "Execution log","cancel_task_tooltip": "Cancel run","cancel_task_aria": "Cancel run",diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.jsonindex 45e7478159..a9af2b0656 100644--- a/packages/views/locales/es/issues.json+++ b/packages/views/locales/es/issues.json@@ -795,6 +795,11 @@"cancel_failed": "No se ha podido cancelar la ejecución"},"execution_log": {+ "latest": "Recientes",+ "include_children": "Incluir subtareas",+ "loading": "Cargando ejecuciones...",+ "load_failed_retry": "No se han podido cargar las ejecuciones. Reintentar",+ "empty": "No hay ejecuciones en este ámbito.","section": "Registro de ejecución","cancel_task_tooltip": "Cancelar ejecución","cancel_task_aria": "Cancelar ejecución",diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex 82e1ab2299..68eb45d47a 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -812,6 +812,11 @@"cancel_failed": "Échec de l'annulation de l'exécution"},"execution_log": {+ "latest": "Récentes",+ "include_children": "Inclure les sous-tâches",+ "loading": "Chargement des exécutions...",+ "load_failed_retry": "Impossible de charger les exécutions. Réessayer",+ "empty": "Aucune exécution dans ce périmètre.","section": "Journal d'exécution","cancel_task_tooltip": "Annuler l'exécution","cancel_task_aria": "Annuler l'exécution",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex a39b4a5ae4..71c6201abb 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -782,6 +782,11 @@"cancel_failed": "実行をキャンセルできませんでした"},"execution_log": {+ "latest": "最新",+ "include_children": "サブタスクを含める",+ "loading": "実行履歴を読み込み中...",+ "load_failed_retry": "実行履歴を読み込めませんでした。再試行",+ "empty": "この範囲には実行履歴がありません。","section": "実行ログ","cancel_task_tooltip": "実行をキャンセル","cancel_task_aria": "実行をキャンセル",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex a2752a0a71..d9656ebcf3 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -782,6 +782,11 @@"cancel_failed": "실행을 취소하지 못했습니다"},"execution_log": {+ "latest": "최근",+ "include_children": "하위 태스크 포함",+ "loading": "실행 기록 불러오는 중...",+ "load_failed_retry": "실행 기록을 불러올 수 없습니다. 다시 시도",+ "empty": "이 범위에 실행 기록이 없습니다.","section": "실행 로그","cancel_task_tooltip": "실행 취소","cancel_task_aria": "실행 취소",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex d48b35dd5b..2c72423099 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -782,6 +782,11 @@"cancel_failed": "取消运行失败"},"execution_log": {+ "latest": "最近",+ "include_children": "包含子任务",+ "loading": "正在加载运行记录...",+ "load_failed_retry": "无法加载运行记录,点击重试",+ "empty": "此范围内暂无运行记录。","section": "执行日志","cancel_task_tooltip": "取消运行","cancel_task_aria": "取消运行",diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.jsonindex 0185d72bb6..3ddb04eb53 100644--- a/packages/views/locales/zh-Hant/issues.json+++ b/packages/views/locales/zh-Hant/issues.json@@ -782,6 +782,11 @@"cancel_failed": "取消執行失敗"},"execution_log": {+ "latest": "最近",+ "include_children": "包含子任務",+ "loading": "正在載入執行記錄...",+ "load_failed_retry": "無法載入執行記錄,點擊重試",+ "empty": "此範圍內暫無執行記錄。","section": "執行日誌","cancel_task_tooltip": "取消執行","cancel_task_aria": "取消執行",diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex a911d079b1..be78a9baf0 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -408,6 +408,7 @@ type AgentTaskResponse struct {WorkspaceID string `json:"workspace_id"`WorkspaceSlug string `json:"workspace_slug,omitempty"`IssueIdentifier string `json:"issue_identifier,omitempty"`+ IssueTitle string `json:"issue_title,omitempty"`RemoteMCPConnections []remotemcp.Connection `json:"remote_mcp_connections,omitempty"`// PluginHookTools are the workspace's agent-trigger plugin hooks, which the// daemon renders as MCP tools for this task. Resolved at claim time sodiff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 6981cd47c6..2e0510fca3 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -6300,6 +6300,8 @@ type ActiveRunSummary struct {// child of that parent. Implies active=true, because a full execution// history across a whole family is unbounded and answers no question anyone// asked.+// - scope=subtree — full execution history for this issue and all descendants.+// Unlike family, it never includes ancestors or siblings and is not capped.func (h *Handler) ListTasksByIssue(w http.ResponseWriter, r *http.Request) {issueID := chi.URLParam(r, "id")issue, ok := h.loadIssueForUser(w, r, issueID)@@ -6308,8 +6310,8 @@ func (h *Handler) ListTasksByIssue(w http.ResponseWriter, r *http.Request) {}scope := r.URL.Query().Get("scope")- if scope != "" && scope != "issue" && scope != "family" {- writeError(w, http.StatusBadRequest, "scope must be 'issue' or 'family'")+ if scope != "" && scope != "issue" && scope != "family" && scope != "subtree" {+ writeError(w, http.StatusBadRequest, "scope must be 'issue', 'family', or 'subtree'")return}// Parse rather than compare. `active=tru` answering with the full history@@ -6379,7 +6381,20 @@ func (h *Handler) ListTasksByIssue(w http.ResponseWriter, r *http.Request) {var tasks []db.AgentTaskQueuevar err error- if activeOnly {+ type issueLabel struct{ identifier, title string }+ labels := make(map[string]issueLabel)+ if scope == "subtree" {+ rows, queryErr := h.Queries.ListTasksByIssueSubtree(r.Context(), db.ListTasksByIssueSubtreeParams{+ RootIssueID: issue.ID, WorkspaceID: issue.WorkspaceID, ActiveOnly: activeOnly,+ })+ err = queryErr+ for _, row := range rows {+ tasks = append(tasks, row.AgentTaskQueue)+ labels[uuidToString(row.AgentTaskQueue.IssueID)] = issueLabel{+ identifier: service.IssueIdentifier(row.IssuePrefix, row.IssueNumber), title: row.IssueTitle,+ }+ }+ } else if activeOnly {tasks, err = h.Queries.ListActiveTasksByIssue(r.Context(), issue.ID)} else {tasks, err = h.Queries.ListTasksByIssue(r.Context(), issue.ID)@@ -6393,6 +6408,10 @@ func (h *Handler) ListTasksByIssue(w http.ResponseWriter, r *http.Request) {resp := make([]AgentTaskResponse, len(tasks))for i, t := range tasks {resp[i] = taskToResponse(t, workspaceID)+ if label, ok := labels[resp[i].IssueID]; ok {+ resp[i].IssueIdentifier = label.identifier+ resp[i].IssueTitle = label.title+ }}h.hydrateTaskSupplementMetadata(r.Context(), r, issue.WorkspaceID, tasks, resp)// Execution-log rows render the "on behalf of <member>" badge, so this@@ -6405,12 +6424,38 @@ func (h *Handler) ListTasksByIssue(w http.ResponseWriter, r *http.Request) {// paying the full-history cost this filter exists to remove — and pay it// for a column that is near-empty on runs that have not finished.if !activeOnly {- h.hydrateTaskUsage(r.Context(), issue.ID, resp)+ if scope == "subtree" {+ h.hydrateSubtreeTaskUsage(r.Context(), tasks, resp)+ } else {+ h.hydrateTaskUsage(r.Context(), issue.ID, resp)+ }}writeJSON(w, http.StatusOK, resp)}+// Usage is fetched only for the authorized, visible subtree runs in one batch.+func (h *Handler) hydrateSubtreeTaskUsage(ctx context.Context, tasks []db.AgentTaskQueue, resp []AgentTaskResponse) {+ if len(tasks) == 0 {+ return+ }+ ids := make([]pgtype.UUID, len(tasks))+ for i, task := range tasks {+ ids[i] = task.ID+ }+ rows, err := h.Queries.ListTaskUsageByIDs(ctx, ids)+ if err != nil {+ return+ }+ byTask := make(map[string][]TaskUsageData, len(resp))+ for _, row := range rows {+ appendTaskUsage(byTask, row.TaskID, row.Provider, row.Model,+ row.InputTokens, row.OutputTokens, row.CacheReadTokens,+ row.CacheWriteTokens, row.CostUsdTicks, row.CreditsMicros)+ }+ attachTaskUsage(resp, byTask)+}+// hydrateTaskUsage attaches each run's own token usage to the execution-log// rows. One query for the whole issue, then a map join — not one query per// task, which would be an N+1 over a list the UI always renders in full.diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex dbc88c92bd..7acfbe2d12 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -4202,25 +4202,27 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {willRun = willRun && !req.SuppressRunupdatedPayload := map[string]any{- "issue": resp,- "assignee_changed": assigneeChanged,- "status_changed": statusChanged,- "priority_changed": priorityChanged,- "project_changed": projectChanged,- "start_date_changed": startDateChanged,- "due_date_changed": dueDateChanged,- "description_changed": descriptionChanged,- "title_changed": titleChanged,- "prev_title": prevIssue.Title,- "prev_assignee_type": textToPtr(prevIssue.AssigneeType),- "prev_assignee_id": uuidToPtr(prevIssue.AssigneeID),- "prev_status": prevIssue.Status,- "prev_priority": prevIssue.Priority,- "prev_start_date": prevStartDate,- "prev_due_date": prevDueDate,- "prev_description": textToPtr(prevIssue.Description),- "creator_type": prevIssue.CreatorType,- "creator_id": uuidToString(prevIssue.CreatorID),+ "issue": resp,+ "assignee_changed": assigneeChanged,+ "status_changed": statusChanged,+ "priority_changed": priorityChanged,+ "project_changed": projectChanged,+ "start_date_changed": startDateChanged,+ "due_date_changed": dueDateChanged,+ "description_changed": descriptionChanged,+ "title_changed": titleChanged,+ "parent_changed": prevIssue.ParentIssueID != issue.ParentIssueID,+ "prev_parent_issue_id": uuidToPtr(prevIssue.ParentIssueID),+ "prev_title": prevIssue.Title,+ "prev_assignee_type": textToPtr(prevIssue.AssigneeType),+ "prev_assignee_id": uuidToPtr(prevIssue.AssigneeID),+ "prev_status": prevIssue.Status,+ "prev_priority": prevIssue.Priority,+ "prev_start_date": prevStartDate,+ "prev_due_date": prevDueDate,+ "prev_description": textToPtr(prevIssue.Description),+ "creator_type": prevIssue.CreatorType,+ "creator_id": uuidToString(prevIssue.CreatorID),// Both ends of a mark change ride here: the activity log records it// and clients refresh the two issues' relations from it."duplicate_of_issue_id": liveDuplicateMark(issue.Status, issue.DuplicateOfIssueID),@@ -5004,6 +5006,10 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {"status_changed": statusChanged,"priority_changed": priorityChanged,"project_changed": projectChanged,+ "title_changed": req.Updates.Title != nil && prevIssue.Title != issue.Title,+ "prev_title": prevIssue.Title,+ "parent_changed": prevIssue.ParentIssueID != issue.ParentIssueID,+ "prev_parent_issue_id": uuidToPtr(prevIssue.ParentIssueID),"prev_status": prevIssue.Status,"duplicate_of_issue_id": liveDuplicateMark(issue.Status, issue.DuplicateOfIssueID),"prev_duplicate_of_issue_id": liveDuplicateMark(prevIssue.Status, prevIssue.DuplicateOfIssueID),diff --git a/server/internal/handler/issue_subtree_events_test.go b/server/internal/handler/issue_subtree_events_test.gonew file mode 100644index 0000000000..08701a02d3--- /dev/null+++ b/server/internal/handler/issue_subtree_events_test.go@@ -0,0 +1,95 @@+package handler++import (+ "net/http"+ "sync"+ "testing"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func TestIssueSubtreeChangeEvents(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ for _, batch := range []bool{false, true} {+ name := "single"+ if batch {+ name = "batch"+ }+ t.Run(name, func(t *testing.T) {+ parent := dbfx.Issue(t, "subtree event parent")+ otherParent := dbfx.Issue(t, "subtree event other parent")+ child := dbfx.Issue(t, "subtree event child")+ h := *testHandler+ h.Bus = events.New()+ var mu sync.Mutex+ var payloads []map[string]any+ h.Bus.Subscribe(protocol.EventIssueUpdated, func(e events.Event) {+ payload, ok := e.Payload.(map[string]any)+ if !ok {+ return+ }+ if issue, ok := payload["issue"].(IssueResponse); ok && issue.ID == child {+ mu.Lock()+ payloads = append(payloads, payload)+ mu.Unlock()+ }+ })+ steps := []struct {+ name string+ updates map[string]any+ parentChanged bool+ prevParent *string+ titleChanged bool+ }{+ {name: "ordinary edit", updates: map[string]any{"priority": "high"}},+ {name: "attach", updates: map[string]any{"parent_issue_id": parent}, parentChanged: true},+ {name: "same parent", updates: map[string]any{"parent_issue_id": parent}, prevParent: &parent},+ {name: "move", updates: map[string]any{"parent_issue_id": otherParent}, parentChanged: true, prevParent: &parent},+ {name: "detach", updates: map[string]any{"parent_issue_id": nil}, parentChanged: true, prevParent: &otherParent},+ {name: "rename", updates: map[string]any{"title": "Renamed child"}, titleChanged: true},+ {name: "same title", updates: map[string]any{"title": "Renamed child"}},+ }+ for _, step := range steps {+ t.Run(step.name, func(t *testing.T) {+ mu.Lock()+ payloads = nil+ mu.Unlock()+ if batch {+ testutil.Call(t, h.BatchUpdateIssues, newRequest(http.MethodPost, "/api/issues/batch-update", map[string]any{+ "issue_ids": []string{child}, "updates": step.updates,+ })).Want(http.StatusOK)+ } else {+ testutil.Call(t, h.UpdateIssue, updateIssueRequest(child, step.updates)).Want(http.StatusOK)+ }+ mu.Lock()+ defer mu.Unlock()+ if len(payloads) != 1 {+ t.Fatalf("got %d issue:updated events, want 1", len(payloads))+ }+ payload := payloads[0]+ if payload["parent_changed"] != step.parentChanged {+ t.Errorf("parent_changed = %v, want %v", payload["parent_changed"], step.parentChanged)+ }+ previous, ok := payload["prev_parent_issue_id"].(*string)+ if !ok {+ t.Fatalf("prev_parent_issue_id has unexpected type %T", payload["prev_parent_issue_id"])+ }+ if step.prevParent == nil {+ if previous != nil {+ t.Errorf("previous parent = %s, want nil", *previous)+ }+ } else if previous == nil || *previous != *step.prevParent {+ t.Errorf("previous parent = %v, want %s", previous, *step.prevParent)+ }+ if payload["title_changed"] != step.titleChanged {+ t.Errorf("title_changed = %v, want %v", payload["title_changed"], step.titleChanged)+ }+ })+ }+ })+ }+}diff --git a/server/internal/handler/task_runs_scope_test.go b/server/internal/handler/task_runs_scope_test.goindex e4d8dae249..15cdd7de67 100644--- a/server/internal/handler/task_runs_scope_test.go+++ b/server/internal/handler/task_runs_scope_test.go@@ -133,6 +133,83 @@ func TestListTasksByIssueDefaultsToFullHistory(t *testing.T) {}}+func TestListTasksByIssueSubtreeIncludesAllDescendantsAndUsage(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ f := newFamilyFixture(t)+ grandchild := dbfx.Issue(t, "grandchild", testutil.Cols{"parent_issue_id": f.childA})+ greatGrandchild := dbfx.Issue(t, "great-grandchild", testutil.Cols{"parent_issue_id": grandchild})+ rootRun := f.task(t, f.parentID, "completed")+ childRun := f.task(t, f.childA, "failed")+ grandchildRun := f.task(t, grandchild, "cancelled")+ deepRun := f.task(t, greatGrandchild, "running")+ siblingRun := f.task(t, f.childB, "queued")+ f.task(t, f.unrelated, "completed")+ // A malformed cross-workspace parent pointer must not widen authorization.+ otherWorkspace := dbfx.Workspace(t, "other subtree workspace", "other-subtree")+ foreignChild := dbfx.Issue(t, "foreign child", testutil.Cols{"workspace_id": otherWorkspace, "parent_issue_id": f.parentID})+ f.task(t, foreignChild, "completed")+ if _, err := testPool.Exec(context.Background(), `+ INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost_usd_ticks, credits_micros)+ VALUES ($1, 'openai', 'subtree-test-model', 100, 50, 20, 10, 2000000000, 1250000)+ `, grandchildRun); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM task_usage WHERE task_id = $1`, grandchildRun)+ })++ resp := runsRequest(t, f.parentID, "scope=subtree")+ if got, want := taskIDs(resp), sortedCopy(rootRun, childRun, grandchildRun, deepRun, siblingRun); !sameIDs(got, want) {+ t.Fatalf("subtree runs = %v, want %v", got, want)+ }+ for _, run := range resp {+ if run.IssueIdentifier == "" || run.IssueTitle == "" {+ t.Errorf("missing owning issue labels: %+v", run)+ }+ if run.ID == grandchildRun {+ if len(run.Usage) != 1 || run.Usage[0].InputTokens != 100 || run.Usage[0].CostUsdTicks == nil || *run.Usage[0].CostUsdTicks != 2000000000 {+ t.Errorf("grandchild usage missing or changed: %+v", run.Usage)+ } else if run.Usage[0].CreditsMicros == nil || *run.Usage[0].CreditsMicros != 1250000 {+ t.Errorf("grandchild credits missing or changed: %+v", run.Usage)+ }+ }+ }+ // Opening the same scope on a child must exclude its parent and siblings.+ if got, want := taskIDs(runsRequest(t, f.childA, "scope=subtree")), sortedCopy(childRun, grandchildRun, deepRun); !sameIDs(got, want) {+ t.Fatalf("child subtree = %v, want %v", got, want)+ }+ if got, want := taskIDs(runsRequest(t, f.parentID, "scope=subtree&active=true")), sortedCopy(deepRun, siblingRun); !sameIDs(got, want) {+ t.Fatalf("active subtree = %v, want %v", got, want)+ }+ if got, want := taskIDs(runsRequest(t, f.parentID, "")), sortedCopy(rootRun); !sameIDs(got, want) {+ t.Fatalf("default scope changed: %v, want %v", got, want)+ }+}++func TestListTasksByIssueSubtreeIsUncappedAndCycleSafe(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ f := newFamilyFixture(t)+ want := []string{}+ for range familyActiveRunCap + 3 {+ want = append(want, f.task(t, f.childA, "completed"))+ }+ // UNION on IDs must visit each node only once even in a corrupt cycle.+ if _, err := testPool.Exec(context.Background(), `UPDATE issue SET parent_issue_id = $1 WHERE id = $2`, f.childA, f.parentID); err != nil {+ t.Fatal(err)+ }+ sort.Strings(want)+ response := runsResponse(t, f.parentID, "scope=subtree").Want(http.StatusOK)+ var runs []AgentTaskResponse+ response.JSON(&runs)+ if got := taskIDs(runs); !sameIDs(got, want) {+ t.Fatalf("uncapped cycle-safe subtree = %v, want %v", got, want)+ }+}+func TestTaskHistoryOmitsUnusedAssigneeFallbacks(t *testing.T) {if testHandler == nil || testPool == nil {t.Skip("database not available")diff --git a/server/internal/service/builtin_skills/multica-platform/references/issues.md b/server/internal/service/builtin_skills/multica-platform/references/issues.mdindex 328dedbfcc..280096fc3b 100644--- a/server/internal/service/builtin_skills/multica-platform/references/issues.md+++ b/server/internal/service/builtin_skills/multica-platform/references/issues.md@@ -310,6 +310,17 @@ archived statuses remain readable via an explicit status filter.## Who else is running right now+The issue sidebar's **Include sub-issues** checkbox uses+`GET /api/issues/{id}/task-runs?scope=subtree` to show the current issue and+every descendant at any depth. This is full, uncapped execution history with+per-run usage and owning issue labels, never ancestors or siblings. It drives+the sidebar totals, status indicators, spend chart, and complete Runs timeline.+The Runs dialog inherits the sidebar scope when opened and provides its own+checkbox beside the issue title. Changing it updates only the dialog; reopening+the dialog inherits the sidebar selection again.+The default endpoint still returns only the current issue. The subtree scope+is separate from the active-only family coordination read below.+Nothing about concurrent runs is pushed into your prompt: the answer changeswhile a turn is running, and most turns never need it. Ask the server on theturns that do — before opening a PR against code a sibling issue also touches:diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 24c6d38e38..e3492b85b1 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -6357,6 +6357,124 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]return items, nil}+const listTasksByIssueSubtree = `-- name: ListTasksByIssueSubtree :many+WITH RECURSIVE subtree(id) AS (+ SELECT root.id FROM issue root+ WHERE root.id = $2 AND root.workspace_id = $3+ UNION+ SELECT child.id FROM issue child+ JOIN subtree parent ON child.parent_issue_id = parent.id+ WHERE child.workspace_id = $3+)+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step, i.title AS issue_title, i.number AS issue_number, w.issue_prefix+FROM agent_task_queue atq+JOIN subtree ON subtree.id = atq.issue_id+JOIN issue i ON i.id = atq.issue_id+JOIN workspace w ON w.id = i.workspace_id+WHERE NOT $1::boolean+ OR atq.status IN ('queued', 'dispatched', 'waiting_local_directory', 'running')+ORDER BY atq.created_at DESC, atq.id+`++type ListTasksByIssueSubtreeParams struct {+ ActiveOnly bool `json:"active_only"`+ RootIssueID pgtype.UUID `json:"root_issue_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++type ListTasksByIssueSubtreeRow struct {+ AgentTaskQueue AgentTaskQueue `json:"agent_task_queue"`+ IssueTitle string `json:"issue_title"`+ IssueNumber int32 `json:"issue_number"`+ IssuePrefix string `json:"issue_prefix"`+}++// UNION deduplicates IDs, so even a corrupt parent cycle terminates.+// Constrain every recursive step to the authorized root's workspace.+func (q *Queries) ListTasksByIssueSubtree(ctx context.Context, arg ListTasksByIssueSubtreeParams) ([]ListTasksByIssueSubtreeRow, error) {+ rows, err := q.db.Query(ctx, listTasksByIssueSubtree, arg.ActiveOnly, arg.RootIssueID, arg.WorkspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListTasksByIssueSubtreeRow{}+ for rows.Next() {+ var i ListTasksByIssueSubtreeRow+ if err := rows.Scan(+ &i.AgentTaskQueue.ID,+ &i.AgentTaskQueue.AgentID,+ &i.AgentTaskQueue.IssueID,+ &i.AgentTaskQueue.Status,+ &i.AgentTaskQueue.Priority,+ &i.AgentTaskQueue.DispatchedAt,+ &i.AgentTaskQueue.StartedAt,+ &i.AgentTaskQueue.CompletedAt,+ &i.AgentTaskQueue.Result,+ &i.AgentTaskQueue.Error,+ &i.AgentTaskQueue.CreatedAt,+ &i.AgentTaskQueue.Context,+ &i.AgentTaskQueue.RuntimeID,+ &i.AgentTaskQueue.SessionID,+ &i.AgentTaskQueue.WorkDir,+ &i.AgentTaskQueue.TriggerCommentID,+ &i.AgentTaskQueue.ChatSessionID,+ &i.AgentTaskQueue.AutopilotRunID,+ &i.AgentTaskQueue.Attempt,+ &i.AgentTaskQueue.MaxAttempts,+ &i.AgentTaskQueue.ParentTaskID,+ &i.AgentTaskQueue.FailureReason,+ &i.AgentTaskQueue.TriggerSummary,+ &i.AgentTaskQueue.ForceFreshSession,+ &i.AgentTaskQueue.IsLeaderTask,+ &i.AgentTaskQueue.WaitReason,+ &i.AgentTaskQueue.InitiatorUserID,+ &i.AgentTaskQueue.HandoffNote,+ &i.AgentTaskQueue.PrepareLeaseExpiresAt,+ &i.AgentTaskQueue.SquadID,+ &i.AgentTaskQueue.RuntimeMcpOverlay,+ &i.AgentTaskQueue.EscalationForTaskID,+ &i.AgentTaskQueue.FireAt,+ &i.AgentTaskQueue.OriginatorUserID,+ &i.AgentTaskQueue.RuntimeConnectedApps,+ &i.AgentTaskQueue.CoalescedCommentIds,+ &i.AgentTaskQueue.DeliveredCommentIds,+ &i.AgentTaskQueue.ChatInputTaskID,+ &i.AgentTaskQueue.ChatFinalizeDeferredAt,+ &i.AgentTaskQueue.OriginatorSource,+ &i.AgentTaskQueue.DelegatedFromTaskID,+ &i.AgentTaskQueue.RetryOfTaskID,+ &i.AgentTaskQueue.RerunOfTaskID,+ &i.AgentTaskQueue.RuleVersionID,+ &i.AgentTaskQueue.TriggerEvidenceKind,+ &i.AgentTaskQueue.TriggerEvidenceRefID,+ &i.AgentTaskQueue.AccountableUserID,+ &i.AgentTaskQueue.SessionRolloutMissing,+ &i.AgentTaskQueue.RetiredSessionID,+ &i.AgentTaskQueue.QuickActionsDisabled,+ &i.AgentTaskQueue.RegenerateQuickActionsFor,+ &i.AgentTaskQueue.BranchName,+ &i.AgentTaskQueue.DurableWorkDir,+ &i.AgentTaskQueue.ChannelContextRevision,+ &i.AgentTaskQueue.CommentThreadID,+ &i.AgentTaskQueue.CancelledByType,+ &i.AgentTaskQueue.CancelledByID,+ &i.AgentTaskQueue.CancelledByName,+ &i.AgentTaskQueue.IssueSnapshot,+ &i.AgentTaskQueue.WorkflowStep,+ &i.IssueTitle,+ &i.IssueNumber,+ &i.IssuePrefix,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listUserAgentIDsByRuntime = `-- name: ListUserAgentIDsByRuntime :manySELECT id FROM agentWHERE runtime_id = $1 AND kind = 'user'diff --git a/server/pkg/db/generated/task_usage.sql.go b/server/pkg/db/generated/task_usage.sql.goindex a1bf3cc2ff..c97e898961 100644--- a/server/pkg/db/generated/task_usage.sql.go+++ b/server/pkg/db/generated/task_usage.sql.go@@ -776,6 +776,57 @@ func (q *Queries) ListIssueTaskUsage(ctx context.Context, issueID pgtype.UUID) (return items, nil}+const listTaskUsageByIDs = `-- name: ListTaskUsageByIDs :many+SELECT task_id, provider, model, input_tokens, output_tokens,+ cache_read_tokens, cache_write_tokens, cost_usd_ticks, credits_micros+FROM task_usage+WHERE task_id = ANY($1::uuid[])+ORDER BY task_id, model+`++type ListTaskUsageByIDsRow struct {+ TaskID pgtype.UUID `json:"task_id"`+ Provider string `json:"provider"`+ Model string `json:"model"`+ InputTokens int64 `json:"input_tokens"`+ OutputTokens int64 `json:"output_tokens"`+ CacheReadTokens int64 `json:"cache_read_tokens"`+ CacheWriteTokens int64 `json:"cache_write_tokens"`+ CostUsdTicks pgtype.Int8 `json:"cost_usd_ticks"`+ CreditsMicros pgtype.Int8 `json:"credits_micros"`+}++// Only called with task IDs selected through an authorized issue scope.+func (q *Queries) ListTaskUsageByIDs(ctx context.Context, taskIds []pgtype.UUID) ([]ListTaskUsageByIDsRow, error) {+ rows, err := q.db.Query(ctx, listTaskUsageByIDs, taskIds)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListTaskUsageByIDsRow{}+ for rows.Next() {+ var i ListTaskUsageByIDsRow+ if err := rows.Scan(+ &i.TaskID,+ &i.Provider,+ &i.Model,+ &i.InputTokens,+ &i.OutputTokens,+ &i.CacheReadTokens,+ &i.CacheWriteTokens,+ &i.CostUsdTicks,+ &i.CreditsMicros,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const upsertTaskUsage = `-- name: UpsertTaskUsage :execINSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost_usd_ticks, credits_micros, updated_at)VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now())diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex decbb1e6cc..b0d499307f 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -2680,6 +2680,26 @@ SELECT * FROM agent_task_queueWHERE issue_id = $1ORDER BY created_at DESC;+-- name: ListTasksByIssueSubtree :many+-- UNION deduplicates IDs, so even a corrupt parent cycle terminates.+-- Constrain every recursive step to the authorized root's workspace.+WITH RECURSIVE subtree(id) AS (+ SELECT root.id FROM issue root+ WHERE root.id = sqlc.arg(root_issue_id) AND root.workspace_id = sqlc.arg(workspace_id)+ UNION+ SELECT child.id FROM issue child+ JOIN subtree parent ON child.parent_issue_id = parent.id+ WHERE child.workspace_id = sqlc.arg(workspace_id)+)+SELECT sqlc.embed(atq), i.title AS issue_title, i.number AS issue_number, w.issue_prefix+FROM agent_task_queue atq+JOIN subtree ON subtree.id = atq.issue_id+JOIN issue i ON i.id = atq.issue_id+JOIN workspace w ON w.id = i.workspace_id+WHERE NOT sqlc.arg(active_only)::boolean+ OR atq.status IN ('queued', 'dispatched', 'waiting_local_directory', 'running')+ORDER BY atq.created_at DESC, atq.id;+-- name: UpdateAgentStatus :oneUPDATE agent SET status = $2, updated_at = now()WHERE id = $1diff --git a/server/pkg/db/queries/task_usage.sql b/server/pkg/db/queries/task_usage.sqlindex 7e6a1baffd..636ec8067c 100644--- a/server/pkg/db/queries/task_usage.sql+++ b/server/pkg/db/queries/task_usage.sql@@ -52,6 +52,14 @@ JOIN agent_task_queue atq ON atq.id = tu.task_idWHERE atq.issue_id = $1ORDER BY tu.task_id, tu.model;+-- name: ListTaskUsageByIDs :many+-- Only called with task IDs selected through an authorized issue scope.+SELECT task_id, provider, model, input_tokens, output_tokens,+ cache_read_tokens, cache_write_tokens, cost_usd_ticks, credits_micros+FROM task_usage+WHERE task_id = ANY(sqlc.arg(task_ids)::uuid[])+ORDER BY task_id, model;+-- name: ListAgentTaskUsage :many-- Per-(task, provider, model) usage rows for one agent's explicitly requested-- task history. ListAgentTasks is already access-gated before this query runs;