Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8968: fix(issues): one meaning for "my agents' work" across filters and sidebar (#10310)
Jiayuan Zhang4e457b406b1c
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex f9f9dd1e09..297decdfff 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -457,6 +457,7 @@ import {TeamAppImpactSchema,EMPTY_ISSUE_UNREAD_PAGE,SubscribedIssueIdsSchema,+ InvolvedSquadIdsSchema,IssueInboxReadSchema,InboxItemListSchema,ArchivedInboxPageSchema,@@ -4944,6 +4945,15 @@ export class ApiClient {}) as Squad[];}+ async listInvolvedSquadIds(): Promise<string[]> {+ const raw = await this.fetch<unknown>("/api/squads/involved");+ const parsed = parseWithFallback<{ squad_ids: string[] } | null>(raw, InvolvedSquadIdsSchema, null, {+ endpoint: "GET /api/squads/involved",+ });+ if (!parsed) throw new Error("GET /api/squads/involved returned a malformed body");+ return parsed.squad_ids;+ }+async getSquad(id: string): Promise<Squad> {const raw = await this.fetch<unknown>(`/api/squads/${id}`);return parseWithFallback(raw, SquadSchema, EMPTY_SQUAD, {diff --git a/packages/core/api/involved-squads.test.ts b/packages/core/api/involved-squads.test.tsnew file mode 100644index 0000000000..277cfb921a--- /dev/null+++ b/packages/core/api/involved-squads.test.ts@@ -0,0 +1,30 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from "vitest";+import { ApiClient } from "./client";++afterEach(() => vi.unstubAllGlobals());++const list = (body: unknown) => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json(body)));+ return new ApiClient("https://api.example.test").listInvolvedSquadIds();+};++describe("listInvolvedSquadIds", () => {+ it("returns the ids and tolerates extra fields", async () => {+ await expect(list({ squad_ids: ["s-1", "s-2"], extra: true })).resolves.toEqual(["s-1", "s-2"]);+ });++ it("drops entries that are not ids", async () => {+ await expect(list({ squad_ids: ["s-1", 7, null, "", "s-2"] })).resolves.toEqual(["s-1", "s-2"]);+ });++ // An empty fallback would make "my agents" hide every squad row; failing+ // lets the surface show its retryable error instead.+ it.each([+ ["a missing list", {}],+ ["a non-array list", { squad_ids: "s-1" }],+ ["a null body", null],+ ])("fails for %s", async (_name, body) => {+ await expect(list(body)).rejects.toThrow("malformed");+ });+});diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 7f55057f00..5c79be68fb 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -2908,6 +2908,17 @@ export const SubscribedIssueIdsSchema = z}).loose();+// The squads behind the viewer's "my agents" relation (`/api/squads/involved`+// GET). Same rules as `SubscribedIssueIdsSchema`: an empty set would hide+// every squad row under the filter, so a body without the list fails.+export const InvolvedSquadIdsSchema = z+ .object({+ squad_ids: z+ .array(z.unknown())+ .transform((ids) => ids.filter((id): id is string => typeof id === "string" && id.length > 0)),+ })+ .loose();+// Inbox items (`/api/inbox` and `/api/inbox/archived` GET).// Lenient per the usual rules: `severity` / `type` / `recipient_type` stay// `z.string()` so a notification kind this client doesn't know yet stilldiff --git a/packages/core/issues/cache-coordinator.test.ts b/packages/core/issues/cache-coordinator.test.tsindex b3421eec46..ea4fb3135a 100644--- a/packages/core/issues/cache-coordinator.test.ts+++ b/packages/core/issues/cache-coordinator.test.ts@@ -268,7 +268,12 @@ describe("applyIssueChange", () => {});it("patches and rolls back loaded sidebar rows", () => {- const sidebarKey = issueKeys.sidebar(WS_ID, "project:p1", { project_id: "p1" }, 5);+ const sidebarKey = issueKeys.sidebar(+ WS_ID,+ "project:p1",+ { table: { scope: { kind: "project", project_id: "p1" }, filters: {}, sort: { field: "updated_at", direction: "desc" } } },+ 5,+ );const snapshot: ListIssuesResponse = { issues: [issue()], total: 1 };qc.setQueryData(sidebarKey, snapshot);diff --git a/packages/core/issues/queries.test.ts b/packages/core/issues/queries.test.tsindex 82929734dc..aeaef5a78c 100644--- a/packages/core/issues/queries.test.ts+++ b/packages/core/issues/queries.test.ts@@ -750,22 +750,4 @@ describe("sidebarIssuesOptions", () => {{ limit: 20, cursor: "100" },]);});-- it("walks list pages past the server's 100-row cap", async () => {- const listIssues = vi.fn(async (params?: ListIssuesParams): Promise<ListIssuesResponse> => {- const offset = params?.offset ?? 0;- return { issues: issues.slice(offset, offset + Math.min(params?.limit ?? 100, 100)), total: issues.length };- });- installFakeApi(listIssues);-- const result = await new QueryClient().fetchQuery(- sidebarIssuesOptions(WS_ID, "builtin:my_issues", { assignee_id: "u1" }, 130),- );-- expect(result.issues.map((issue) => issue.id)).toEqual(issues.map((issue) => issue.id));- expect(listIssues.mock.calls.map(([params]) => [params?.limit, params?.offset])).toEqual([- [100, 0],- [30, 100],- ]);- });});diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.tsindex aca5f28534..d73c8f4caa 100644--- a/packages/core/issues/queries.ts+++ b/packages/core/issues/queries.ts@@ -469,7 +469,7 @@ export function projectGanttIssuesOptions(});}-/** Both list endpoints cap a page here, so a longer sidebar list is fetched in pages. */+/** The table endpoint caps a page here, so a longer sidebar list is fetched in pages. */const SIDEBAR_MAX_PAGE = 100;async function listSidebarTableIssues(query: IssueTableQuerySpec, limit: number): Promise<ListIssuesResponse> {@@ -492,22 +492,6 @@ async function listSidebarTableIssues(query: IssueTableQuerySpec, limit: number)return { issues, total };}-async function listSidebarIssues(params: ListIssuesParams, limit: number): Promise<ListIssuesResponse> {- const issues: Issue[] = [];- let total = 0;- do {- const page = await api.listIssues({- ...params,- limit: Math.min(limit - issues.length, SIDEBAR_MAX_PAGE),- offset: issues.length,- });- issues.push(...page.issues);- total = page.total;- if (page.issues.length === 0) break;- } while (issues.length < limit && issues.length < total);- return { issues, total };-}-/** The first `limit` issues of a sidebar list, with the filtered total. */export function sidebarIssuesOptions(wsId: string,@@ -517,10 +501,7 @@ export function sidebarIssuesOptions() {return queryOptions({queryKey: issueKeys.sidebar(wsId, source, request, limit),- queryFn: () =>- "table" in request- ? listSidebarTableIssues(request.table, limit)- : listSidebarIssues(request, limit),+ queryFn: () => listSidebarTableIssues(request.table, limit),});}diff --git a/packages/core/issues/sidebar-list.test.ts b/packages/core/issues/sidebar-list.test.tsindex 63387dc4b7..10fc51eaf7 100644--- a/packages/core/issues/sidebar-list.test.ts+++ b/packages/core/issues/sidebar-list.test.ts@@ -26,45 +26,31 @@ const STATUSES = [describe("projectSidebarRequest", () => {it("leaves out finished statuses and sorts by update time by default", () => {expect(projectSidebarRequest("p1", DEFAULT_SIDEBAR_ISSUE_SETTINGS, STATUSES, "u1")).toEqual({- project_id: "p1",- statuses: ["backlog", "todo", "in_progress", "merged"],- sort_by: "updated_at",- sort_direction: "desc",- });- });-- it("maps the assignee and sub-issue settings onto server filters", () => {- const settings: SidebarIssueSettings = {- ...DEFAULT_SIDEBAR_ISSUE_SETTINGS,- hiddenStatuses: [],- assignee: "my_agents",- showSubIssues: false,- };- expect(projectSidebarRequest("p1", settings, STATUSES, "u1")).toEqual({- project_id: "p1",- involves_user_id: "u1",- top_level_only: true,- sort_by: "updated_at",- sort_direction: "desc",- });- });-- it("lists me and my agents through the table query, which can OR the two", () => {- const settings: SidebarIssueSettings = { ...DEFAULT_SIDEBAR_ISSUE_SETTINGS, assignee: "me_and_my_agents" };- expect(projectSidebarRequest("p1", settings, STATUSES, "u1")).toEqual({table: {scope: { kind: "project", project_id: "p1" },- filters: {- statuses: ["backlog", "todo", "in_progress", "merged"],- relations: ["assigned", "my_agents"],- include_sub_issues: true,- },+ filters: { statuses: ["backlog", "todo", "in_progress", "merged"], include_sub_issues: true },sort: { field: "updated_at", direction: "desc" },},});+ });++ it("maps every assignee setting onto table relations", () => {+ const relations = (assignee: SidebarIssueSettings["assignee"]) =>+ projectSidebarRequest("p1", { ...DEFAULT_SIDEBAR_ISSUE_SETTINGS, assignee }, STATUSES, "u1")?.table.filters+ .relations;+ expect(relations("anyone")).toBeUndefined();+ expect(relations("me")).toEqual(["assigned"]);+ expect(relations("my_agents")).toEqual(["my_agents"]);+ expect(relations("me_and_my_agents")).toEqual(["assigned", "my_agents"]);+ const settings: SidebarIssueSettings = { ...DEFAULT_SIDEBAR_ISSUE_SETTINGS, assignee: "me" };expect(projectSidebarRequest("p1", settings, STATUSES, undefined)).toBeNull();});+ it("maps the sub-issue setting", () => {+ const settings: SidebarIssueSettings = { ...DEFAULT_SIDEBAR_ISSUE_SETTINGS, hiddenStatuses: [], showSubIssues: false };+ expect(projectSidebarRequest("p1", settings, STATUSES, "u1")?.table.filters).toEqual({ include_sub_issues: false });+ });+it("lists nothing when every status is hidden", () => {const settings = { ...DEFAULT_SIDEBAR_ISSUE_SETTINGS, hiddenStatuses: STATUSES.map((s) => s.key) };expect(shownSidebarStatuses(settings, STATUSES)).toEqual([]);@@ -172,17 +158,13 @@ describe("builtinSidebarRequest", () => {expect(request("my_agents", "assigned")?.scope).toEqual({ kind: "my", relation: "involved" });});- it("maps the assignee setting and lists nothing when every status is hidden", () => {- const mine = { ...DEFAULT_SIDEBAR_ISSUE_SETTINGS, hiddenStatuses: [], assignee: "my_agents" as const };- expect(builtinSidebarRequest("all_issues", "assigned", mine, STATUSES)?.table.filters).toEqual({- relations: ["my_agents"],- include_sub_issues: true,- });- const both = { ...mine, assignee: "me_and_my_agents" as const };- expect(builtinSidebarRequest("all_issues", "assigned", both, STATUSES)?.table.filters).toEqual({- relations: ["assigned", "my_agents"],- include_sub_issues: true,- });+ it("ignores the project-only assignee setting and lists nothing when every status is hidden", () => {+ for (const assignee of ["me", "my_agents", "me_and_my_agents"] as const) {+ const settings = { ...DEFAULT_SIDEBAR_ISSUE_SETTINGS, hiddenStatuses: [], assignee };+ expect(builtinSidebarRequest("my_agents", "assigned", settings, STATUSES)?.table.filters).toEqual({+ include_sub_issues: true,+ });+ }const none = { ...DEFAULT_SIDEBAR_ISSUE_SETTINGS, hiddenStatuses: STATUSES.map((s) => s.key) };expect(builtinSidebarRequest("all_issues", "assigned", none, STATUSES)).toBeNull();});diff --git a/packages/core/issues/sidebar-list.ts b/packages/core/issues/sidebar-list.tsindex 1141b1f01b..7bdaf1a20f 100644--- a/packages/core/issues/sidebar-list.ts+++ b/packages/core/issues/sidebar-list.ts@@ -7,7 +7,6 @@ import type {IssueTableRelation,IssueTableScope,IssueTableSortField,- ListIssuesParams,Project,} from "../types";import { assigneeTypesForActorKind } from "./surface/scope";@@ -61,30 +60,17 @@ export function projectSidebarRequest(const shown = shownSidebarStatuses(settings, statuses);if (shown.length === 0) return null;if (settings.assignee !== "anyone" && !userId) return null;- const statusFilter = shown.length < statuses.length ? { statuses: shown } : {};- // The list endpoint cannot OR the user with their agents: `involves_user_id`- // never matches issues assigned to the user directly.- if (settings.assignee === "me_and_my_agents") {- return {- table: {- scope: { kind: "project", project_id: projectId },- filters: {- ...statusFilter,- relations: ASSIGNEE_RELATIONS.me_and_my_agents,- include_sub_issues: settings.showSubIssues,- },- sort: { field: settings.sortBy, direction: settings.sortDirection },- },- };- }+ const relations = ASSIGNEE_RELATIONS[settings.assignee] ?? [];return {- project_id: projectId,- ...statusFilter,- ...(settings.assignee === "me" ? { assignee_id: userId } : {}),- ...(settings.assignee === "my_agents" ? { involves_user_id: userId } : {}),- ...(settings.showSubIssues ? {} : { top_level_only: true }),- sort_by: settings.sortBy,- sort_direction: settings.sortDirection,+ table: {+ scope: { kind: "project", project_id: projectId },+ filters: {+ ...(shown.length < statuses.length ? { statuses: shown } : {}),+ ...(relations.length > 0 ? { relations } : {}),+ include_sub_issues: settings.showSubIssues,+ },+ sort: { field: settings.sortBy, direction: settings.sortDirection },+ },};}@@ -103,16 +89,11 @@ const VIEW_SORTS = new Set<string>([type SidebarViewFields = Pick<IssueView, "query" | "display" | "scope_variant"> &Partial<Pick<IssueView, "scope_type" | "scope_id">>;-/** A sidebar list read through the table query, which can express every view filter. */-export interface SidebarTableRequest {+/** A sidebar list, read through the table query, which can express every view filter. */+export interface SidebarIssuesRequest {table: IssueTableQuerySpec;}-export type SidebarIssuesRequest = ListIssuesParams | SidebarTableRequest;--export const isSidebarTableRequest = (request: SidebarIssuesRequest): request is SidebarTableRequest =>- "table" in request;-function viewTableScope(view: SidebarViewFields): IssueTableScope | null {const assigneeTypes = assigneeTypesForActorKind(view.scope_variant === "members" || view.scope_variant === "agents" ? view.scope_variant : undefined,@@ -157,7 +138,7 @@ export function viewSidebarRequest(view: SidebarViewFields,today: string,unreadIssueIds: readonly string[] = [],-): SidebarTableRequest | null {+): SidebarIssuesRequest | null {const scope = viewTableScope(view);if (!scope) return null;const { raw } = baselineFromQuery(view.query);@@ -203,25 +184,24 @@ export function viewSidebarRequest(/*** The request for an expanded built-in view: the page's scope, listed with- * the same sidebar settings as an expanded project. `null` when the settings- * leave nothing to list.+ * the same status, sub-issue and ordering settings as an expanded project.+ * The assignee setting is for projects only: the scope already says whose+ * issues a built-in lists. `null` when the settings leave nothing to list.*/export function builtinSidebarRequest(builtin: Exclude<BuiltinViewKey, "unread">,myRelation: MyIssuesRelation,settings: SidebarIssueSettings,statuses: readonly StatusRef[],-): SidebarTableRequest | null {+): SidebarIssuesRequest | null {const shown = shownSidebarStatuses(settings, statuses);if (shown.length === 0) return null;const relation = builtin === "my_agents" ? "involved" : myRelation === "all" ? "any" : myRelation;- const relations = ASSIGNEE_RELATIONS[settings.assignee] ?? [];return {table: {scope: builtin === "all_issues" ? { kind: "workspace" } : { kind: "my", relation },filters: {...(shown.length < statuses.length ? { statuses: shown } : {}),- ...(relations.length > 0 ? { relations } : {}),include_sub_issues: settings.showSubIssues,},sort: { field: settings.sortBy, direction: settings.sortDirection },diff --git a/packages/core/issues/ws-updaters.test.ts b/packages/core/issues/ws-updaters.test.tsindex 5c3bb02f34..5d42f3b531 100644--- a/packages/core/issues/ws-updaters.test.ts+++ b/packages/core/issues/ws-updaters.test.ts@@ -1155,10 +1155,13 @@ describe("project gantt cache invalidation", () => {// only the lists it can reorder or move the issue across.describe("sidebar issue lists", () => {const PROJECT_ID = "project-1";- const params = { project_id: PROJECT_ID, sort_by: "updated_at", sort_direction: "desc" } as const;- const ownKey = issueKeys.sidebar(WS_ID, `project:${PROJECT_ID}`, params, 5);- const otherKey = issueKeys.sidebar(WS_ID, "project:project-9", { project_id: "project-9" }, 5);- const viewKey = issueKeys.sidebar(WS_ID, "view:view-1", {}, 5);+ const sort = { field: "updated_at", direction: "desc" } as const;+ const projectRequest = (projectId: string) => ({+ table: { scope: { kind: "project", project_id: projectId }, filters: {}, sort },+ }) as const;+ const ownKey = issueKeys.sidebar(WS_ID, `project:${PROJECT_ID}`, projectRequest(PROJECT_ID), 5);+ const otherKey = issueKeys.sidebar(WS_ID, "project:project-9", projectRequest("project-9"), 5);+ const viewKey = issueKeys.sidebar(WS_ID, "view:view-1", { table: { scope: { kind: "workspace" }, filters: {}, sort } }, 5);const builtinKey = issueKeys.sidebar(WS_ID,"builtin:all_issues",diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsxindex 8b2319b7da..c30afc990a 100644--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx@@ -679,7 +679,7 @@ describe("useRealtimeSync — Table server membership invalidation", () => {// A saved view's sidebar preview filters on working_only server-side.affected.push(issueKeys.sidebar("ws-1", "view:v1", { table: { ...spec, filters: { working_only: true } } }, 5));untouched.push(issueKeys.sidebar("ws-1", "view:v2", { table: spec }, 5));- untouched.push(issueKeys.sidebar("ws-1", "project:p1", { project_id: "p1" }, 5));+ untouched.push(issueKeys.sidebar("ws-1", "project:p1", { table: { ...spec, scope: { kind: "project", project_id: "p1" } } }, 5));for (const key of [...untouched, ...affected]) qc.setQueryData(key, []);emit("task:completed");await vi.advanceTimersByTimeAsync(1_000);diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex c34578683c..4a944e0c50 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -11,7 +11,7 @@ import { clearWorkspaceStorage } from "../platform/storage-cleanup";import { defaultStorage } from "../platform/storage";import { getCurrentWsId, getCurrentSlug } from "../platform/workspace-storage";import { issueKeys } from "../issues/queries";-import { isSidebarTableRequest, type SidebarIssuesRequest } from "../issues/sidebar-list";+import type { SidebarIssuesRequest } from "../issues/sidebar-list";import { refreshIssueUnread } from "../issues/unread";import { refreshSubscribedIssues, subscribedIssueKeys } from "../issues/subscribed";import { projectKeys } from "../projects/queries";@@ -743,7 +743,7 @@ async function refreshWorkingAgentQueries(qc: QueryClient, wsId: string): PromisqueryKey: issueKeys.sidebarAll(wsId),predicate: ({ queryKey }) => {const request = queryKey[4] as SidebarIssuesRequest | undefined;- return !!request && isSidebarTableRequest(request) && request.table.filters.working_only === true;+ return request?.table.filters.working_only === true;},},];diff --git a/packages/core/workspace/queries.ts b/packages/core/workspace/queries.tsindex 4c7de686c6..82a99a6695 100644--- a/packages/core/workspace/queries.ts+++ b/packages/core/workspace/queries.ts@@ -13,6 +13,8 @@ export const workspaceKeys = {agent: (wsId: string, agentId: string) =>["workspaces", wsId, "agents", "detail", agentId] as const,squads: (wsId: string) => ["workspaces", wsId, "squads"] as const,+ /** Under `squads` so membership changes refetch it. */+ involvedSquads: (wsId: string) => ["workspaces", wsId, "squads", "involved"] as const,// Per-squad member status. Lives under the workspace key tree so// workspace switches naturally drop the cache, and so a broad// `["workspaces", wsId, "squads"]` invalidation covers it.@@ -105,6 +107,18 @@ export function squadListOptions(wsId: string) {});}+/**+ * The squads behind the viewer's "my agents" relation, for evaluating it on+ * rows the client filters itself.+ */+export function involvedSquadIdsOptions(wsId: string) {+ return queryOptions({+ queryKey: workspaceKeys.involvedSquads(wsId),+ queryFn: () => api.listInvolvedSquadIds(),+ enabled: !!wsId,+ });+}+// Per-squad members status snapshot. The freshness signal is the WS task /// agent / runtime invalidation wired in use-realtime-sync (which broadly// invalidates `["workspaces", wsId, "squads"]`); the staleTime is adiff --git a/packages/views/issues/surface/use-issue-surface-controller.test.tsx b/packages/views/issues/surface/use-issue-surface-controller.test.tsxindex 22e677e9f8..e37425c558 100644--- a/packages/views/issues/surface/use-issue-surface-controller.test.tsx+++ b/packages/views/issues/surface/use-issue-surface-controller.test.tsx@@ -166,6 +166,7 @@ describe("useIssueSurfaceController", () => {let listIssueTableFacets: ReturnType<typeof vi.fn>;let listSubscribedIssueIds: ReturnType<typeof vi.fn<() => Promise<string[]>>>;let listAgents: ReturnType<typeof vi.fn<() => Promise<Agent[]>>>;+ let listInvolvedSquadIds: ReturnType<typeof vi.fn<() => Promise<string[]>>>;// Every row the current fixture holds, kept outside the mocked list endpoint// so the working-agents facet stand-in can read it without registering a// call that Table-isolation tests assert never happens.@@ -193,6 +194,7 @@ describe("useIssueSurfaceController", () => {listIssueUnread = vi.fn(() => Promise.resolve([]));listSubscribedIssueIds = vi.fn(() => never<string[]>());listAgents = vi.fn(() => Promise.resolve([] satisfies Agent[]));+ listInvolvedSquadIds = vi.fn(() => Promise.resolve([]));setApiInstance({// The board pages by category, so every surface stub answers the catalog// read. Empty is the real shape for a workspace with no custom statuses:@@ -209,6 +211,7 @@ describe("useIssueSurfaceController", () => {listIssueUnread,getChildIssueProgress: vi.fn(() => never()),listAgents,+ listInvolvedSquadIds,listSubscribedIssueIds,} as unknown as ApiClient);pruneIssueSurfaceViewStates([]);@@ -2026,6 +2029,43 @@ describe("useIssueSurfaceController", () => {expect(result.current.filteredGanttIssues.map((issue) => issue.id)).toEqual(["gantt-open"]);});+ it("holds loading while the squads behind \"my agents\" load, then keeps only the viewer's", async () => {+ const squadRow = (id: string, squad: string) =>+ makeIssue({+ id,+ status: "in_progress",+ assignee_type: "squad",+ assignee_id: squad,+ start_date: "2026-01-01",+ due_date: "2026-01-05",+ });+ let finish!: (ids: string[]) => void;+ listInvolvedSquadIds.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));+ mockGanttIssues([squadRow("my-squad-row", "squad-1"), squadRow("their-squad-row", "squad-2")]);+ const store = getIssueSurfaceViewStore("project:p1");+ act(() => {+ store.getState().setViewMode("gantt");+ store.getState().toggleRelationFilter("my_agents");+ });+ const { result } = renderHook(+ () => useIssueSurfaceController({ scope: { type: "project", projectId: "p1" }, modes: ["gantt"] }),+ { wrapper: makeWrapper(qc, "project:p1") },+ );++ await waitFor(() => expect(result.current.ganttIssues).toHaveLength(2));+ await waitFor(() => expect(listInvolvedSquadIds).toHaveBeenCalled());+ expect(result.current.isLoading).toBe(true);++ await act(async () => finish(["squad-1"]));+ await waitFor(() => expect(result.current.isLoading).toBe(false));+ expect(result.current.filteredGanttIssues.map((issue) => issue.id)).toEqual(["my-squad-row"]);++ act(() => store.getState().setFilterNegated("relation", true));+ await waitFor(() =>+ expect(result.current.filteredGanttIssues.map((issue) => issue.id)).toEqual(["their-squad-row"]),+ );+ });+it("offers a retry when the agents behind \"my agents\" fail", async () => {listAgents.mockRejectedValueOnce(new Error("offline"));listSubscribedIssueIds.mockResolvedValue([]);diff --git a/packages/views/issues/surface/use-issue-surface-controller.ts b/packages/views/issues/surface/use-issue-surface-controller.tsindex 656cb45b18..2a0866f7d5 100644--- a/packages/views/issues/surface/use-issue-surface-controller.ts+++ b/packages/views/issues/surface/use-issue-surface-controller.ts@@ -58,7 +58,7 @@ import {} from "@multica/core/issues/stores/view-store";import { useViewStore } from "@multica/core/issues/stores/view-store-context";import { useAuthStore } from "@multica/core/auth";-import { agentListOptions } from "@multica/core/workspace/queries";+import { agentListOptions, involvedSquadIdsOptions } from "@multica/core/workspace/queries";import { subscribedIssueIdsOptions } from "@multica/core/issues/subscribed";import { useShallow } from "zustand/react/shallow";import type { IssueFilters, IssueRelationContext } from "../utils/filter";@@ -340,6 +340,11 @@ export function useIssueSurfaceController({enabled: usesMyAgents,});const agents = agentsQuery.data;+ const involvedSquadIdsQuery = useQuery({+ ...involvedSquadIdsOptions(wsId),+ enabled: usesMyAgents,+ });+ const involvedSquadIds = involvedSquadIdsQuery.data;const subscribedIssueIdsQuery = useQuery({...subscribedIssueIdsOptions(wsId),enabled: usesSubscribed,@@ -347,6 +352,7 @@ export function useIssueSurfaceController({const subscribedIssueIds = subscribedIssueIdsQuery.data;const relationSources = [usesMyAgents && agentsQuery,+ usesMyAgents && involvedSquadIdsQuery,usesSubscribed && subscribedIssueIdsQuery,];const relationContext = useMemo<IssueRelationContext | undefined>(() => {@@ -360,11 +366,12 @@ export function useIssueSurfaceController({),}: {}),+ ...(usesMyAgents && involvedSquadIds ? { mySquadIds: new Set(involvedSquadIds) } : {}),...(usesSubscribed && subscribedIssueIds? { subscribedIssueIds: new Set(subscribedIssueIds) }: {}),};- }, [agents, subscribedIssueIds, userId, usesMyAgents, usesSubscribed]);+ }, [agents, involvedSquadIds, subscribedIssueIds, userId, usesMyAgents, usesSubscribed]);const allowedModes = useMemo(() => new Set<IssueSurfaceMode>(modes), [modes]);const fallbackMode = modes[0] ?? "list";diff --git a/packages/views/issues/surface/use-issue-surface-data.ts b/packages/views/issues/surface/use-issue-surface-data.tsindex 6dc171d05f..f10ebdaae8 100644--- a/packages/views/issues/surface/use-issue-surface-data.ts+++ b/packages/views/issues/surface/use-issue-surface-data.ts@@ -167,8 +167,8 @@ export function useIssueSurfaceData({labelFilters: string[];relationFilters: IssueRelationFilter[];relationContext: IssueRelationContext | undefined;- /** What the active relation values read: the viewer's agents for- * "my_agents", their subscriptions for "subscribed". */+ /** What the active relation values read: the viewer's agents and squads+ * for "my_agents", their subscriptions for "subscribed". */relationSources: readonly (FilterDependencySource | false)[];dueDateFilters: DueDateFilter[];/** The scoped, pruned rule tree. */diff --git a/packages/views/issues/utils/filter.test.ts b/packages/views/issues/utils/filter.test.tsindex 6d8237328e..166c4671e2 100644--- a/packages/views/issues/utils/filter.test.ts+++ b/packages/views/issues/utils/filter.test.ts@@ -829,15 +829,45 @@ describe("relation filters", () => {).toEqual(["2", "3", "4"]);});- it("answers subscribed without the viewer's agents, leaving only my_agents open", () => {+ describe("my_agents with squads", () => {+ const mine = makeIssue({ id: "mine", assignee_type: "squad", assignee_id: "my-squad", priority: "medium" });+ const theirs = makeIssue({ id: "theirs", assignee_type: "squad", assignee_id: "their-squad", priority: "medium" });+ const agent = makeIssue({ id: "agent", assignee_type: "agent", assignee_id: "a-1", priority: "medium" });+ const viewer = { userId: "u-1", myAgentIds: new Set(["a-1"]), mySquadIds: new Set(["my-squad"]) };+ const squadIds = (filters: Partial<IssueFilters>) =>+ filterIssues([mine, theirs, agent], { ...NO_FILTER, relationContext: viewer, ...filters }).map((i) => i.id);++ it("keeps the viewer's squads and drops the others", () => {+ expect(squadIds({ relationFilters: ["my_agents"] })).toEqual(["mine", "agent"]);+ });++ it("negated, keeps only the other squads", () => {+ expect(squadIds({ relationFilters: ["my_agents"], negatedFilters: ["relation"] })).toEqual(["theirs"]);+ });++ it("keeps a squad row an OR sibling does not match", () => {+ const advancedFilter = createFilterGroup("any", [+ createFilterCondition("relation", ["my_agents"]),+ createFilterCondition("priority", ["urgent"]),+ ]);+ expect(squadIds({ advancedFilter })).toEqual(["mine", "agent"]);+ });++ it("leaves squad rows to the server until the viewer's squads load", () => {+ const agentsOnly = { userId: "u-1", myAgentIds: new Set(["a-1"]) };+ expect(squadIds({ relationContext: agentsOnly, relationFilters: ["my_agents"] })).toEqual([+ "mine",+ "theirs",+ "agent",+ ]);+ });+ });++ it("answers subscribed without the viewer's agents, leaving only agent rows of my_agents open", () => {const subscriptionsOnly = { userId: "u-1", subscribedIssueIds: new Set(["3"]) };expect(ids({ relationContext: subscriptionsOnly, relationFilters: ["subscribed"] })).toEqual(["3"]);- expect(ids({ relationContext: subscriptionsOnly, relationFilters: ["my_agents"] })).toEqual([- "1",- "2",- "3",- "4",- ]);+ // Member and unassigned rows are never an agent's work.+ expect(ids({ relationContext: subscriptionsOnly, relationFilters: ["my_agents"] })).toEqual(["2"]);});});diff --git a/packages/views/issues/utils/filter.ts b/packages/views/issues/utils/filter.tsindex 59f8427053..a72e9e21d9 100644--- a/packages/views/issues/utils/filter.ts+++ b/packages/views/issues/utils/filter.ts@@ -114,8 +114,12 @@ export interface IssueFilterContext {export interface IssueRelationContext {userId: string;/** Agents the viewer owns. Loaded only while a filter tests "my_agents";- * without it that relation is left to the server. */+ * without it that relation is left to the server for agent rows. */myAgentIds?: ReadonlySet<string>;+ /** Squads the viewer or one of their agents is in, the other half of+ * "my_agents"; without it that relation is left to the server for squad+ * rows. */+ mySquadIds?: ReadonlySet<string>;/** Issues the viewer subscribes to. Loaded only while a filter tests the* relation; without it "subscribed" is left to the server. */subscribedIssueIds?: ReadonlySet<string>;@@ -399,13 +403,17 @@ function issueMatchesRelation(return issue.assignee_type === "member" && issue.assignee_id === context.userId;case "created":return issue.creator_type === "member" && issue.creator_id === context.userId;- case "my_agents":- if (!context.myAgentIds) return undefined;- return (- issue.assignee_type === "agent" &&- !!issue.assignee_id &&- context.myAgentIds.has(issue.assignee_id)- );+ case "my_agents": {+ const ids =+ issue.assignee_type === "agent"+ ? context.myAgentIds+ : issue.assignee_type === "squad"+ ? context.mySquadIds+ : null;+ if (ids === null) return false;+ if (!ids) return undefined;+ return !!issue.assignee_id && ids.has(issue.assignee_id);+ }}}diff --git a/packages/views/layout/panels/sidebar-settings.tsx b/packages/views/layout/panels/sidebar-settings.tsxindex 526c463d9e..46f5b06e79 100644--- a/packages/views/layout/panels/sidebar-settings.tsx+++ b/packages/views/layout/panels/sidebar-settings.tsx@@ -228,15 +228,18 @@ function ProjectIssuesGroup({))}</div></div>- <Field label={t(($) => $.panels.work.settings_assignee)}>- <SortSelect- label={t(($) => $.panels.work.settings_assignee)}- value={settings.assignee}- options={assigneeOptions}- onChange={(assignee) => update({ assignee })}- className="w-44"- />- </Field>+ <div className="space-y-1">+ <Field label={t(($) => $.panels.work.settings_assignee)}>+ <SortSelect+ label={t(($) => $.panels.work.settings_assignee)}+ value={settings.assignee}+ options={assigneeOptions}+ onChange={(assignee) => update({ assignee })}+ className="w-44"+ />+ </Field>+ <p className="text-caption text-muted-foreground">{t(($) => $.panels.work.assignee_projects_only)}</p>+ </div><SwitchFieldlabel={ti(($) => $.display.show_sub_issues)}checked={settings.showSubIssues}diff --git a/packages/views/layout/panels/sidebar-tree.test.tsx b/packages/views/layout/panels/sidebar-tree.test.tsxindex 0e3438e84f..874dea56d8 100644--- a/packages/views/layout/panels/sidebar-tree.test.tsx+++ b/packages/views/layout/panels/sidebar-tree.test.tsx@@ -5,8 +5,9 @@ import { describe, expect, it, vi } from "vitest";import { agentTaskSnapshotOptions } from "@multica/core/agents";import { buildIssueStatusCatalog } from "@multica/core/issue-statuses/queries";import { issueKeys } from "@multica/core/issues/queries";+import type { SidebarIssuesRequest } from "@multica/core/issues/sidebar-list";import { issueUnreadOptions } from "@multica/core/issues/unread";-import type { AgentTask, Issue, IssueUnread, ListIssuesParams } from "@multica/core/types";+import type { AgentTask, Issue, IssueUnread } from "@multica/core/types";import { renderWithI18n } from "../../test/i18n";import { IssueContextMenuProvider } from "../../issues/actions";import { SidebarIssueList, TreeRow } from "./sidebar-tree";@@ -70,7 +71,13 @@ vi.mock("@multica/core/paths", async (importOriginal) => {});const SOURCE = "project:p1";-const PARAMS: ListIssuesParams = { project_id: "p1", sort_by: "updated_at", sort_direction: "desc" };+const PARAMS: SidebarIssuesRequest = {+ table: {+ scope: { kind: "project", project_id: "p1" },+ filters: {},+ sort: { field: "updated_at", direction: "desc" },+ },+};const issues = (count: number): Issue[] =>Array.from({ length: count }, (_, i) => ({ id: `issue-${i + 1}`, title: `Issue ${i + 1}`, status: "todo" }) as Issue);@@ -82,7 +89,7 @@ function renderList({onCollapse = vi.fn(),}: {total?: number;- params?: ListIssuesParams | null;+ params?: SidebarIssuesRequest | null;tasks?: Partial<AgentTask>[];unread?: IssueUnread[];onCollapse?: () => void;diff --git a/packages/views/layout/panels/sidebar-tree.tsx b/packages/views/layout/panels/sidebar-tree.tsxindex 107e8a4414..e3245103b6 100644--- a/packages/views/layout/panels/sidebar-tree.tsx+++ b/packages/views/layout/panels/sidebar-tree.tsx@@ -17,7 +17,7 @@ import { useSidebarTreeStore } from "@multica/core/issues/stores/sidebar-tree-stimport { issueUnreadTarget, useIssueUnread } from "@multica/core/issues/unread";import { useWorkspacePaths } from "@multica/core/paths";import { useActorName } from "@multica/core/workspace/hooks";-import type { AgentTask, Issue, IssueUnread, ListIssuesParams } from "@multica/core/types";+import type { AgentTask, Issue, IssueUnread } from "@multica/core/types";import { AppLink } from "../../navigation";import { AgentAvatarStack } from "../../agents/components/agent-avatar-stack";import { StatusIcon } from "../../issues/components/status-icon";@@ -176,7 +176,9 @@ export function issueRowMenuOpenClass(active: boolean) {return active ? undefined : "data-popup-open:bg-surface-hover data-popup-open:text-foreground";}-const EMPTY_PARAMS: ListIssuesParams = {};+const EMPTY_PARAMS: SidebarIssuesRequest = {+ table: { scope: { kind: "workspace" }, filters: {}, sort: { field: "position", direction: "asc" } },+};const EMPTY_ISSUES: Issue[] = [];/**diff --git a/packages/views/layout/panels/work-panel.test.tsx b/packages/views/layout/panels/work-panel.test.tsxindex c1af17cf33..0e034e6ffc 100644--- a/packages/views/layout/panels/work-panel.test.tsx+++ b/packages/views/layout/panels/work-panel.test.tsx@@ -15,12 +15,12 @@ import { useSidebarTreeStore } from "@multica/core/issues/stores/sidebar-tree-stimport { spaceForPath } from "@multica/core/paths";import { pinListOptions } from "@multica/core/pins/queries";import { projectListOptions } from "@multica/core/projects/queries";-import type { Issue, IssueTableRowsResponse, PinnedItem, Project } from "@multica/core/types";+import type { Issue, IssueTableRowsRequest, IssueTableRowsResponse, PinnedItem, Project } from "@multica/core/types";import { renderWithI18n } from "../../test/i18n";import { NavigationProvider, type NavigationAdapter } from "../../navigation";import { KeptRowsRelease, WorkPanel } from "./work-panel";-const apiMock = vi.hoisted(() => ({ listIssueTableRows: vi.fn(), listIssues: vi.fn(), getIssue: vi.fn() }));+const apiMock = vi.hoisted(() => ({ listIssueTableRows: vi.fn(), getIssue: vi.fn() }));const actions = vi.hoisted(() => ({sidebar: {items: [@@ -221,7 +221,6 @@ beforeEach(() => {total: 2,next_cursor: null,} as unknown as IssueTableRowsResponse);- apiMock.listIssues.mockResolvedValue({ issues: [ISSUE, OTHER], total: 2 });// The issue page never finishes loading, so the panel cannot lean on it.apiMock.getIssue.mockReturnValue(new Promise<Issue>(() => {}));});@@ -431,10 +430,10 @@ describe("WorkPanel and the open issue's project", () => {it("lists an issue lit in a view under its project once the project is expanded", async () => {// The open issue is on the project's second page.- apiMock.listIssues.mockImplementation(async ({ offset }: { offset: number }) => ({- issues: offset ? [] : [OTHER],- total: 2,- }));+ const builtinRows = await apiMock.listIssueTableRows();+ apiMock.listIssueTableRows.mockImplementation(async ({ query }: IssueTableRowsRequest) =>+ query.scope.kind === "project" ? { rows: [{ issue: OTHER }], total: 2, next_cursor: null } : builtinRows,+ );const qc = renderPanel("/acme/my-issues", [], [PROJECT]);await openInProject(qc);const inMyIssues = await waitFor(() => {@@ -458,7 +457,7 @@ describe("WorkPanel and the open issue's project", () => {it("lists the open issue last under its expanded project when no page has it", async () => {useSidebarTreeStore.setState({ expanded: [PROJECT_SOURCE] });- apiMock.listIssues.mockResolvedValue({ issues: [OTHER], total: 1 });+ apiMock.listIssueTableRows.mockResolvedValue({ rows: [{ issue: OTHER }], total: 1, next_cursor: null });const qc = renderPanel(`/acme/issues/${ISSUE.id}`, [], [PROJECT]);await openInProject(qc);diff --git a/packages/views/layout/panels/work-tree.catalog.test.tsx b/packages/views/layout/panels/work-tree.catalog.test.tsxindex 94188fab46..fe4778e1c4 100644--- a/packages/views/layout/panels/work-tree.catalog.test.tsx+++ b/packages/views/layout/panels/work-tree.catalog.test.tsx@@ -54,7 +54,7 @@ const TODO_STATUS = {const PROJECT = { id: "p1", title: "Desktop", status: "in_progress", issue_count: 4, done_count: 1 } as Project;-let listIssues: ReturnType<typeof vi.fn>;+let listIssueTableRows: ReturnType<typeof vi.fn>;let listIssueStatuses: ReturnType<typeof vi.fn>;function renderSection() {@@ -79,10 +79,10 @@ function renderSection() {}beforeEach(() => {- listIssues = vi.fn(async () => ({ issues: [], total: 0 }));+ listIssueTableRows = vi.fn(async () => ({ rows: [], total: 0, next_cursor: null }));listIssueStatuses = vi.fn(async () => ({ statuses: [TODO_STATUS], categories: [], total: 1 }));setApiInstance({- listIssues,+ listIssueTableRows,listIssueStatuses,getIssueViewPreference: vi.fn(() => new Promise(() => {})),} as unknown as ApiClient);@@ -97,11 +97,13 @@ describe("ProjectsSection project row", () => {const retry = await screen.findByRole("button", { name: "Retry" });expect(screen.getByText("Couldn't load issues")).toBeInTheDocument();- expect(listIssues).not.toHaveBeenCalled();+ expect(listIssueTableRows).not.toHaveBeenCalled();fireEvent.click(retry);await screen.findByText("No issues");- expect(listIssues).toHaveBeenCalledWith(expect.objectContaining({ project_id: "p1" }));+ expect(listIssueTableRows).toHaveBeenCalledWith(+ expect.objectContaining({ query: expect.objectContaining({ scope: { kind: "project", project_id: "p1" } }) }),+ );});});diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 833bc7b2d5..6b4cfd4fc2 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -56,7 +56,7 @@},"relation_filter_error": {"title": "Couldn't load the \"Relation to me\" filter",- "hint": "Issues filtered by \"Subscribed by me\" or \"Assigned to my agents\" can't be shown until your subscriptions and agents load."+ "hint": "Issues filtered by \"Subscribed by me\" or \"My agents' work\" can't be shown until your subscriptions and agents load."},"source_context": {"create_action": "Create sub-issue from here",@@ -194,7 +194,7 @@"section_relation": "Relation to me","relation_assigned": "Assigned to me","relation_created": "Created by me",- "relation_my_agents": "Assigned to my agents",+ "relation_my_agents": "My agents' work","relation_subscribed": "Subscribed by me","section_agent_status": "Agent status","agent_status_running": "Running",@@ -1117,7 +1117,7 @@"variant_my_any": "Any relation","variant_my_assigned": "Assigned to me","variant_my_created": "Created by me",- "variant_my_involved": "Involved"+ "variant_my_involved": "My agents' work"},"plugins": {"panels": "Plugins",diff --git a/packages/views/locales/en/layout.json b/packages/views/locales/en/layout.jsonindex f17e1b768e..f0d2386ffa 100644--- a/packages/views/locales/en/layout.json+++ b/packages/views/locales/en/layout.json@@ -131,6 +131,7 @@"assignee_me": "Me","assignee_my_agents": "My agents","assignee_me_and_my_agents": "Me and my agents",+ "assignee_projects_only": "Only applies to issues listed under Projects","reset": "Reset","load_more": "Load more","show_less": "Show less",diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.jsonindex d72d8f76c5..a8fca9a39b 100644--- a/packages/views/locales/es/issues.json+++ b/packages/views/locales/es/issues.json@@ -210,7 +210,7 @@"section_relation": "Relación conmigo","relation_assigned": "Asignadas a mí","relation_created": "Creadas por mí",- "relation_my_agents": "Asignadas a mis agentes",+ "relation_my_agents": "Trabajo de mis agentes","relation_subscribed": "Suscrito por mí","section_agent_status": "Estado del agente","agent_status_running": "En ejecución",@@ -1031,7 +1031,7 @@"variant_my_any": "Cualquier relación","variant_my_assigned": "Asignadas a mí","variant_my_created": "Creadas por mí",- "variant_my_involved": "En las que participo"+ "variant_my_involved": "Trabajo de mis agentes"},"plugins": {"panels": "Plugins",@@ -1818,7 +1818,7 @@},"relation_filter_error": {"title": "No se ha podido cargar el filtro «Relación conmigo»",- "hint": "Las tareas filtradas por «Suscrito por mí» o «Asignadas a mis agentes» no se pueden mostrar hasta que se carguen tus suscripciones y agentes."+ "hint": "Las tareas filtradas por «Suscrito por mí» o «Trabajo de mis agentes» no se pueden mostrar hasta que se carguen tus suscripciones y agentes."},"views": {"builtin": {diff --git a/packages/views/locales/es/layout.json b/packages/views/locales/es/layout.jsonindex a00fc177d9..114a890a20 100644--- a/packages/views/locales/es/layout.json+++ b/packages/views/locales/es/layout.json@@ -131,6 +131,7 @@"assignee_me": "Yo","assignee_my_agents": "Mis agentes","assignee_me_and_my_agents": "Yo y mis agentes",+ "assignee_projects_only": "Solo se aplica a las tareas que se muestran en Proyectos","reset": "Restablecer","load_more": "Cargar más","show_less": "Mostrar menos",diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex 54ff09a499..b59aaff8b8 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -56,7 +56,7 @@},"relation_filter_error": {"title": "Impossible de charger le filtre « Lien avec moi »",- "hint": "Les tâches filtrées par « Auxquels je suis abonné » ou « Assignés à mes agents » s'affichent une fois vos abonnements et agents chargés."+ "hint": "Les tâches filtrées par « Auxquels je suis abonné » ou « Travail de mes agents » s'affichent une fois vos abonnements et agents chargés."},"source_context": {"create_action": "Créer une sous-tâche à partir d'ici",@@ -194,7 +194,7 @@"section_relation": "Lien avec moi","relation_assigned": "Qui me sont assignés","relation_created": "Créés par moi",- "relation_my_agents": "Assignés à mes agents",+ "relation_my_agents": "Travail de mes agents","relation_subscribed": "Auxquels je suis abonné","section_agent_status": "Statut de l'agent","agent_status_running": "En cours d'exécution",@@ -1117,7 +1117,7 @@"variant_my_any": "Toute relation","variant_my_assigned": "Qui me sont assignés","variant_my_created": "Que j'ai créés",- "variant_my_involved": "Impliqué"+ "variant_my_involved": "Travail de mes agents"},"plugins": {"panels": "Plugins",diff --git a/packages/views/locales/fr/layout.json b/packages/views/locales/fr/layout.jsonindex cef3d72e55..6a9519bc0b 100644--- a/packages/views/locales/fr/layout.json+++ b/packages/views/locales/fr/layout.json@@ -131,6 +131,7 @@"assignee_me": "Moi","assignee_my_agents": "Mes agents","assignee_me_and_my_agents": "Moi et mes agents",+ "assignee_projects_only": "S'applique uniquement aux tâches affichées sous Projets","reset": "Réinitialiser","load_more": "Afficher plus","show_less": "Afficher moins",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex f36d939ba0..a57b0c612f 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -55,7 +55,7 @@},"relation_filter_error": {"title": "「自分との関係」フィルターを読み込めませんでした",- "hint": "「自分が購読中」または「自分のエージェントが担当」で絞り込んだタスクは、購読とエージェントを読み込むまで表示できません。"+ "hint": "「自分が購読中」または「マイエージェントの作業」で絞り込んだタスクは、購読とエージェントを読み込むまで表示できません。"},"source_context": {"create_action": "このコメントからサブタスクを作成",@@ -192,7 +192,7 @@"section_relation": "自分との関係","relation_assigned": "自分が担当","relation_created": "自分が作成",- "relation_my_agents": "自分のエージェントが担当",+ "relation_my_agents": "マイエージェントの作業","relation_subscribed": "自分が購読中","section_agent_status": "エージェントの状態","agent_status_running": "実行中",@@ -1071,7 +1071,7 @@"variant_my_any": "何らかの関わり","variant_my_assigned": "自分に割り当て","variant_my_created": "自分が作成",- "variant_my_involved": "関与中"+ "variant_my_involved": "マイエージェントの作業"},"plugins": {"panels": "Plugins",diff --git a/packages/views/locales/ja/layout.json b/packages/views/locales/ja/layout.jsonindex 31ce62ee92..b00bd89429 100644--- a/packages/views/locales/ja/layout.json+++ b/packages/views/locales/ja/layout.json@@ -129,6 +129,7 @@"assignee_me": "自分","assignee_my_agents": "自分のエージェント","assignee_me_and_my_agents": "自分と自分のエージェント",+ "assignee_projects_only": "サイドバーの「プロジェクト」に表示されるタスクにのみ適用されます","reset": "リセット","load_more": "さらに表示","show_less": "表示を減らす",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex ee843564ba..804bb7a395 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -55,7 +55,7 @@},"relation_filter_error": {"title": "'나와의 관계' 필터를 불러오지 못했습니다",- "hint": "구독과 에이전트를 불러온 후에 '내가 구독 중' 또는 '내 에이전트가 담당' 필터의 태스크를 표시할 수 있습니다."+ "hint": "구독과 에이전트를 불러온 후에 '내가 구독 중' 또는 '내 에이전트의 작업' 필터의 태스크를 표시할 수 있습니다."},"source_context": {"create_action": "이 댓글에서 하위 태스크 만들기",@@ -192,7 +192,7 @@"section_relation": "나와의 관계","relation_assigned": "내가 담당","relation_created": "내가 생성",- "relation_my_agents": "내 에이전트가 담당",+ "relation_my_agents": "내 에이전트의 작업","relation_subscribed": "내가 구독 중","section_agent_status": "에이전트 상태","agent_status_running": "실행 중",@@ -1071,7 +1071,7 @@"variant_my_any": "모든 관련","variant_my_assigned": "나에게 할당됨","variant_my_created": "내가 생성함",- "variant_my_involved": "참여 중"+ "variant_my_involved": "내 에이전트의 작업"},"plugins": {"panels": "Plugins",diff --git a/packages/views/locales/ko/layout.json b/packages/views/locales/ko/layout.jsonindex 267f7a2212..42e4055e07 100644--- a/packages/views/locales/ko/layout.json+++ b/packages/views/locales/ko/layout.json@@ -129,6 +129,7 @@"assignee_me": "나","assignee_my_agents": "내 에이전트","assignee_me_and_my_agents": "나와 내 에이전트",+ "assignee_projects_only": "사이드바의 '프로젝트' 아래에 표시되는 태스크에만 적용됩니다","reset": "초기화","load_more": "더 보기","show_less": "간단히 보기",diff --git a/packages/views/locales/ru/issues.json b/packages/views/locales/ru/issues.jsonindex cefe32f6a7..69c9afbc61 100644--- a/packages/views/locales/ru/issues.json+++ b/packages/views/locales/ru/issues.json@@ -191,7 +191,7 @@"section_relation": "Отношение ко мне","relation_assigned": "Назначено мне","relation_created": "Создано мной",- "relation_my_agents": "Назначено моим агентам",+ "relation_my_agents": "Работа моих агентов","section_agent_status": "Статус агента","agent_status_running": "Выполняется","operator_label": "Условие",@@ -1208,7 +1208,7 @@"variant_my_any": "Любое отношение","variant_my_assigned": "Назначено мне","variant_my_created": "Создано мной",- "variant_my_involved": "Я участвую"+ "variant_my_involved": "Работа моих агентов"},"plugins": {"panels": "Плагины",@@ -2028,7 +2028,7 @@"setup_hint": "Условий пока нет, поэтому в представлении показаны все задачи"},"relation_filter_error": {- "hint": "Задачи с фильтрами «За которыми я слежу» или «Назначенные моим агентам» нельзя показать, пока не загрузятся ваши подписки и агенты.",+ "hint": "Задачи с фильтрами «За которыми я слежу» или «Работа моих агентов» нельзя показать, пока не загрузятся ваши подписки и агенты.","title": "Не удалось загрузить фильтр «Отношение ко мне»"},"unread_filter_error": {diff --git a/packages/views/locales/ru/layout.json b/packages/views/locales/ru/layout.jsonindex ff57a0ce56..d901ad68bc 100644--- a/packages/views/locales/ru/layout.json+++ b/packages/views/locales/ru/layout.json@@ -105,6 +105,7 @@"assignee_me": "Я","assignee_my_agents": "Мои агенты","assignee_me_and_my_agents": "Я и мои агенты",+ "assignee_projects_only": "Действует только на задачи в разделе «Проекты»","reset": "Сбросить","load_more": "Загрузить ещё","show_less": "Показать меньше",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex b2f69f1adb..b50165ded6 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -55,7 +55,7 @@},"relation_filter_error": {"title": "“与我的关系”筛选加载失败",- "hint": "加载订阅和智能体后才能显示按“我订阅的”或“分配给我的智能体的”筛选的任务。"+ "hint": "加载订阅和智能体后才能显示按“我订阅的”或“我的智能体在做”筛选的任务。"},"source_context": {"create_action": "从这条评论创建子任务",@@ -192,7 +192,7 @@"section_relation": "与我的关系","relation_assigned": "分配给我的","relation_created": "我创建的",- "relation_my_agents": "分配给我的智能体的",+ "relation_my_agents": "我的智能体在做","relation_subscribed": "我订阅的","section_agent_status": "智能体状态","agent_status_running": "运行中",@@ -1071,7 +1071,7 @@"variant_my_any": "任何相关","variant_my_assigned": "分配给我","variant_my_created": "我创建的",- "variant_my_involved": "我参与的"+ "variant_my_involved": "我的智能体在做"},"plugins": {"panels": "Plugins",diff --git a/packages/views/locales/zh-Hans/layout.json b/packages/views/locales/zh-Hans/layout.jsonindex 579ffdde95..38f2a98b45 100644--- a/packages/views/locales/zh-Hans/layout.json+++ b/packages/views/locales/zh-Hans/layout.json@@ -129,6 +129,7 @@"assignee_me": "我","assignee_my_agents": "我的智能体","assignee_me_and_my_agents": "我和我的智能体",+ "assignee_projects_only": "仅作用于侧边栏“项目”下展开的任务","reset": "重置","load_more": "加载更多","show_less": "收起",diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.jsonindex 0adb0f8ba5..b4829af3b3 100644--- a/packages/views/locales/zh-Hant/issues.json+++ b/packages/views/locales/zh-Hant/issues.json@@ -55,7 +55,7 @@},"relation_filter_error": {"title": "「與我的關係」篩選載入失敗",- "hint": "載入訂閱和 AI 代理後才能顯示按「我訂閱的」或「分配給我的 AI 代理的」篩選的任務。"+ "hint": "載入訂閱和 AI 代理後才能顯示按「我訂閱的」或「我的 AI 代理在做」篩選的任務。"},"source_context": {"create_action": "從這條評論建立子任務",@@ -192,7 +192,7 @@"section_relation": "與我的關係","relation_assigned": "分配給我的","relation_created": "我建立的",- "relation_my_agents": "分配給我的 AI 代理的",+ "relation_my_agents": "我的 AI 代理在做","relation_subscribed": "我訂閱的","section_agent_status": "AI 代理狀態","agent_status_running": "執行中",@@ -1071,7 +1071,7 @@"variant_my_any": "任何相關","variant_my_assigned": "分配給我","variant_my_created": "我建立的",- "variant_my_involved": "我參與的"+ "variant_my_involved": "我的 AI 代理在做"},"plugins": {"panels": "Plugins",diff --git a/packages/views/locales/zh-Hant/layout.json b/packages/views/locales/zh-Hant/layout.jsonindex 0f87f10cb1..629c848eb6 100644--- a/packages/views/locales/zh-Hant/layout.json+++ b/packages/views/locales/zh-Hant/layout.json@@ -129,6 +129,7 @@"assignee_me": "我","assignee_my_agents": "我的 AI 代理","assignee_me_and_my_agents": "我和我的 AI 代理",+ "assignee_projects_only": "僅作用於側邊欄「專案」下展開的任務","reset": "重設","load_more": "載入更多","show_less": "收合",diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 68d44ea3d1..9706afc965 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2278,6 +2278,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Route("/api/squads", func(r chi.Router) {r.Get("/", h.ListSquads)r.Post("/", h.CreateSquad)+ // The squads behind the caller's "my agents" relation; backs+ // that filter on client-filtered surfaces.+ r.Get("/involved", h.ListInvolvedSquadIDs)r.Route("/{id}", func(r chi.Router) {r.Get("/", h.GetSquad)r.Put("/", h.UpdateSquad)diff --git a/server/internal/handler/issue_table_negation_test.go b/server/internal/handler/issue_table_negation_test.goindex 2bce2e7d63..585b01b9cc 100644--- a/server/internal/handler/issue_table_negation_test.go+++ b/server/internal/handler/issue_table_negation_test.go@@ -7,7 +7,9 @@ import ("testing""time"+ "github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated")// "Is not" keeps exactly the rows "is" drops — including rows where the@@ -36,6 +38,24 @@ func TestIssueTableRowsNegationAndRelations(t *testing.T) {unassignedByOther := issue("unassigned", testutil.Cols{"status": "in_progress", "creator_id": otherUser,})+ ledByMyAgent := dbfx.Squad(t, fmt.Sprintf("negate my squad %d", suffix), myAgent)+ withMe := dbfx.Squad(t, fmt.Sprintf("negate squad with me %d", suffix), otherAgent)+ dbfx.SquadMember(t, withMe, "member", testUserID)+ withMyAgent := dbfx.Squad(t, fmt.Sprintf("negate squad with my agent %d", suffix), otherAgent)+ dbfx.SquadMember(t, withMyAgent, "agent", myAgent)+ notMine := dbfx.Squad(t, fmt.Sprintf("negate their squad %d", suffix), otherAgent)+ mySquad := issue("my agent's squad", testutil.Cols{+ "assignee_type": "squad", "assignee_id": ledByMyAgent, "creator_id": otherUser,+ })+ squadWithMe := issue("squad with me", testutil.Cols{+ "assignee_type": "squad", "assignee_id": withMe, "creator_id": otherUser,+ })+ squadWithMyAgent := issue("squad with my agent", testutil.Cols{+ "assignee_type": "squad", "assignee_id": withMyAgent, "creator_id": otherUser,+ })+ theirSquad := issue("their squad", testutil.Cols{+ "assignee_type": "squad", "assignee_id": notMine, "creator_id": otherUser,+ })subscribe := func(issueID, userType, userID string) {dbfx.InsertNoID(t, "issue_subscriber", testutil.Cols{@@ -50,6 +70,7 @@ func TestIssueTableRowsNegationAndRelations(t *testing.T) {fixture := map[string]struct{}{assignedToMe: {}, mineByAgent: {}, theirAgent: {}, unassignedByOther: {},+ mySquad: {}, squadWithMe: {}, squadWithMyAgent: {}, theirSquad: {},}rows := func(filters issueTableFiltersRequest) []string {t.Helper()@@ -85,39 +106,42 @@ func TestIssueTableRowsNegationAndRelations(t *testing.T) {assertRows("status is not done",issueTableFiltersRequest{Statuses: []string{"done"}, Negate: []string{"statuses"}},- mineByAgent, theirAgent, unassignedByOther)+ mineByAgent, theirAgent, unassignedByOther, mySquad, squadWithMe, squadWithMyAgent, theirSquad)// The unassigned row has no assignee to compare: "is not" keeps it.assertRows("assignee is not me keeps unassigned rows",issueTableFiltersRequest{Assignees: []issueTableActorRef{{Type: "member", ID: testUserID}},Negate: []string{"assignees"},},- mineByAgent, theirAgent, unassignedByOther)+ mineByAgent, theirAgent, unassignedByOther, mySquad, squadWithMe, squadWithMyAgent, theirSquad)assertRows("assignee is not 'no assignee'",issueTableFiltersRequest{IncludeNoAssignee: true, Negate: []string{"assignees"}},- assignedToMe, mineByAgent, theirAgent)+ assignedToMe, mineByAgent, theirAgent, mySquad, squadWithMe, squadWithMyAgent, theirSquad)assertRows("project is not P keeps projectless rows",issueTableFiltersRequest{ProjectIDs: []string{project}, Negate: []string{"project_ids"}},- mineByAgent, unassignedByOther)+ mineByAgent, unassignedByOther, mySquad, squadWithMe, squadWithMyAgent, theirSquad)assertRows("negating a dimension without values changes nothing",issueTableFiltersRequest{Negate: []string{"label_ids", "priorities"}},- assignedToMe, mineByAgent, theirAgent, unassignedByOther)+ assignedToMe, mineByAgent, theirAgent, unassignedByOther, mySquad, squadWithMe, squadWithMyAgent, theirSquad)assertRows("relation assigned",issueTableFiltersRequest{Relations: []string{"assigned"}},assignedToMe)- assertRows("relation my agents excludes other people's agents",+ assertRows("relation my agents matches the involved scope: my agents and my squads",issueTableFiltersRequest{Relations: []string{"my_agents"}},- mineByAgent)+ mineByAgent, mySquad, squadWithMe, squadWithMyAgent)assertRows("relations OR within the dimension",issueTableFiltersRequest{Relations: []string{"assigned", "my_agents"}},- assignedToMe, mineByAgent)+ assignedToMe, mineByAgent, mySquad, squadWithMe, squadWithMyAgent)+ assertRows("relation is not my agents",+ issueTableFiltersRequest{Relations: []string{"my_agents"}, Negate: []string{"relations"}},+ assignedToMe, theirAgent, unassignedByOther, theirSquad)assertRows("relation subscribed matches only my member subscriptions",issueTableFiltersRequest{Relations: []string{"subscribed"}},assignedToMe, theirAgent)assertRows("relation is not subscribed",issueTableFiltersRequest{Relations: []string{"subscribed"}, Negate: []string{"relations"}},- mineByAgent, unassignedByOther)+ mineByAgent, unassignedByOther, mySquad, squadWithMe, squadWithMyAgent, theirSquad)subscribedNotMine := issueTableFilterNode{Match: "all", Children: []issueTableFilterNode{{Field: "relations", Values: rawValues("subscribed")},{Field: "relations", Negate: true, Values: rawValues("assigned", "my_agents")},@@ -127,7 +151,7 @@ func TestIssueTableRowsNegationAndRelations(t *testing.T) {theirAgent)assertRows("relation is not created by me",issueTableFiltersRequest{Relations: []string{"created"}, Negate: []string{"relations"}},- mineByAgent, theirAgent, unassignedByOther)+ mineByAgent, theirAgent, unassignedByOther, mySquad, squadWithMe, squadWithMyAgent, theirSquad)assertRows("negation is per dimension and ANDs with the rest",issueTableFiltersRequest{Relations: []string{"assigned"},@@ -135,6 +159,28 @@ func TestIssueTableRowsNegationAndRelations(t *testing.T) {Negate: []string{"relations"},},)++ // The id list clients filter "my agents" with holds the same squads.+ involved := map[string]bool{}+ for _, id := range involvedSquadIDs(t) {+ involved[id] = true+ }+ for squad, want := range map[string]bool{ledByMyAgent: true, withMe: true, withMyAgent: true, notMine: false} {+ if involved[squad] != want {+ t.Fatalf("involved squads include %s = %v, want %v", squad, involved[squad], want)+ }+ }+}++func involvedSquadIDs(t *testing.T) []string {+ t.Helper()+ var out struct {+ SquadIDs []string `json:"squad_ids"`+ }+ req := newRequest(http.MethodGet, "/api/squads/involved", nil)+ req = req.WithContext(middleware.SetMemberContext(req.Context(), testWorkspaceID, db.Member{}))+ testutil.Call(t, testHandler.ListInvolvedSquadIDs, req).Want(http.StatusOK).JSON(&out)+ return out.SquadIDs}func TestIssueTableRowsRejectsUnknownNegateAndRelation(t *testing.T) {diff --git a/server/internal/handler/issue_table_query.go b/server/internal/handler/issue_table_query.goindex 9e104e4b81..da0a768659 100644--- a/server/internal/handler/issue_table_query.go+++ b/server/internal/handler/issue_table_query.go@@ -445,18 +445,20 @@ func issueTableRelationPredicate(relation string, userRef string) string {AND isub.user_id = %s::uuidAND isub.unsubscribed_at IS NULL)`, userRef)- default: // my_agents- return fmt.Sprintf(`(i.assignee_type = 'agent' AND i.assignee_id IN (- SELECT a.id FROM agent a- WHERE a.workspace_id = $1- AND a.owner_id = %s::uuid- ))`, userRef)+ default: // my_agents — the same issues as the "involved" scope+ return issueTableInvolvedPredicate(userRef)}}func appendIssueTableInvolvedPredicate(where []string, addArg func(any) string, userID pgtype.UUID) []string {- ref := addArg(userID)- return append(where, fmt.Sprintf(`(+ return append(where, issueTableInvolvedPredicate(addArg(userID)))+}++// issueTableInvolvedPredicate matches issues assigned to an agent the user+// owns, or to a squad the user belongs to or one of their agents leads or+// belongs to.+func issueTableInvolvedPredicate(userRef string) string {+ return fmt.Sprintf(`((i.assignee_type = 'agent' AND i.assignee_id IN (SELECT a.id FROM agent aWHERE a.workspace_id = $1@@ -486,7 +488,7 @@ func appendIssueTableInvolvedPredicate(where []string, addArg func(any) string,AND a.workspace_id = $1AND a.owner_id = %[1]s::uuid))-)`, ref))+)`, userRef)}func (h *Handler) compileIssueTableQuery(w http.ResponseWriter, r *http.Request, spec issueTableQuerySpec) (issueTableSQL, bool) {diff --git a/server/internal/handler/squad.go b/server/internal/handler/squad.goindex 59534ac4d4..7548dcf31e 100644--- a/server/internal/handler/squad.go+++ b/server/internal/handler/squad.go@@ -224,6 +224,33 @@ func (h *Handler) ListSquads(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, resp)}+// ListInvolvedSquadIDs returns the ids of the squads whose issues count as the+// caller's agents' work, so clients can evaluate the "my agents" relation on+// rows they filter themselves.+func (h *Handler) ListInvolvedSquadIDs(w http.ResponseWriter, r *http.Request) {+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceIDFromURL(r, "workspaceId"), "workspace_id")+ if !ok {+ return+ }+ ids, err := h.Queries.ListInvolvedSquadIDs(r.Context(), db.ListInvolvedSquadIDsParams{+ WorkspaceID: wsUUID,+ UserID: parseUUID(userID),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list involved squads")+ return+ }+ squadIDs := make([]string, len(ids))+ for i, id := range ids {+ squadIDs[i] = uuidToString(id)+ }+ writeJSON(w, http.StatusOK, map[string][]string{"squad_ids": squadIDs})+}+func (h *Handler) CreateSquad(w http.ResponseWriter, r *http.Request) {workspaceID := workspaceIDFromURL(r, "workspaceId")// Any workspace member can create a squad and becomes its creatordiff --git a/server/pkg/db/generated/squad.sql.go b/server/pkg/db/generated/squad.sql.goindex 6039d3445a..71c4831faa 100644--- a/server/pkg/db/generated/squad.sql.go+++ b/server/pkg/db/generated/squad.sql.go@@ -267,6 +267,59 @@ func (q *Queries) ListAllSquads(ctx context.Context, workspaceID pgtype.UUID) ([return items, nil}+const listInvolvedSquadIDs = `-- name: ListInvolvedSquadIDs :many+SELECT sm.squad_id+ FROM squad_member sm+ JOIN squad s ON s.id = sm.squad_id+ WHERE s.workspace_id = $1+ AND sm.member_type = 'member'+ AND sm.member_id = $2+UNION+SELECT s.id+ FROM squad s+ JOIN agent a ON a.id = s.leader_id+ WHERE s.workspace_id = $1+ AND a.workspace_id = $1+ AND a.owner_id = $2+UNION+SELECT sm.squad_id+ FROM squad_member sm+ JOIN squad s ON s.id = sm.squad_id+ JOIN agent a ON a.id = sm.member_id+ WHERE s.workspace_id = $1+ AND sm.member_type = 'agent'+ AND a.workspace_id = $1+ AND a.owner_id = $2+`++type ListInvolvedSquadIDsParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ UserID pgtype.UUID `json:"user_id"`+}++// Squads whose issues count as the user's agents' work: the user is a member,+// or an agent they own leads or is a member. Must match the squad branch of+// issueTableInvolvedPredicate.+func (q *Queries) ListInvolvedSquadIDs(ctx context.Context, arg ListInvolvedSquadIDsParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listInvolvedSquadIDs, arg.WorkspaceID, arg.UserID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var squad_id pgtype.UUID+ if err := rows.Scan(&squad_id); err != nil {+ return nil, err+ }+ items = append(items, squad_id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listSquadMemberPreviewRows = `-- name: ListSquadMemberPreviewRows :manySELECTsm.squad_id,diff --git a/server/pkg/db/queries/squad.sql b/server/pkg/db/queries/squad.sqlindex 17300551ef..56e6bdf8df 100644--- a/server/pkg/db/queries/squad.sql+++ b/server/pkg/db/queries/squad.sql@@ -59,6 +59,33 @@ ORDER BY(sm.member_type = 'agent' AND sm.member_id = s.leader_id) DESC,sm.created_at ASC;+-- name: ListInvolvedSquadIDs :many+-- Squads whose issues count as the user's agents' work: the user is a member,+-- or an agent they own leads or is a member. Must match the squad branch of+-- issueTableInvolvedPredicate.+SELECT sm.squad_id+ FROM squad_member sm+ JOIN squad s ON s.id = sm.squad_id+ WHERE s.workspace_id = sqlc.arg(workspace_id)+ AND sm.member_type = 'member'+ AND sm.member_id = sqlc.arg(user_id)+UNION+SELECT s.id+ FROM squad s+ JOIN agent a ON a.id = s.leader_id+ WHERE s.workspace_id = sqlc.arg(workspace_id)+ AND a.workspace_id = sqlc.arg(workspace_id)+ AND a.owner_id = sqlc.arg(user_id)+UNION+SELECT sm.squad_id+ FROM squad_member sm+ JOIN squad s ON s.id = sm.squad_id+ JOIN agent a ON a.id = sm.member_id+ WHERE s.workspace_id = sqlc.arg(workspace_id)+ AND sm.member_type = 'agent'+ AND a.workspace_id = sqlc.arg(workspace_id)+ AND a.owner_id = sqlc.arg(user_id);+-- name: ListAllSquads :manySELECT * FROM squad WHERE workspace_id = $1 ORDER BY created_at ASC;