Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7418: add issue event and time wakeups (#8467)
Jiayuan Zhangc375f83c2ec5
diff --git a/apps/mobile/app/(app)/[workspace]/issue/[id]/runs.tsx b/apps/mobile/app/(app)/[workspace]/issue/[id]/runs.tsxindex 5cbcd58aa5..b2bbbc0890 100644--- a/apps/mobile/app/(app)/[workspace]/issue/[id]/runs.tsx+++ b/apps/mobile/app/(app)/[workspace]/issue/[id]/runs.tsx@@ -29,6 +29,7 @@ const PAST_STATUS_ORDER: Record<AgentTask["status"], number> = {cancelled: 1,completed: 2,queued: 99,+ deferred: 99,dispatched: 99,waiting_local_directory: 99,running: 99,diff --git a/apps/mobile/components/issue/run-row.tsx b/apps/mobile/components/issue/run-row.tsxindex 7383fc7f3b..874c9e1b7c 100644--- a/apps/mobile/components/issue/run-row.tsx+++ b/apps/mobile/components/issue/run-row.tsx@@ -133,6 +133,7 @@ function fallbackSummary(task: AgentTask): string {const STATUS_LABEL: Record<AgentTask["status"], string> = {queued: "Queued",+ deferred: "Queued",dispatched: "Starting",waiting_local_directory: "Waiting for directory",running: "Running",@@ -143,6 +144,7 @@ const STATUS_LABEL: Record<AgentTask["status"], string> = {const STATUS_CLASS: Record<AgentTask["status"], string> = {queued: "text-muted-foreground",+ deferred: "text-muted-foreground",dispatched: "text-brand",waiting_local_directory: "text-muted-foreground",running: "text-brand",diff --git a/docs/engineering/issue-wakeups.md b/docs/engineering/issue-wakeups.mdnew file mode 100644index 0000000000..c9fac1517c--- /dev/null+++ b/docs/engineering/issue-wakeups.md@@ -0,0 +1,398 @@+# Issue wakeups++An agent can save an event subscription or a timer on an issue, finish its run,+and receive another ordinary run when the input arrives. Business completion is+still decided by the agent after reading current state. There is no sleeping+process, business-condition evaluator, or second run lifecycle.++## Product contract++The shared web/Desktop issue sidebar lists event and time wakeups together,+as compact trigger/target summaries with a separate execution status when available.+Instructions, full filters, errors and+latest-run transcript are in the details popover. A directly visible toggle+controls enabled configurations and restores manually disabled subscriptions or+recurring schedules. Consumed one-shots offer Cancel this execution while unclaimed,+then Enable again (events) or Set a new time (time).+Wakeup history is collapsed by default. A consumed one-shot remains+in the current group while its run is queued, deferred, dispatched or running.+Running or already+claimed tasks use the normal Stop controls. Terminal lifecycle categories+(`done` and `closed`, including custom statuses) disable all configurations;+reopening does not reactivate them.++Board and list activity cues prioritize current runs, mark wakeup-origin runs,+and show enabled wakeup rules as a separate count, not a forecast of executions.+Without an active run they show the+next scheduled time (including a date when needed) or waiting for an event.+A shared workspace summary request contains exact enabled counts and at most+three previews per issue, never prompts or history. Access follows shared issue visibility and workspace membership; private+source-agent and source-run filters are redacted consistently. The issue surface polls once every ten+seconds; cards select their own rows from that shared cache.++Restoring an interval schedules from now; cron uses its next future occurrence,+without replaying missed times. An unconsumed future one-shot can be toggled back+on; expired or consumed time wakeups require choosing a new future time. One-shot+rearming is refused while a previous run is active. Closed issues cannot enable+wakeups; reopening an issue still requires manual enable.++The additive `POST /api/issues/{id}/wakeups/{wakeupID}/enable` accepts the observed+`revision`, plus optional `rearm` and future `at`. It loads stored configuration+under the existing issue/configuration locks and reuses Save's validation,+authorization, receipt cleanup and revision fencing. A stale revision returns+409, and a repeated already-enabled request with the current revision is a no-op.+Clients do not resend instructions, filters or thread references. The new UI+requires this endpoint for restore; deploy the server first. Old clients and the+existing full-config CLI update continue to work without a migration.++Agents manage configurations with `multica issue wakeup`:++```sh+multica issue wakeup events+multica issue wakeup create ISSUE --kind at --after 10m --instruction-file ./instruction.md+multica issue wakeup create ISSUE --kind every --every 1h --instruction-file ./instruction.md+multica issue wakeup create ISSUE --kind cron --cron '0 * * * *' --timezone Asia/Shanghai --instruction-file ./instruction.md+multica issue wakeup create ISSUE --kind event --event task.completed,task.failed,task.cancelled --task-id RUN --instruction-file ./instruction.md+multica issue wakeup list ISSUE+multica issue wakeup get ISSUE WAKEUP+multica issue wakeup disable ISSUE WAKEUP+```++Specify `--agent-id` for human callers; authenticated agents default to themselves.+Event subscriptions default to `once`; `--mode continuous` keeps listening.+A concrete source run must belong to this issue. Registration checks its current+terminal state under a lock, so a run that just finished is not missed. A busy+source run returns 409 and asks the caller to retry; registration never waits+on a source lock while holding the issue lock. The server returns the stable+`wakeup_source_busy` code for this rolled-back conflict; CLI create retries it+once after 250ms. Other conflicts and ambiguous network failures are not retried.+Broad+agent filters observe future facts, without replaying history or following retry+chains. `--parent COMMENT` preserves the original result-delivery thread.++`update ISSUE WAKEUP` accepts the complete create configuration, replaces it,+increments its revision, withdraws old unclaimed inputs, and explicitly enables+it. The creator or a workspace owner/admin may update or disable; the replacing+caller must themselves be allowed to invoke the selected agent and becomes the+new configuration's recorded human principal.++The scheduler checks approximately every 30 seconds. One-shot timers remain+queued while their runtime is offline. Repeating timers coalesce missed periods+into one pending check and continue from the next future time; they do not replay+every historical tick. All runs retain normal comment delivery, including checks+that find no change. CI can be polled by the agent; CI push events are not claimed+as supported by this version.++## Event catalog++`multica issue wakeup events` lists the 25 supported issue-scoped subscriptions:++| Area | Events |+| --- | --- |+| Run | `task.queued`, `task.dispatched`, `task.started`, `task.deferred`, `task.waiting_local_directory`, `task.completed`, `task.failed`, `task.cancelled` |+| Issue | `issue.updated`, `issue.status_changed`, `issue.assignee_changed`, `issue.parent_changed`, `issue.project_changed`, `issue.labels_changed`, `issue.properties_changed`, `issue.metadata_changed` |+| Comment | `comment.created`, `comment.updated`, `comment.deleted`, `comment.resolved`, `comment.unresolved` |+| Reaction | `reaction.added`, `reaction.removed` (issue or comment) |+| Attachment | `attachment.attached`, `attachment.detached` (issue or comment) |++`task.started` means the persisted run entered `running`. Retries emit a new+`task.queued` with `retry_of_task_id`; manual reruns carry `rerun_of_task_id`.+Queue/defer transitions may happen repeatedly. Unchanged writes, bookkeeping+revisions, duplicate reactions, and pruning an already-deleted comment do not+produce another fact. Attachment events describe binding to an issue/comment,+not uploading an unbound file; moving a file produces detach and attach facts.++`issue.updated` includes `changed_fields` for meaningful issue fields, excluding+position, revision and timestamps. Specialized issue events can accompany it;+subscribing to both produces two inputs that the normal dispatcher coalesces.+Metadata/properties events include changed keys, never their values. Comment+events contain comment/thread/parent references, not bodies. Attachment events+contain references, not private URLs or filenames. Agents pull current state to+decide what to do. There is no business-condition evaluator.++Each newly captured fact includes `event_id`, `event_type`, `version`,+`occurred_at`, workspace/issue IDs, actor identity and optional source run/agent.+The already-terminal registration snapshot additionally has `observed_at` and+`registration_snapshot`; its `occurred_at` can be null for historical runs with+no completion timestamp. Older queued payloads remain readable.++`--filter-agent-id` selects the run's agent for task events. New mutation-only+requests using this legacy flag normalize to `filter_actor_type=agent` and+`filter_actor_id`; use actor flags for comment/issue/reaction/attachment changes.+Existing stored rules and legacy mixed task/mutation requests remain supported. Editing another agent's comment does not make that+agent the editor; payloads distinguish actor from author. `--task-id` accepts+only run events. Filters never expand the subscription beyond its current issue.++Use `--filter-actor-type member --filter-actor-id USER_ID` to wait for a+specific workspace member, or type `agent` for a source agent. For example:++```sh+multica issue wakeup create ISSUE --kind event --event comment.created \+ --filter-actor-type member --filter-actor-id USER_ID \+ --instruction-file ./instruction.md+```++These optional paired filters apply to issue, comment, reaction and attachment+changes. They match the actor who performed the change; for a new comment this+is its author, but for an edit it is the editor, not the original author. Unknown+system attribution does not match. Task subscriptions keep their existing+agent/run filters. Actor filters cannot be combined with those source filters.+The ID is the user's UUID, not the membership record's UUID; it must belong to+the current workspace. Other people's events neither enqueue nor consume a+one-shot rule. Broad subscriptions without actor filters behave as before.+Enable/rearm retains the stored actor filter; an explicit full update can replace+or clear it. The sidebar, board summary and inventory show the actor's name;+private agent references are redacted, retaining a generic selected-actor label.++Migrations 531–532 add nullable actor columns and update transactional capture.+Apply migrations, then deploy the API/CLI before creating actor-filtered rules;+update web/Desktop to display the actor restriction. Old clients can read the+additive response, but cannot show the new restriction. On application rollback,+keep these migrations: the database still enforces stored filters even for older+consumers. Schema rollback deliberately refuses while any actor-filtered rule+exists, including disabled rules, so a later re-enable cannot silently broaden+it. Disable/drain and remove those configurations before rolling 532/531 back.++The platform lifecycle names `issue.created` and `issue.deleted` are listed+separately and rejected for self-wakeups: subscription requires an existing+issue, and deleting it withdraws its work. Workspace/cross-issue subscriptions,+external CI push events, and expanding the plugin subscription contract are+outside this version. Terminal issue transitions disable wakeups rather than+starting a final run on the closed issue.++## Implementation++- `pkg/eventcontract` owns stable business-event names independently of plugins.+ Plugin constants alias the existing names, preserving their payload contract.+- `issue_wakeup` stores configuration and `issue_wakeup_receipt` stores matching+ inputs. Run transitions and the collaboration changes in the catalog above+ capture matching receipts in the source transaction. SQL capture hooks cover+ service, scheduler and HTTP writers without a best-effort in-memory hop. They+ do not build a general event archive or evaluate business predicates.+- Registration is prospective once committed; agents should subscribe before+ querying current state. The explicit run filter also checks current state+ during registration. There is no global event order or historical replay API.+- The existing scheduler leases `issue_wakeup_dispatch`. The adapter locks one+ issue/configuration, rechecks scope and the creator's current invoke rights,+ and consumes receipts together with ordinary task enqueue. Failure leaves the+ receipt available for retry. Claim rechecks permissions after an offline wait.+- Event notifications merge by rule, revision and event type, keeping the first+ occurrence time, count and latest source reference. Agents read current state+ and comment history when intermediate references have been condensed.+ Time inputs replace the pending time note with the newest signal. A claimed+ prompt is immutable; later input becomes at most one subsequent queued task.+- Mutations and run events from the same wakeup's run are ignored. HTTP mutation+ transactions stamp server-resolved actor and source task identity in local+ PostgreSQL settings; those settings do not survive connection reuse. A client+ cannot choose source identity through a request body or an untrusted task header.+- `context.wakeup_id` and `context.wakeup_revision` identify the new trigger.+ Bounded structured facts live in additive `context.wakeup_evidence` (version 1).+ Its instruction/facts travel in the ordinary per-turn handoff note. Daemon+ wakeup prompts preserve this instruction even when a delivery thread exists.+ Automatic retries inherit both context and note.+- The existing pending-task index is retained. For wakeup tasks only, its derived+ `comment_thread_id` scheduling scope is the configuration ID; the real delivery+ thread stays in `trigger_comment_id`. This preserves old retry SQL during a+ rolling server upgrade. Comment/assign coalescing excludes wakeup inputs, and+ the existing issue/agent execution fence still serializes actual runs.+- Issue/workspace deletion explicitly removes configurations and receipts in+ the application deletion graph. No foreign keys or cascading relationships+ are added.++## Deployment and verification++Apply additive migrations before starting the new server. Existing pending-task+indexes are not rebuilt or dropped, and historical queue rows are not rewritten.+Deploy the updated CLI and daemon with the server to recognize the wakeup command+and per-turn prompt. Before rollback, disable/drain wakeups; do not remove their+configuration tables while tasks still reference them.++Migration 520 adds capture hooks without indexes, table rewrites, or foreign+keys. Deploy it before admitting subscriptions to the expanded catalog. Older+servers still dispatch the added receipts and older sidebars fall back to raw+event names; only updated servers accept create/update with new event types.+During a rolling upgrade, mutation attribution from older HTTP servers is best+effort (some older write paths provide no source identity). Keep new event+subscriptions disabled until all mutation-serving instances are upgraded, so+their own writes cannot feed back without attribution. Before rolling application+code back, disable subscriptions using the expanded catalog; before rolling the+capture migration back, drain their inputs as well. The down migration restores+the original five-event capture behavior and retains configuration/receipt data.++Migration 521 adds a concurrent partial index for enabled workspace summaries.+It can be rolled back independently of configuration data. Deploy the server+before the UI: an older server lacks the summary endpoint, so cards cannot+show future wakeups until it is upgraded. Existing task activity still works.+New detail fields are optional for rolling compatibility.++Migration 523 excludes the registering run's own events, in addition to events+from runs produced by the same rule. Human/external events with no source run+still match. Apply this migration before enabling broad agent-created subscriptions.+Rolling it back restores the previous capture function without rewriting data;+disable affected subscriptions first to avoid registration feedback.++This unmerged branch's wakeup migrations use prefixes 509–532, following+main's migrations through 508. The previously used 500–523 wakeup names were+renumbered by +9 without changing their SQL or relative execution order.++Before updating a local database that has already applied the old branch,+stop its API and daemon and rename only the exact wakeup+`schema_migrations.version` entries from the old filenames to the new filenames+(+9). Do not rename main's similarly numbered migrations or rerun the base+wakeup table creation. Databases still on the older 495–508 wakeup names first+need the previous +5 rename to the 500–513 names, then this +9 rename.+Keep this ledger change transactional; leave all wakeup rules, receipts and+queued tasks intact. Fresh databases use the normal migration runner.+++Dispatch keeps the instruction and recent evidence within a 40,000-byte prompt+budget. Large or older details are explicitly condensed; original receipts remain+linked to the task and are consumed atomically with its queue update. A claimed+prompt is immutable, so further inputs remain pending until it starts or recovers.+After the normal 90-second claim recovery window with an expired/absent prepare+lease, `last_error` exposes that wait. Existing runtime claim recovery owns retries;+wakeups do not add another execution timeout. Timer progress advances while waiting.++Integration coverage includes transaction rollback, already-terminal registration,+source scope, one-shot deduplication, independent comment/assign input, merging,+self-loop suppression, custom terminal statuses, reopen behavior, offline timers,+configuration replacement, revoked permission at enqueue/claim, and retry prompt+inheritance. UI tests cover disabling and consumed one-shot state; API response+schemas reject malformed wakeup state rather than presenting an empty list.+Expanded-event integration tests execute writes for every advertised event and+cover attachment rebinding, repeated queue transitions, tombstone cleanup,+meaningful-change suppression, rollback, actor/author distinction, forged source+headers, metadata redaction and self-loop suppression on HTTP mutations.++## Workspace management++Web and Desktop expose **Issue wakeups** inside the Autopilot page (`?tab=wakeups`).+The tab remains available without any autopilots. `GET /api/issue-wakeups` returns+an access-filtered inventory with counts, agent filter choices, and offset+pagination (50 by default, maximum 100). Scope, trigger kind, target agent, and+literal case-insensitive search run on the server; page rows and counts share+one database snapshot. Prompts are omitted from this collection response.++Active means an enabled rule on an open issue **or** an unfinished run, including+consumed one-shot rules and manually disabled rules with running work. The query+looks up runs by their wakeup context, so a retry remains visible even if the+rule's last-task pointer refers to an older attempt. Configuration state and run+state are separate columns. Rules on terminal issues appear under Ended once+all their runs finish. Counts include every rule on shared issues, including rules targeting private+agents. Reading a rule does not grant permission to invoke or configure its+agent. Private source-agent and source-run references are redacted in inventory,+sidebar and board summary responses alike. Instructions remain shared issue+content and are omitted from inventory and summary responses.++Trigger labels describe conditions (for example, "When Emacs's run succeeds"),+not an outcome that has already happened. The monitored agent and specific run+are distinct from the agent to wake. Multiple event types mean any of those events.+Rule labels distinguish waiting, scheduled, turned off, triggered, expired, and+stopped because the issue ended. A consumed one-shot is Triggered even when its+execution is still queued or has failed. A manually disabled rule remains Turned+off even if its previous execution succeeded. Execution results have their own+labels and transcript entrypoint. Familiar schedules use natural language, while+details retain the original cron and timezone. Disabled one-time rules retain+their original scheduled time.++The sidebar and inventory share enable, resubscribe, reschedule, and withdrawal+controls. Batch disable is limited to explicitly selected enabled rules on the+current page. It confirms that already-started runs continue, sends bounded+sequential calls to the existing authorized disable endpoint, and retains only+failed selections for retry. The inventory polls every ten seconds; mutations+invalidate inventory, sidebar, board summaries, and task caches. No scheduler or+Autopilot execution semantics change.+++## Database load and notification retention++The scheduler discovers candidates from due timers and the partial pending-receipt+index, instead of scanning disabled rule history. Each dispatch has a two-second+budget and a 50 ms PostgreSQL lock timeout; diagnostic/fairness writes have their+own 100 ms budgets. Contention leaves inputs pending for the next tick and does+not spend the full batch deadline on one issue. The global inventory counts only+unfinished runs before pagination; indexed latest-run lookups happen for the+selected page, rather than sorting the entire completed-run history.++At most 32 rules per issue and 1,000 per workspace can be enabled. These are+activation limits: disabled history does not count, existing rules are not+silently removed, and editing an already-enabled rule does not consume another+slot. A database trigger serializes activation within a workspace, including+concurrent creation on different issues. Capacity errors return HTTP 400 with+`wakeup_capacity_exceeded`. These initial limits bound synchronous source-event+fanout and can be revisited with measured workload data.++New event captures retain at most one pending notification per rule revision+and event type (25 currently supported types). Repeated inputs retain a count,+first occurrence time and the latest source reference, with an explicit prompt+instruction to read source state. This is a wakeup notification, not an immutable+event archive or a promise to execute once per source event. Legacy pending+receipts remain readable and drain in batches of 100. Processed receipts become+eligible for deletion after seven days, with up to 1,000 deleted per scheduler+tick; backlog can extend that retention. Pending inputs are never age-expired.+Run history and source comments are unaffected. Receipt keys suppress retained+first/latest fact duplicates; they are not a permanent deduplication ledger for+all intermediate coalesced facts.++Migrations 524–527 add concurrent lookup/expiry indexes, 528 adds a nullable+coalescing key, 529 adds its partial unique index, and 530 enables bounded capture+and activation limits. Apply in that order before the new server. No existing+receipt rewrite is needed. New consumers lock receipt rows before constructing+queue evidence. Each merge also rotates its receipt ID: an old consumer can only+mark the version it read as processed, so a concurrent replacement remains+pending during rolling upgrades (a redundant check is possible, lost new input+is avoided). Existing event/task keys and API fields remain compatible.++Rolling application code back leaves the database limits and coalescing active;+old consumers can still drain the notifications. To roll the schema back, reverse+530 before dropping 529/528 and the additive indexes. This restores the prior+capture function and removes limits without deleting rules or pending inputs.+The base wakeup tables must still be retained while any wakeup runs reference them.++## Summary compatibility and capture locks++Pending-run evidence is merged as structured facts and rendered once, without+parsing a previous prompt's headings or omission messages. The total rendered+note still fits 40KB. Older tasks, or notes rewritten by an older dispatcher,+are carried as one opaque bounded legacy item; overflowing history is marked+as condensed and the latest input remains readable. Existing readers and retries+continue using `handoff_note`; no migration or new execution lifecycle is needed.++Dispatch takes the pending-task lock before locking event receipts, so waiting+for an existing task does not hold up capture on those receipt rows. Receipt+consumption and task enqueue/update still commit in one transaction. Source+writes can still wait during that short critical section; this is not a promise+of nonblocking comment writes. Splitting enqueue from consumption would require+another delivery/recovery protocol and is intentionally avoided.++Direct self-trigger protection is scoped to one rule and trusted source-run+identity. Cross-rule cycles remain possible; avoid mutually triggering continuous+comment subscriptions. Prefer a member actor filter for waiting on a human.+Target agent names follow shared issue visibility, while source references and+invocation/management authority keep their existing checks.+++### Editing wakeup instructions++The issue sidebar details and Autopilot wakeup list share a prompt editor. The+workspace list loads the issue's prompts only when the editor opens. Saving uses+`PATCH /api/issues/:id/wakeups/:wakeupID/instruction` with `instruction`,+`expected_instruction`, and `revision`; success returns 204. The existing full+replacement PUT still has its original reconfiguration/rearm semantics.++Prompt-only edits preserve schedule, enabled/consumed state, creator, provenance,+subscription revision, pending receipts and existing runs. Later dispatch uses the+new instructions (including when merging new evidence into a still-pending run);+saving itself does not rewrite queued or running tasks. Structured evidence keeps+the instruction used for its last rendering, so editing does not turn structured+facts into a nested old prompt. Pre-snapshot notes remain bounded historical+context, explicitly subordinate to the current instruction. Closed/disabled rules may+be edited without resuming them. The caller must be the creator or a workspace+admin/owner and must currently be allowed to invoke the target agent.++Under the issue/config locks, both the prior prompt and subscription revision+must match; otherwise saving returns 409 and the UI retains the draft. Keeping+the subscription revision avoids invalidating receipts and queued work on a text+edit. This additive endpoint needs no migration and does not change existing+clients. Deploy the API before using the editor; an older API rejects the new+endpoint and the editor keeps the unsaved text.diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 91a7723017..99d5d3e0d4 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -1,3 +1,6 @@+import type { IssueWakeup, IssueWakeupSummaryRow } from "../types/issue-wakeup";+import type { WorkspaceWakeupPage, WorkspaceWakeupFilters } from "../types/issue-wakeup";+import { WorkspaceWakeupPageSchema, IssueWakeupSchema, IssueWakeupSummaryRowSchema } from "./schemas";import type { InboxFilters } from "../inbox/filter-store";import type { ArchivedInboxPage, ArchivedInboxFacets } from "../types/inbox";import { configStore } from "../config";@@ -1223,6 +1226,40 @@ export class ApiClient {* an ApiError 404, so `issueIdentifierOptions` propagates it instead of* caching it as "no such issue".*/+ async listWorkspaceWakeups(filters: WorkspaceWakeupFilters): Promise<WorkspaceWakeupPage> {+ const params = new URLSearchParams(Object.entries(filters).map(([key, value]) => [key, String(value)]));+ const raw = await this.fetch<unknown>(`/api/issue-wakeups?${params}`);+ const parsed = parseWithFallback<WorkspaceWakeupPage | null>(raw, WorkspaceWakeupPageSchema, null, { endpoint: "GET /api/issue-wakeups" });+ if (!parsed) throw new Error("Could not load workspace wakeups");+ return parsed;+ }++ async listIssueWakeups(issueId: string): Promise<IssueWakeup[]> {+ const raw = await this.fetch<unknown>(`/api/issues/${encodeURIComponent(issueId)}/wakeups`);+ const parsed = parseWithFallback<IssueWakeup[] | null>(raw, IssueWakeupSchema.array(), null, { endpoint: "GET /api/issues/:id/wakeups" });+ if (!parsed) throw new Error("Could not load wakeups");+ return parsed;+ }++ async listIssueWakeupSummaries(): Promise<IssueWakeupSummaryRow[]> {+ const raw = await this.fetch<unknown>("/api/issue-wakeup-summaries");+ const parsed = parseWithFallback<IssueWakeupSummaryRow[] | null>(raw, IssueWakeupSummaryRowSchema.array(), null, { endpoint: "GET /api/issue-wakeup-summaries" });+ if (!parsed) throw new Error("Could not load wakeup summaries");+ return parsed;+ }++ async enableIssueWakeup(issueId: string, wakeupId: string, input: { revision: number; at?: string; rearm?: boolean }): Promise<void> {+ await this.fetch(`/api/issues/${encodeURIComponent(issueId)}/wakeups/${encodeURIComponent(wakeupId)}/enable`, { method: "POST", body: JSON.stringify(input) });+ }++ async editIssueWakeupInstruction(issueId: string, wakeupId: string, input: { instruction: string; expected_instruction: string; revision: number }): Promise<void> {+ await this.fetch(`/api/issues/${encodeURIComponent(issueId)}/wakeups/${encodeURIComponent(wakeupId)}/instruction`, { method: "PATCH", body: JSON.stringify(input) });+ }++ async disableIssueWakeup(issueId: string, wakeupId: string): Promise<void> {+ await this.fetch(`/api/issues/${encodeURIComponent(issueId)}/wakeups/${encodeURIComponent(wakeupId)}/disable`, { method: "POST" });+ }+async getIssue(id: string, options?: { signal?: AbortSignal }): Promise<Issue> {const raw = await this.fetch<unknown>(`/api/issues/${encodeURIComponent(id)}`,diff --git a/packages/core/api/issue-wakeup.test.ts b/packages/core/api/issue-wakeup.test.tsnew file mode 100644index 0000000000..6de092cfdb--- /dev/null+++ b/packages/core/api/issue-wakeup.test.ts@@ -0,0 +1,156 @@+// @vitest-environment node+import { afterEach, expect, it, vi } from "vitest";+import { ApiClient } from "./client";+import { AgentTaskSchema } from "./schemas";+afterEach(() => vi.unstubAllGlobals());+const client = new ApiClient("https://api.example.test");+it("does not present malformed wakeup state as an empty list", async () => {+ vi.stubGlobal(+ "fetch",+ vi+ .fn()+ .mockResolvedValue(+ new Response(JSON.stringify([{ id: "wake", enabled: "false" }])),+ ),+ );+ await expect(client.listIssueWakeups("issue")).rejects.toThrow(+ "Could not load wakeups",+ );+});+it("preserves an empty wakeup list", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("[]")));+ await expect(client.listIssueWakeups("issue")).resolves.toEqual([]);+});+it("does not swallow a disable permission refusal", async () => {+ vi.stubGlobal(+ "fetch",+ vi+ .fn()+ .mockResolvedValue(+ new Response('{"error":"forbidden"}', { status: 403 }),+ ),+ );+ await expect(client.disableIssueWakeup("issue", "wake")).rejects.toThrow();+});++it("rejects malformed wakeup summary counts", async () => {+ vi.stubGlobal(+ "fetch",+ vi+ .fn()+ .mockResolvedValue(new Response(JSON.stringify([{ active_count: "2" }]))),+ );+ await expect(client.listIssueWakeupSummaries()).rejects.toThrow();+});+it("preserves empty summaries", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("[]")));+ await expect(client.listIssueWakeupSummaries()).resolves.toEqual([]);+});++const inventoryFilters = {+ scope: "active",+ kind: "all",+ search: "",+ agent_id: "",+ offset: 0,+ limit: 50,+} as const;+it("rejects malformed workspace inventory rather than hiding ongoing work", async () => {+ vi.stubGlobal(+ "fetch",+ vi+ .fn()+ .mockResolvedValue(+ new Response(JSON.stringify({ items: [], total: "0" })),+ ),+ );+ await expect(client.listWorkspaceWakeups(inventoryFilters)).rejects.toThrow(+ "Could not load workspace wakeups",+ );+});+it("preserves an empty page and its inventory counts", async () => {+ const page = {+ items: [],+ total: 101,+ counts: { all: 101, active: 100, disabled: 1, ended: 0 },+ agents: [],+ };+ const fetcher = vi.fn().mockResolvedValue(new Response(JSON.stringify(page)));+ vi.stubGlobal("fetch", fetcher);+ await expect(+ client.listWorkspaceWakeups({+ ...inventoryFilters,+ offset: 150,+ search: "CI & release",+ }),+ ).resolves.toEqual(page);+ expect(fetcher.mock.calls[0]![0]).toContain("search=CI+%26+release");+ expect(fetcher.mock.calls[0]![0]).toContain("offset=150");+});++it("preserves wakeup origin while accepting old task responses", () => {+ expect(+ AgentTaskSchema.parse({ id: "run", wakeup_id: "wake", status: "deferred" }),+ ).toMatchObject({ wakeup_id: "wake", status: "deferred" });+ expect(AgentTaskSchema.parse({ id: "run" }).wakeup_id).toBeUndefined();+});++it("sends a scoped enable request without rewriting the configuration", async () => {+ const fetcher = vi.fn().mockResolvedValue(new Response("{}"));+ vi.stubGlobal("fetch", fetcher);+ await client.enableIssueWakeup("issue", "wake", {+ revision: 2,+ rearm: true,+ at: "2099-01-01T00:00:00Z",+ });+ const [url, init] = fetcher.mock.calls[0]!;+ expect(url).toContain("/api/issues/issue/wakeups/wake/enable");+ expect(init.method).toBe("POST");+ expect(JSON.parse(init.body)).toEqual({+ revision: 2,+ rearm: true,+ at: "2099-01-01T00:00:00Z",+ });+});+it("surfaces a stale enable refusal instead of reporting success", async () => {+ vi.stubGlobal(+ "fetch",+ vi+ .fn()+ .mockResolvedValue(+ new Response('{"error":"wakeup changed"}', { status: 409 }),+ ),+ );+ await expect(+ client.enableIssueWakeup("issue", "wake", { revision: 1 }),+ ).rejects.toThrow();+});++it("preserves actor filters and accepts older responses without them", async () => {+ const rule = {+ id: "wake", issue_id: "issue", agent_id: "agent", agent_name: "Emacs",+ instruction: "wait", kind: "event", mode: "once", event_types: ["comment.created"],+ filter_agent_id: null, filter_task_id: null, interval_seconds: null,+ cron_expression: null, timezone: "UTC", next_fire_at: null, enabled: true,+ disabled_at: null, last_task_id: null, last_error: null,+ };+ for (const fields of [{}, { filter_actor_type: "member", filter_actor_id: "user", filter_actor_name: "Jiayuan" }, { filter_actor_type: "agent", filter_actor_id: null, filter_actor_name: null }]) {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify([{ ...rule, ...fields }]))));+ await expect(client.listIssueWakeups("issue")).resolves.toEqual([{ ...rule, ...fields }]);+ }+ for (const fields of [{ filter_actor_type: 42 }, { filter_actor_type: "robot" }, { filter_actor_id: 42 }, { filter_actor_name: 42 }]) {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify([{ ...rule, ...fields }]))));+ await expect(client.listIssueWakeups("issue")).rejects.toThrow("Could not load wakeups");+ }+});++it("edits instructions through the scoped endpoint and propagates conflicts", async () => {+ const fetch = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));+ vi.stubGlobal("fetch", fetch);+ const input = { instruction: "new", expected_instruction: "old", revision: 2 };+ await client.editIssueWakeupInstruction("issue", "wake", input);+ expect(fetch.mock.calls[0]?.[0]).toContain("/api/issues/issue/wakeups/wake/instruction");+ expect(fetch.mock.calls[0]?.[1]).toEqual(expect.objectContaining({ method: "PATCH", body: JSON.stringify(input) }));+ fetch.mockResolvedValue(new Response('{"error":"conflict"}', { status: 409 }));+ await expect(client.editIssueWakeupInstruction("issue", "wake", input)).rejects.toThrow();+});diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 40999cf20c..523e70ae08 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -1811,6 +1811,7 @@ const TaskUsageSchema = z.object({}).loose();export const AgentTaskSchema = z.object({+ wakeup_id: z.string().optional().catch(undefined),cancelled_by_comment_change: z.boolean().optional().catch(undefined),cancelled_by: TaskCancellationActorSchema.optional().catch(undefined),id: z.string(),@@ -3490,6 +3491,41 @@ export const EMPTY_JOIN_SHARE_LINK_RESPONSE: {workspace_slug: "",};+export const IssueWakeupSchema = z.object({+ id: z.string(), issue_id: z.string(), agent_id: z.string(), agent_name: z.string().default(""),+ instruction: z.string(), kind: z.enum(["event", "at", "every", "cron"]), mode: z.enum(["once", "continuous"]),+ event_types: z.array(z.string()), filter_agent_id: z.string().nullable(), filter_task_id: z.string().nullable(),+ interval_seconds: z.number().nullable(), cron_expression: z.string().nullable(), timezone: z.string(),+ next_fire_at: z.string().nullable(), enabled: z.boolean(), disabled_at: z.string().nullable(),+ last_task_id: z.string().nullable(), last_error: z.string().nullable(),+ filter_actor_type: z.enum(["member", "agent"]).nullable().optional(),+ filter_actor_id: z.string().nullable().optional(),+ filter_actor_name: z.string().nullable().optional(),+ revision: z.number().int().positive().optional(),+ filter_agent_name: z.string().nullable().optional(), last_task_status: z.string().nullable().optional(),+});++export const IssueWakeupSummaryRowSchema = IssueWakeupSchema.pick({+ id: true, issue_id: true, agent_id: true, agent_name: true, kind: true, mode: true,+ event_types: true, filter_task_id: true, filter_agent_name: true, interval_seconds: true,+ filter_actor_type: true, filter_actor_id: true, filter_actor_name: true,+ cron_expression: true, timezone: true, next_fire_at: true,+}).extend({ active_count: z.number().int().positive(), event_count: z.number().int().nonnegative() });++export const WorkspaceWakeupPageSchema = z.object({+ items: z.array(IssueWakeupSchema.omit({ instruction: true }).extend({+ issue_title: z.string(), issue_identifier: z.string(), issue_closed: z.boolean(),+ can_manage: z.boolean(), active_runs: z.number().int().nonnegative(),+ task: AgentTaskSchema.nullable(),+ })),+ total: z.number().int().nonnegative(),+ counts: z.object({+ active: z.number().int().nonnegative(), all: z.number().int().nonnegative(),+ disabled: z.number().int().nonnegative(), ended: z.number().int().nonnegative(),+ }),+ agents: z.array(z.object({ id: z.string(), name: z.string() })),+});+// Older servers omit runtime_type; the protocol remains their compatibility target.export const RuntimeProfileSchema = z.object({diff --git a/packages/core/issues/index.ts b/packages/core/issues/index.tsindex 21030fb925..e26ef2d778 100644--- a/packages/core/issues/index.ts+++ b/packages/core/issues/index.ts@@ -19,3 +19,4 @@ export {type StatusFilterColumnsResult,normalizeStatusPatch,} from "./status-category";+export * from "./wakeups";diff --git a/packages/core/issues/wakeups.ts b/packages/core/issues/wakeups.tsnew file mode 100644index 0000000000..f8b42452c8--- /dev/null+++ b/packages/core/issues/wakeups.ts@@ -0,0 +1,134 @@+import {+ queryOptions,+ useMutation,+ useQueryClient,+} from "@tanstack/react-query";+import type { WorkspaceWakeupFilters } from "../types";+import { api } from "../api";+import { issueKeys } from "./queries";++export function workspaceWakeupSummariesOptions(workspaceId: string) {+ return queryOptions({+ queryKey: ["issue-wakeup-summaries", workspaceId],+ queryFn: () => api.listIssueWakeupSummaries(),+ enabled: !!workspaceId,+ staleTime: 10_000,+ });+}++export function issueWakeupsOptions(workspaceId: string, issueId: string) {+ return queryOptions({+ queryKey: ["issue-wakeups", workspaceId, issueId],+ queryFn: () => api.listIssueWakeups(issueId),+ enabled: !!workspaceId && !!issueId,+ refetchInterval: 10_000,+ });+}++export function useDisableIssueWakeup(workspaceId: string, issueId: string) {+ const client = useQueryClient();+ return useMutation({+ mutationFn: (id: string) => api.disableIssueWakeup(issueId, id),+ onSettled: async () => {+ await Promise.all([+ client.invalidateQueries({+ queryKey: ["workspace-wakeups", workspaceId],+ }),+ client.invalidateQueries({+ queryKey: issueWakeupsOptions(workspaceId, issueId).queryKey,+ }),+ client.invalidateQueries({+ queryKey: workspaceWakeupSummariesOptions(workspaceId).queryKey,+ }),+ client.invalidateQueries({ queryKey: issueKeys.tasks(issueId) }),+ ]);+ },+ });+}++export function useEnableIssueWakeup(workspaceId: string, issueId: string) {+ const client = useQueryClient();+ return useMutation({+ mutationFn: ({+ id,+ ...input+ }: {+ id: string;+ revision: number;+ at?: string;+ rearm?: boolean;+ }) => api.enableIssueWakeup(issueId, id, input),+ onSettled: async () => {+ await Promise.all([+ client.invalidateQueries({+ queryKey: ["workspace-wakeups", workspaceId],+ }),+ client.invalidateQueries({+ queryKey: issueWakeupsOptions(workspaceId, issueId).queryKey,+ }),+ client.invalidateQueries({+ queryKey: workspaceWakeupSummariesOptions(workspaceId).queryKey,+ }),+ client.invalidateQueries({ queryKey: issueKeys.tasks(issueId) }),+ ]);+ },+ });+}++export function useEditWakeupInstruction(workspaceId: string, issueId: string) {+ const client = useQueryClient();+ return useMutation({+ mutationFn: ({ id, ...input }: { id: string; instruction: string; expected_instruction: string; revision: number }) =>+ api.editIssueWakeupInstruction(issueId, id, input),+ onSettled: async () => {+ await Promise.all([+ client.invalidateQueries({ queryKey: ["workspace-wakeups", workspaceId] }),+ client.invalidateQueries({ queryKey: issueWakeupsOptions(workspaceId, issueId).queryKey }),+ ]);+ },+ });+}++export function workspaceWakeupsOptions(+ workspaceId: string,+ filters: WorkspaceWakeupFilters,+) {+ return queryOptions({+ queryKey: ["workspace-wakeups", workspaceId, filters],+ queryFn: () => api.listWorkspaceWakeups(filters),+ enabled: !!workspaceId,+ refetchInterval: 10_000,+ });+}++export function useDisableWorkspaceWakeups(workspaceId: string) {+ const client = useQueryClient();+ return useMutation({+ mutationFn: async (rows: { id: string; issue_id: string }[]) => {+ const failed: string[] = [];+ // Sequential requests bound load and retain precise partial-failure results.+ for (const row of rows) {+ try {+ await api.disableIssueWakeup(row.issue_id, row.id);+ } catch {+ failed.push(row.id);+ }+ }+ return { failed, succeeded: rows.length - failed.length };+ },+ onSettled: async (_data, _error, rows) => {+ await Promise.all([+ client.invalidateQueries({+ queryKey: ["workspace-wakeups", workspaceId],+ }),+ client.invalidateQueries({ queryKey: ["issue-wakeups", workspaceId] }),+ client.invalidateQueries({+ queryKey: ["issue-wakeup-summaries", workspaceId],+ }),+ ...Array.from(new Set(rows.map((r) => r.issue_id))).map((id) =>+ client.invalidateQueries({ queryKey: issueKeys.tasks(id) }),+ ),+ ]);+ },+ });+}diff --git a/packages/core/package.json b/packages/core/package.jsonindex 0d73747401..09c5537723 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -37,6 +37,7 @@"./issues/batch": "./issues/batch.ts","./issues/canonical-id": "./issues/canonical-id.ts","./issues/queries": "./issues/queries.ts",+ "./issues/wakeups": "./issues/wakeups.ts","./issues/mutations": "./issues/mutations.ts","./issues/timeline-sort": "./issues/timeline-sort.ts","./issues/comment-deletion": "./issues/comment-deletion.ts",diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex c442643677..2d08f2be6f 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -298,6 +298,7 @@ export interface TaskCancellationActor {}export interface AgentTask {+ wakeup_id?: string;id: string;agent_id: string;runtime_id: string;@@ -314,6 +315,7 @@ export interface AgentTask {| "queued"| "dispatched"| "waiting_local_directory"+ | "deferred"| "running"| "completed"| "failed"diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 4c2ea20493..b936d51aca 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -333,3 +333,6 @@ export type {WorkspaceSubscriptionSeatReconcileResult,CreateWorkspaceSubscriptionPortalResponse,} from "./billing";+export type { IssueWakeup, WakeupPreview, IssueWakeupSummaryRow } from "./issue-wakeup";++export type { WorkspaceWakeup, WorkspaceWakeupPage, WorkspaceWakeupFilters, WakeupScope } from "./issue-wakeup";diff --git a/packages/core/types/issue-wakeup.ts b/packages/core/types/issue-wakeup.tsnew file mode 100644index 0000000000..af886d5aee--- /dev/null+++ b/packages/core/types/issue-wakeup.ts@@ -0,0 +1,74 @@+export interface IssueWakeup {+ id: string;+ issue_id: string;+ agent_id: string;+ agent_name: string;+ instruction: string;+ kind: "event" | "at" | "every" | "cron";+ mode: "once" | "continuous";+ event_types: string[];+ filter_agent_id: string | null;+ filter_task_id: string | null;+ filter_actor_type?: "member" | "agent" | null;+ filter_actor_id?: string | null;+ filter_actor_name?: string | null;+ interval_seconds: number | null;+ cron_expression: string | null;+ timezone: string;+ next_fire_at: string | null;+ enabled: boolean;+ revision?: number;+ disabled_at: string | null;+ last_task_id: string | null;+ last_error: string | null;+ filter_agent_name?: string | null;+ last_task_status?: string | null;+}++export type WakeupPreview = Pick<+ IssueWakeup,+ | "id"+ | "issue_id"+ | "agent_id"+ | "agent_name"+ | "kind"+ | "mode"+ | "event_types"+ | "filter_task_id"+ | "filter_agent_name"+ | "filter_actor_type"+ | "filter_actor_id"+ | "filter_actor_name"+ | "interval_seconds"+ | "cron_expression"+ | "timezone"+ | "next_fire_at"+>;+export interface IssueWakeupSummaryRow extends WakeupPreview {+ active_count: number;+ event_count: number;+}++export type WakeupScope = "active" | "all" | "disabled" | "ended";+export interface WorkspaceWakeup extends Omit<IssueWakeup, "instruction"> {+ issue_title: string;+ issue_identifier: string;+ issue_closed: boolean;+ can_manage: boolean;+ active_runs: number;+ task: import("./agent").AgentTask | null;+}+export interface WorkspaceWakeupPage {+ items: WorkspaceWakeup[];+ total: number;+ counts: Record<WakeupScope, number>;+ agents: { id: string; name: string }[];+}+export interface WorkspaceWakeupFilters {+ scope: WakeupScope;+ kind: "all" | "event" | "at" | "recurring";+ search: string;+ agent_id: string;+ offset: number;+ limit: number;+}diff --git a/packages/views/agents/components/agent-activity-hover-content.tsx b/packages/views/agents/components/agent-activity-hover-content.tsxindex d8a53b358d..aa2f1fd893 100644--- a/packages/views/agents/components/agent-activity-hover-content.tsx+++ b/packages/views/agents/components/agent-activity-hover-content.tsx@@ -1,6 +1,7 @@"use client";import { useEffect, useState } from "react";+import { Bell } from "lucide-react";import { useQuery } from "@tanstack/react-query";import { ActorAvatar as ActorAvatarBase } from "@multica/ui/components/common/actor-avatar";import { useActorName } from "@multica/core/workspace/hooks";@@ -111,6 +112,7 @@ function AgentActivityTaskRow({<span className="flex-1 truncate font-medium">{getActorName("agent", task.agent_id)}</span>+ {task.wakeup_id && <Bell className="size-3 shrink-0 text-muted-foreground" aria-label={t(($) => $.wakeups.triggered_by_wakeup)} />}<span className="flex shrink-0 items-center gap-1.5"><span className={`h-1.5 w-1.5 rounded-full ${dotClass}`} /><span className={labelClass}>diff --git a/packages/views/agents/components/tabs/activity-tab.tsx b/packages/views/agents/components/tabs/activity-tab.tsxindex d618898edf..b1d8847cab 100644--- a/packages/views/agents/components/tabs/activity-tab.tsx+++ b/packages/views/agents/components/tabs/activity-tab.tsx@@ -831,6 +831,7 @@ type TimeAgoFn = (dateStr: string) => string;function taskStatusLabel(status: AgentTask["status"], t: AgentsT): string {switch (status) {case "queued":+ case "deferred":return t(($) => $.tab_body.activity.status.queued);case "dispatched":return t(($) => $.tab_body.activity.status.dispatched);diff --git a/packages/views/autopilots/components/autopilots-page.test.tsx b/packages/views/autopilots/components/autopilots-page.test.tsxnew file mode 100644index 0000000000..f1187b1828--- /dev/null+++ b/packages/views/autopilots/components/autopilots-page.test.tsx@@ -0,0 +1,69 @@+import { useState } from "react";+import { expect, it, vi } from "vitest";+import { fireEvent, screen } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { api } from "@multica/core/api";+import { NavigationProvider } from "../../navigation";+import { renderWithI18n } from "../../test/i18n";+import { AutopilotsPage } from "./autopilots-page";++vi.mock("@multica/core/api", () => ({ api: { listAutopilots: vi.fn() } }));+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws" }));+vi.mock("@multica/core/paths", () => ({+ useWorkspacePaths: () => ({ autopilots: () => "/ws/autopilots" }),+}));+vi.mock("./workspace-wakeups", () => ({+ WorkspaceWakeups: () => <div>Wakeup inventory</div>,+}));+vi.mock("./autopilot-dialog", () => ({ AutopilotDialog: () => null }));++function Harness() {+ const [path, setPath] = useState("/ws/autopilots?keep=yes");+ const url = new URL(path, "https://example.test");+ return (+ <NavigationProvider+ value={{+ pathname: url.pathname,+ searchParams: url.searchParams,+ hash: "",+ push: setPath,+ replace: setPath,+ back: () => {},+ getShareableUrl: (v) => v,+ }}+ >+ <AutopilotsPage />+ </NavigationProvider>+ );+}+it.each(["empty", "error"])(+ "keeps wakeups reachable when autopilots are %s",+ async (state) => {+ if (state === "empty")+ vi.mocked(api.listAutopilots).mockResolvedValue({ autopilots: [], total: 0 });+ else+ vi.mocked(api.listAutopilots).mockRejectedValue(+ new Error("Autopilots unavailable"),+ );+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ renderWithI18n(+ <QueryClientProvider client={client}>+ <Harness />+ </QueryClientProvider>,+ );+ await screen.findByText(+ state === "empty" ? "No autopilots yet" : "Autopilots unavailable",+ );+ fireEvent.click(screen.getByRole("tab", { name: "Issue wakeups" }));+ expect(await screen.findByText("Wakeup inventory")).toBeVisible();+ expect(screen.queryByRole("button", { name: "New autopilot" })).toBeNull();+ fireEvent.click(+ screen.getByRole("tab", { name: "Autopilot" }),+ );+ expect(+ await screen.findByRole("button", { name: "New autopilot" }),+ ).toBeVisible();+ },+);diff --git a/packages/views/autopilots/components/autopilots-page.tsx b/packages/views/autopilots/components/autopilots-page.tsxindex 8e587e3042..a773dadb12 100644--- a/packages/views/autopilots/components/autopilots-page.tsx+++ b/packages/views/autopilots/components/autopilots-page.tsx@@ -44,7 +44,14 @@ import {type ListGridSortDirection,} from "@multica/ui/components/ui/list-grid";import { Skeleton } from "@multica/ui/components/ui/skeleton";-import { useRowLink } from "../../navigation";+import {+ Tabs,+ TabsList,+ TabsTrigger,+ TabsContent,+} from "@multica/ui/components/ui/tabs";+import { WorkspaceWakeups } from "./workspace-wakeups";+import { useNavigation, useRowLink } from "../../navigation";import { ActorAvatar } from "../../common/actor-avatar";import { formatInTimeZone } from "../../common/format-in-time-zone";import {@@ -53,7 +60,10 @@ import {CollectionPageState,} from "../../layout/collection-page";import { AutopilotDialog } from "./autopilot-dialog";-import { AutopilotListToolbar, actorFilterValue } from "./autopilot-list-toolbar";+import {+ AutopilotListToolbar,+ actorFilterValue,+} from "./autopilot-list-toolbar";import {AutopilotBatchToolbar,AutopilotRowActions,@@ -139,7 +149,10 @@ interface AutopilotTemplate {schedule: Pick<ScheduleConfig, "time" | "days">;}-const WEEKDAYS: ScheduleConfig["days"] = { kind: "weekly", daysOfWeek: [1, 2, 3, 4, 5] };+const WEEKDAYS: ScheduleConfig["days"] = {+ kind: "weekly",+ daysOfWeek: [1, 2, 3, 4, 5],+};const MONDAY: ScheduleConfig["days"] = { kind: "weekly", daysOfWeek: [1] };const TEMPLATES: AutopilotTemplate[] = [@@ -227,7 +240,9 @@ function CheckboxCell({onToggle();}}className={`-m-1.5 flex items-center p-1.5 ${- checked ? "" : "opacity-0 transition-opacity group-hover/row:opacity-100"+ checked+ ? ""+ : "opacity-0 transition-opacity group-hover/row:opacity-100"}`}><Checkbox@@ -362,7 +377,11 @@ function LastRunCell({ autopilot }: { autopilot: Autopilot }) {return (<ListGridCell className="hidden gap-1.5 @2xl:flex"><span- title={knownStatus ? t(($) => $.run_status[knownStatus]) : status ?? undefined}+ title={+ knownStatus+ ? t(($) => $.run_status[knownStatus])+ : (status ?? undefined)+ }className={`size-1.5 shrink-0 rounded-full ${runStatusDotClass(status)}`}/><span className="whitespace-nowrap text-caption tabular-nums text-muted-foreground">@@ -397,7 +416,9 @@ function ModeCell({ autopilot }: { autopilot: Autopilot }) {: mode;return (<ListGridCell className="hidden @2xl:flex">- <span className="truncate text-caption text-muted-foreground">{label}</span>+ <span className="truncate text-caption text-muted-foreground">+ {label}+ </span></ListGridCell>);}@@ -599,6 +620,9 @@ function LoadingSkeleton() {// ---------------------------------------------------------------------------export function AutopilotsPage() {+ const navigation = useNavigation();+ const tab =+ navigation.searchParams.get("tab") === "wakeups" ? "wakeups" : "autopilots";const { t } = useT("autopilots");const locale = useLocale();const wsId = useWorkspaceId();@@ -609,7 +633,10 @@ export function AutopilotsPage() {isLoading,error: listError,refetch: refetchList,- } = useQuery(autopilotListOptions(wsId));+ } = useQuery({+ ...autopilotListOptions(wsId),+ enabled: !!wsId && tab === "autopilots",+ });const [createOpen, setCreateOpen] = useState(false);const [selectedTemplate, setSelectedTemplate] =@@ -680,7 +707,10 @@ export function AutopilotsPage() {) {return false;}- if (filters.modes.length > 0 && !filters.modes.includes(a.execution_mode)) {+ if (+ filters.modes.length > 0 &&+ !filters.modes.includes(a.execution_mode)+ ) {return false;}if (@@ -752,9 +782,7 @@ export function AutopilotsPage() {const lastVirtual = virtualItems[virtualItems.length - 1];const virtualPadding = {top: firstVirtual ? firstVirtual.start : 0,- bottom: lastVirtual- ? rowVirtualizer.getTotalSize() - lastVirtual.end- : 0,+ bottom: lastVirtual ? rowVirtualizer.getTotalSize() - lastVirtual.end : 0,};const totalCount = autopilots.length;@@ -763,222 +791,259 @@ export function AutopilotsPage() {return (// relative: positioning anchor for the batch toolbar (page-centered,// not viewport-centered).- <div className="relative flex flex-1 min-h-0 flex-col">+ <Tabs+ className="relative flex flex-1 min-h-0 flex-col gap-0"+ value={tab}+ onValueChange={(value) => {+ const params = new URLSearchParams(navigation.searchParams);+ if (value === "wakeups") params.set("tab", "wakeups");+ else params.delete("tab");+ navigation.replace(+ `${navigation.pathname}${params.size ? `?${params}` : ""}${navigation.hash}`,+ );+ }}+ >{/* Header */}<CollectionPageHeadericon={Zap}title={t(($) => $.page.title)}- count={totalCount}+ count={tab === "autopilots" ? totalCount : undefined}actions={- <CollectionPageHeaderAction- icon={Plus}- label={t(($) => $.page.new_autopilot)}- onClick={() => openCreate()}- />+ tab === "autopilots" && (+ <CollectionPageHeaderAction+ icon={Plus}+ label={t(($) => $.page.new_autopilot)}+ onClick={() => openCreate()}+ />+ )}/>- {listError ? (- <CollectionPageState- role="alert"- tone="destructive"- icon={AlertCircle}- title={- listError instanceof Error ? listError.message : String(listError)- }- actions={+ <div className="shrink-0 border-b px-4 py-1">+ <TabsList variant="line" aria-label={t(($) => $.page.title)}>+ <TabsTrigger value="autopilots">{t(($) => $.page.title)}</TabsTrigger>+ <TabsTrigger value="wakeups">{t(($) => $.wakeups.title)}</TabsTrigger>+ </TabsList>+ </div>+ <TabsContent+ value="wakeups"+ className="flex min-h-0 flex-col data-hidden:hidden"+ >+ <WorkspaceWakeups key={wsId} />+ </TabsContent>+ <TabsContent+ value="autopilots"+ className="flex min-h-0 flex-col data-hidden:hidden"+ >+ {listError ? (+ <CollectionPageState+ role="alert"+ tone="destructive"+ icon={AlertCircle}+ title={+ listError instanceof Error ? listError.message : String(listError)+ }+ actions={+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => refetchList()}+ >+ {t(($) => $.page.retry)}+ </Button>+ }+ />+ ) : isLoading ? (+ <div className="flex-1 overflow-y-auto @container">+ <LoadingSkeleton />+ </div>+ ) : showEmpty ? (+ <div className="flex flex-col items-center px-5 py-16">+ <Zap className="mb-3 h-10 w-10 text-faint-foreground" />+ <p className="text-body text-muted-foreground">+ {t(($) => $.page.empty.title)}+ </p>+ <p className="mb-6 mt-1 text-caption text-muted-foreground">+ {t(($) => $.page.empty.hint)}+ </p>+ <div className="grid w-full max-w-3xl grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">+ {TEMPLATES.map((tpl) => {+ const Icon = tpl.icon;+ return (+ <button+ key={tpl.id}+ type="button"+ className="flex items-start gap-3 rounded-lg border p-3 text-left transition-colors hover:bg-accent/40"+ onClick={() => openCreate(tpl)}+ >+ <Icon className="mt-0.5 h-5 w-5 shrink-0 text-muted-foreground" />+ <div className="min-w-0">+ <div className="text-body font-medium">+ {t(($) => $.templates[tpl.id].title)}+ </div>+ <div className="mt-0.5 line-clamp-2 text-caption text-muted-foreground">+ {t(($) => $.templates[tpl.id].summary)}+ </div>+ </div>+ </button>+ );+ })}+ </div><Button- type="button"- variant="outline"size="sm"- onClick={() => refetchList()}+ variant="outline"+ className="mt-4"+ onClick={() => openCreate()}>- {t(($) => $.page.retry)}+ <Plus className="mr-1 h-3.5 w-3.5" />+ {t(($) => $.page.start_blank)}</Button>- }- />- ) : isLoading ? (- <div className="flex-1 overflow-y-auto @container">- <LoadingSkeleton />- </div>- ) : showEmpty ? (- <div className="flex flex-col items-center px-5 py-16">- <Zap className="mb-3 h-10 w-10 text-faint-foreground" />- <p className="text-body text-muted-foreground">- {t(($) => $.page.empty.title)}- </p>- <p className="mb-6 mt-1 text-caption text-muted-foreground">- {t(($) => $.page.empty.hint)}- </p>- <div className="grid w-full max-w-3xl grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">- {TEMPLATES.map((tpl) => {- const Icon = tpl.icon;- return (- <button- key={tpl.id}- type="button"- className="flex items-start gap-3 rounded-lg border p-3 text-left transition-colors hover:bg-accent/40"- onClick={() => openCreate(tpl)}- >- <Icon className="mt-0.5 h-5 w-5 shrink-0 text-muted-foreground" />- <div className="min-w-0">- <div className="text-body font-medium">- {t(($) => $.templates[tpl.id].title)}- </div>- <div className="mt-0.5 line-clamp-2 text-caption text-muted-foreground">- {t(($) => $.templates[tpl.id].summary)}- </div>- </div>- </button>- );- })}</div>- <Button- size="sm"- variant="outline"- className="mt-4"- onClick={() => openCreate()}- >- <Plus className="mr-1 h-3.5 w-3.5" />- {t(($) => $.page.start_blank)}- </Button>- </div>- ) : (- <>- <AutopilotListToolbar- scope={scope}- onScopeChange={setScope}- scopeCounts={scopeCounts}- filters={filters}- onToggleFilter={toggleFilter}- onClearFilters={clearFilters}- sortField={sortField}- sortDirection={sortDirection}- onSortFieldChange={handleSortFieldSelect}- onSortDirectionChange={setSortDirection}- hiddenColumns={hiddenColumns}- onToggleColumn={toggleColumn}- allRows={scopeRows}- visibleCount={rows.length}- />- <div- ref={listScrollRef}- className="min-h-0 flex-1 overflow-auto @container"- >- <ListGrid- className={`${GRID_COLS} @2xl:min-w-[var(--apc-minw)]`}- style={columnTrackVars(isColVisible)}+ ) : (+ <>+ <AutopilotListToolbar+ scope={scope}+ onScopeChange={setScope}+ scopeCounts={scopeCounts}+ filters={filters}+ onToggleFilter={toggleFilter}+ onClearFilters={clearFilters}+ sortField={sortField}+ sortDirection={sortDirection}+ onSortFieldChange={handleSortFieldSelect}+ onSortDirectionChange={setSortDirection}+ hiddenColumns={hiddenColumns}+ onToggleColumn={toggleColumn}+ allRows={scopeRows}+ visibleCount={rows.length}+ />+ <div+ ref={listScrollRef}+ className="min-h-0 flex-1 overflow-auto @container">- <AutopilotListHeader- sortField={sortField}- sortDirection={sortDirection}- onSort={handleSort}- allSelected={allSelected}- someSelected={someSelected}- onToggleAll={handleToggleAll}- isColVisible={isColVisible}- />- <ListGridBody- style={{- paddingTop: virtualPadding.top,- paddingBottom:- virtualPadding.bottom + LIST_GRID_BOTTOM_CLEARANCE,- }}+ <ListGrid+ className={`${GRID_COLS} @2xl:min-w-[var(--apc-minw)]`}+ style={columnTrackVars(isColVisible)}>- {rows.length === 0 && (- <div className="col-span-full py-16 text-center text-body text-muted-foreground">- {t(($) => $.page.no_matches)}- </div>- )}- {virtualItems.map((vi) => {- const autopilot = rows[vi.index];- if (!autopilot) return null;- return (- <ListGridRow- key={autopilot.id}- className={`cursor-pointer ${- selectedIds.has(autopilot.id) ? "bg-accent/30" : ""- }`}- {...rowLink(wsPaths.autopilotDetail(autopilot.id), autopilot.title)}- >- <CheckboxCell- checked={selectedIds.has(autopilot.id)}- onToggle={() => toggleSelected(autopilot.id)}- />- <NameCell autopilot={autopilot} />- {isColVisible("assignee") ? (- <AssigneeCell autopilot={autopilot} />- ) : (- <ListGridCell className="px-0" />- )}- {isColVisible("trigger") ? (- <TriggerCell autopilot={autopilot} />- ) : (- <ListGridCell className="hidden px-0 @2xl:flex" />- )}- {isColVisible("lastRun") ? (- <LastRunCell autopilot={autopilot} />- ) : (- <ListGridCell className="hidden px-0 @2xl:flex" />- )}- {isColVisible("nextRun") ? (- <NextRunCell autopilot={autopilot} />- ) : (- <ListGridCell className="hidden px-0 @2xl:flex" />- )}- {isColVisible("mode") ? (- <ModeCell autopilot={autopilot} />- ) : (- <ListGridCell className="hidden px-0 @2xl:flex" />- )}- {isColVisible("creator") ? (- <CreatorCell autopilot={autopilot} />- ) : (- <ListGridCell className="hidden px-0 @2xl:flex" />- )}- {isColVisible("created") ? (- <ListGridCell className="hidden whitespace-nowrap text-caption tabular-nums text-muted-foreground @2xl:flex">- {new Date(autopilot.created_at).toLocaleDateString(locale)}+ <AutopilotListHeader+ sortField={sortField}+ sortDirection={sortDirection}+ onSort={handleSort}+ allSelected={allSelected}+ someSelected={someSelected}+ onToggleAll={handleToggleAll}+ isColVisible={isColVisible}+ />+ <ListGridBody+ style={{+ paddingTop: virtualPadding.top,+ paddingBottom:+ virtualPadding.bottom + LIST_GRID_BOTTOM_CLEARANCE,+ }}+ >+ {rows.length === 0 && (+ <div className="col-span-full py-16 text-center text-body text-muted-foreground">+ {t(($) => $.page.no_matches)}+ </div>+ )}+ {virtualItems.map((vi) => {+ const autopilot = rows[vi.index];+ if (!autopilot) return null;+ return (+ <ListGridRow+ key={autopilot.id}+ className={`cursor-pointer ${+ selectedIds.has(autopilot.id) ? "bg-accent/30" : ""+ }`}+ {...rowLink(+ wsPaths.autopilotDetail(autopilot.id),+ autopilot.title,+ )}+ >+ <CheckboxCell+ checked={selectedIds.has(autopilot.id)}+ onToggle={() => toggleSelected(autopilot.id)}+ />+ <NameCell autopilot={autopilot} />+ {isColVisible("assignee") ? (+ <AssigneeCell autopilot={autopilot} />+ ) : (+ <ListGridCell className="px-0" />+ )}+ {isColVisible("trigger") ? (+ <TriggerCell autopilot={autopilot} />+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("lastRun") ? (+ <LastRunCell autopilot={autopilot} />+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("nextRun") ? (+ <NextRunCell autopilot={autopilot} />+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("mode") ? (+ <ModeCell autopilot={autopilot} />+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("creator") ? (+ <CreatorCell autopilot={autopilot} />+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("created") ? (+ <ListGridCell className="hidden whitespace-nowrap text-caption tabular-nums text-muted-foreground @2xl:flex">+ {new Date(autopilot.created_at).toLocaleDateString(+ locale,+ )}+ </ListGridCell>+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ <ListGridCell className="justify-end px-0">+ <AutopilotRowActions row={autopilot} /></ListGridCell>- ) : (- <ListGridCell className="hidden px-0 @2xl:flex" />- )}- <ListGridCell className="justify-end px-0">- <AutopilotRowActions row={autopilot} />- </ListGridCell>- </ListGridRow>- );- })}- </ListGridBody>- </ListGrid>- </div>- </>- )}-- <AutopilotBatchToolbar- rows={selectedRows}- onClear={() => setSelectedIds(new Set())}- />+ </ListGridRow>+ );+ })}+ </ListGridBody>+ </ListGrid>+ </div>+ </>+ )}- {createOpen && (- <AutopilotDialog- mode="create"- open={createOpen}- onOpenChange={setCreateOpen}- initial={- selectedTemplate- ? {- // Template title pulls from i18n so the user-visible default- // matches their locale, while the prompt body stays raw EN- // since it's injected directly into the agent task.- title: t(($) => $.templates[selectedTemplate.id].title),- description: selectedTemplate.prompt,- }- : undefined- }- initialSchedule={selectedTemplate ? selectedTemplate.schedule : undefined}+ <AutopilotBatchToolbar+ rows={selectedRows}+ onClear={() => setSelectedIds(new Set())}/>- )}- </div>++ {createOpen && (+ <AutopilotDialog+ mode="create"+ open={createOpen}+ onOpenChange={setCreateOpen}+ initial={+ selectedTemplate+ ? {+ // Template title pulls from i18n so the user-visible default+ // matches their locale, while the prompt body stays raw EN+ // since it's injected directly into the agent task.+ title: t(($) => $.templates[selectedTemplate.id].title),+ description: selectedTemplate.prompt,+ }+ : undefined+ }+ initialSchedule={+ selectedTemplate ? selectedTemplate.schedule : undefined+ }+ />+ )}+ </TabsContent>+ </Tabs>);}diff --git a/packages/views/autopilots/components/workspace-wakeups.test.tsx b/packages/views/autopilots/components/workspace-wakeups.test.tsxnew file mode 100644index 0000000000..696162fe20--- /dev/null+++ b/packages/views/autopilots/components/workspace-wakeups.test.tsx@@ -0,0 +1,243 @@+import { beforeEach, expect, it, vi } from "vitest";+import { fireEvent, screen, waitFor, within } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { ReactNode } from "react";+import { api } from "@multica/core/api";+import type {+ WorkspaceWakeup,+ WorkspaceWakeupFilters,+} from "@multica/core/types";+import { renderWithI18n } from "../../test/i18n";+import { WorkspaceWakeups } from "./workspace-wakeups";++vi.mock("@multica/core/api", () => ({+ api: {+ listWorkspaceWakeups: vi.fn(),+ disableIssueWakeup: vi.fn(),+ enableIssueWakeup: vi.fn(),+ listIssueWakeups: vi.fn(),+ editIssueWakeupInstruction: vi.fn(),+ },+}));++vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws" }));+vi.mock("@multica/core/paths", () => ({+ useWorkspacePaths: () => ({+ issueDetail: (id: string) => `/ws/issues/${id}`,+ }),+}));+vi.mock("../../navigation", () => ({+ AppLink: ({+ href,+ children,+ ...props+ }: {+ href: string;+ children: ReactNode;+ }) => (+ <a href={href} {...props}>+ {children}+ </a>+ ),+}));+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));+vi.mock("../../common/task-transcript", () => ({+ TranscriptButton: () => <button>Transcript</button>,+}));++let rows: WorkspaceWakeup[];+let queries: WorkspaceWakeupFilters[];+const list = vi.mocked(api.listWorkspaceWakeups);+const disable = vi.mocked(api.disableIssueWakeup);+const enable = vi.mocked(api.enableIssueWakeup);+function mount() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ return renderWithI18n(+ <QueryClientProvider client={client}>+ <WorkspaceWakeups />+ </QueryClientProvider>,+ );+}+beforeEach(() => {+ queries = [];+ rows = ["a", "b"].map((id) => ({+ id,+ issue_id: `issue-${id}`,+ issue_identifier: `DEV-${id}`,+ issue_title: `Issue ${id}`,+ issue_closed: false,+ agent_id: id,+ agent_name: `Agent ${id}`,+ can_manage: true,+ active_runs: 0,+ task: null,+ kind: "event",+ mode: "continuous",+ event_types: ["task.completed"],+ filter_agent_id: null,+ filter_task_id: null,+ interval_seconds: null,+ cron_expression: null,+ timezone: "UTC",+ next_fire_at: null,+ enabled: true,+ revision: 1,+ disabled_at: null,+ last_task_id: null,+ last_error: null,+ }));+ list.mockReset().mockImplementation(async (filters) => {+ queries.push(filters);+ return {+ items: rows,+ total: 60,+ counts: { all: 60, active: 58, disabled: 1, ended: 1 },+ agents: [+ { id: "a", name: "Agent a" },+ { id: "b", name: "Agent b" },+ ],+ };+ });+ disable.mockReset().mockResolvedValue(undefined);+ enable.mockReset().mockResolvedValue(undefined);+});++it("shows consumed running work separately from its off state and keeps transcript access", async () => {+ rows[0] = {+ ...rows[0]!,+ enabled: false,+ mode: "once",+ last_task_id: "run",+ active_runs: 1,+ task: {+ id: "run",+ agent_id: "a",+ issue_id: "issue-a",+ runtime_id: "runtime",+ status: "running",+ priority: 0,+ created_at: new Date().toISOString(),+ started_at: new Date().toISOString(),+ dispatched_at: null,+ completed_at: null,+ result: null,+ error: null,+ },+ };+ mount();+ const row = await screen.findByRole("row", { name: /Issue a/ });+ expect(within(row).getByText("Running")).toBeVisible();+ expect(within(row).getByText("Triggered")).toBeVisible();+ expect(within(row).queryByText("Completed")).toBeNull();+ expect(within(row).getByRole("button", { name: "Transcript" })).toBeVisible();+ expect(+ within(row).getByRole("button", { name: "Enable again" }),+ ).toBeDisabled();+ expect(within(row).getByRole("checkbox")).toHaveAttribute(+ "aria-disabled",+ "true",+ );+ expect(within(row).getByRole("link", { name: /Issue a/ })).toHaveAttribute(+ "href",+ "/ws/issues/issue-a",+ );+});++it("confirms batch consequences and retains only failed selections for retry", async () => {+ disable.mockImplementation(async (_issue, id) => {+ if (id === "b") throw new Error("forbidden");+ });+ mount();+ await screen.findByText("Issue a");+ fireEvent.click(+ screen.getByRole("checkbox", {+ name: "Select enabled wakeups on this page",+ }),+ );+ fireEvent.click(screen.getByRole("button", { name: "Turn off selected" }));+ expect(+ screen.getByText(/Dispatched runs will continue/),+ ).toBeVisible();+ expect(disable).not.toHaveBeenCalled();+ fireEvent.click(+ screen.getByRole("button", { name: "Turn off" }),+ );+ await screen.findByText("Turned off 1; 1 failed. Failed items remain selected for retry.");+ expect(disable.mock.calls).toEqual([+ ["issue-a", "a"],+ ["issue-b", "b"],+ ]);+ expect(+ screen.getByRole("checkbox", { name: "Select DEV-a, Agent a" }),+ ).not.toBeChecked();+ expect(+ screen.getByRole("checkbox", { name: "Select DEV-b, Agent b" }),+ ).toBeChecked();+});++it("resets page and selection on scope or search changes and sends bounded page requests", async () => {+ mount();+ await screen.findByText("Issue a");+ fireEvent.click(screen.getByRole("button", { name: "Next" }));+ await waitFor(() => expect(queries.at(-1)?.offset).toBe(50));+ await screen.findByText("Issue a");+ fireEvent.click(+ screen.getByRole("checkbox", { name: "Select DEV-a, Agent a" }),+ );+ fireEvent.click(screen.getByRole("button", { name: /^All\s*60/ }));+ await waitFor(() =>+ expect(queries.at(-1)).toMatchObject({+ scope: "all",+ offset: 0,+ limit: 50,+ }),+ );+ expect(+ screen.queryByRole("button", { name: "Turn off selected" }),+ ).toBeNull();+ fireEvent.change(screen.getByRole("searchbox"), {+ target: { value: "CI & release" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Search" }));+ await waitFor(() => expect(queries.at(-1)?.search).toBe("CI & release"));+});++it("makes read-only rules non-selectable and surfaces inventory failures", async () => {+ rows[0]!.can_manage = false;+ const view = mount();+ await screen.findByText("Issue a");+ expect(+ screen.getByRole("checkbox", { name: "Select DEV-a, Agent a" }),+ ).toHaveAttribute("aria-disabled", "true");+ expect(+ screen.getByRole("switch", { name: "Wakeup for Agent a" }),+ ).toHaveAttribute("aria-disabled", "true");+ view.unmount();+ list.mockRejectedValue(new Error("offline"));+ mount();+ expect(await screen.findByRole("alert")).toHaveTextContent(+ "Could not load wakeups",+ );+ expect(screen.getByRole("button", { name: "Retry" })).toBeEnabled();+});+++it("opens the shared prompt editor from a manageable row without loading all prompts", async () => {+ const [first, second] = rows;+ if (!first || !second) throw new Error("Missing wakeup fixtures");+ vi.mocked(api.listIssueWakeups).mockResolvedValue([{ ...first, instruction: "Inspect the result" }]);+ vi.mocked(api.editIssueWakeupInstruction).mockResolvedValue(undefined);+ second.can_manage = false;+ mount();+ const buttons = await screen.findAllByRole("button", { name: "Edit prompt" });+ expect(buttons[1]).toBeDisabled();+ expect(api.listIssueWakeups).not.toHaveBeenCalled();+ if (!buttons[0]) throw new Error("Missing edit button");+ fireEvent.click(buttons[0]);+ const input = await screen.findByRole("textbox", { name: "What to do when woken" });+ fireEvent.change(input, { target: { value: "Inspect and summarize" } });+ fireEvent.click(screen.getByRole("button", { name: "Save" }));+ await waitFor(() => expect(api.editIssueWakeupInstruction).toHaveBeenCalledWith("issue-a", "a", { instruction: "Inspect and summarize", expected_instruction: "Inspect the result", revision: 1 }));+});diff --git a/packages/views/autopilots/components/workspace-wakeups.tsx b/packages/views/autopilots/components/workspace-wakeups.tsxnew file mode 100644index 0000000000..410c7f5fa8--- /dev/null+++ b/packages/views/autopilots/components/workspace-wakeups.tsx@@ -0,0 +1,614 @@+"use client";++import { useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { Bell, Clock3, AlertCircle } from "lucide-react";+import { toast } from "sonner";+import { useWorkspaceId } from "@multica/core/hooks";+import { useWorkspacePaths } from "@multica/core/paths";+import {+ workspaceWakeupsOptions,+ useDisableWorkspaceWakeups,+ useDisableIssueWakeup,+ useEnableIssueWakeup,+} from "@multica/core/issues/wakeups";+import type {+ WorkspaceWakeup,+ WorkspaceWakeupFilters,+} from "@multica/core/types";+import { Button } from "@multica/ui/components/ui/button";+import { Checkbox } from "@multica/ui/components/ui/checkbox";+import { Input } from "@multica/ui/components/ui/input";+import {+ Select,+ SelectTrigger,+ SelectValue,+ SelectContent,+ SelectItem,+} from "@multica/ui/components/ui/select";+import {+ Table,+ TableHeader,+ TableHead,+ TableBody,+ TableRow,+ TableCell,+} from "@multica/ui/components/ui/table";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogFooter,+} from "@multica/ui/components/ui/dialog";+import { AppLink } from "../../navigation";+import { useLocale, useT, useTimeAgo } from "../../i18n";+import { CollectionPageState } from "../../layout/collection-page";+import { ActorAvatar } from "../../common/actor-avatar";+import { TranscriptButton } from "../../common/task-transcript";+import { WakeupInstructionEditor } from "../../issues/components/wakeup-instruction-editor";+import { WakeupControl } from "../../issues/components/wakeup-control";+import {+ isActiveWakeupRun,+ useWakeupText,+} from "../../issues/components/wakeup-presentation";++function WakeupListRow({+ row,+ selected,+ onSelect,+ busy,+}: {+ row: WorkspaceWakeup;+ selected: boolean;+ onSelect: () => void;+ busy: boolean;+}) {+ const { t } = useT("autopilots");+ const { t: ti } = useT("issues");+ const wsId = useWorkspaceId();+ const paths = useWorkspacePaths();+ const locale = useLocale();+ const timeAgo = useTimeAgo();+ const text = useWakeupText();+ const disable = useDisableIssueWakeup(wsId, row.issue_id);+ const enable = useEnableIssueWakeup(wsId, row.issue_id);+ const Icon = row.kind === "event" ? Bell : Clock3;+ const next = text.state(row, row.issue_closed);+ const status = row.task?.status;+ return (+ <TableRow data-state={selected ? "selected" : undefined}>+ <TableCell className="w-10 pl-4">+ <Checkbox+ checked={selected}+ onCheckedChange={onSelect}+ disabled={busy || !row.can_manage || !row.enabled}+ aria-label={t(($) => $.wakeups.select_row, {+ issue: row.issue_identifier,+ agent: row.agent_name,+ })}+ />+ </TableCell>+ <TableCell className="max-w-72">+ <AppLink+ href={paths.issueDetail(row.issue_id)}+ className="block rounded-sm focus-visible:outline-2 focus-visible:outline-ring"+ >+ <span className="block truncate font-medium" title={row.issue_title}>+ {row.issue_title}+ </span>+ <span className="text-caption text-muted-foreground">+ {row.issue_identifier}+ </span>+ </AppLink>+ </TableCell>+ <TableCell className="max-w-44">+ <span className="flex items-center gap-2">+ <ActorAvatar+ actorType="agent"+ actorId={row.agent_id}+ name={row.agent_name}+ size="sm"+ />+ <span className="truncate">{row.agent_name}</span>+ </span>+ </TableCell>+ <TableCell className="max-w-64">+ <span+ className="flex items-center gap-1.5"+ title={row.event_types+ .map((event) =>+ text.eventCondition(event, row),+ )+ .join(", ")}+ >+ <Icon className="size-3.5 shrink-0 text-muted-foreground" />+ <span className="line-clamp-2 break-words">{text.trigger(row)}</span>+ </span>+ <span className="block truncate text-caption text-muted-foreground">+ {row.kind === "event" ? text.frequency(row) : row.timezone}+ </span>+ </TableCell>+ <TableCell className="max-w-48">+ <span+ className="block truncate"+ title={+ row.next_fire_at && row.enabled+ ? `${new Date(row.next_fire_at).toLocaleString(locale, { timeZone: row.timezone })} · ${row.timezone}`+ : undefined+ }+ >+ {next}+ </span>+ {row.last_error && (+ <AppLink+ href={paths.issueDetail(row.issue_id)}+ className="text-caption text-destructive"+ >+ {ti(($) => $.wakeups.needs_attention)}+ </AppLink>+ )}+ </TableCell>+ <TableCell>+ {row.task ? (+ <div className="flex items-center gap-1">+ <div>+ <span+ className={+ isActiveWakeupRun(status)+ ? "text-primary"+ : "text-muted-foreground"+ }+ >+ {text.runState(status)}+ </span>+ <span className="block text-caption text-muted-foreground">+ {row.active_runs > 1+ ? t(($) => $.wakeups.active_runs, { count: row.active_runs })+ : timeAgo(+ row.task.completed_at ??+ row.task.started_at ??+ row.task.created_at,+ )}+ </span>+ </div>+ <TranscriptButton+ task={row.task}+ agentName={row.agent_name}+ title={ti(($) => $.wakeups.last_run)}+ isLive={isActiveWakeupRun(status)}+ />+ </div>+ ) : (+ <span className="text-muted-foreground">{text.runState()}</span>+ )}+ </TableCell>+ <TableCell className="w-px">+ <div+ className="flex items-center justify-end"+ title={+ !row.can_manage+ ? t(($) => $.wakeups.read_only)+ : row.issue_closed+ ? ti(($) => $.wakeups.closed_hint)+ : undefined+ }+ >+ <WakeupControl+ wakeup={row}+ task={row.task ?? undefined}+ closed={row.issue_closed}+ pending={+ busy || !row.can_manage || disable.isPending || enable.isPending+ }+ onDisable={() =>+ disable.mutate(row.id, {+ onError: (err) =>+ toast.error(+ text.error(+ err,+ ti(($) => $.wakeups.disable_error),+ ),+ ),+ })+ }+ onEnable={async (input = {}) => {+ await enable.mutateAsync({+ id: row.id,+ revision: row.revision ?? 0,+ ...input,+ });+ }}+ />+ </div>+ </TableCell>+ <TableCell className="w-px pl-0 pr-4">+ <WakeupInstructionEditor+ workspaceId={wsId}+ issueId={row.issue_id}+ wakeupId={row.id}+ disabled={busy || !row.can_manage}+ triggerStyle="icon"+ />+ </TableCell>+ </TableRow>+ );+}++export function WorkspaceWakeups() {+ const { t } = useT("autopilots");+ const { t: ti } = useT("issues");+ const wsId = useWorkspaceId();+ const [filters, setFilters] = useState<WorkspaceWakeupFilters>({+ scope: "active",+ kind: "all",+ search: "",+ agent_id: "",+ offset: 0,+ limit: 50,+ });+ const [search, setSearch] = useState("");+ const [selected, setSelected] = useState<Set<string>>(new Set());+ const [confirmation, setConfirmation] = useState<WorkspaceWakeup[]>([]);+ const [batchResult, setBatchResult] = useState<{+ failed: string[];+ succeeded: number;+ } | null>(null);+ const query = useQuery(workspaceWakeupsOptions(wsId, filters));+ const batch = useDisableWorkspaceWakeups(wsId);+ const rows = query.data?.items ?? [];+ const selectable = rows.filter((row) => row.enabled && row.can_manage);+ const picked = selectable.filter((row) => selected.has(row.id));+ const change = (patch: Partial<WorkspaceWakeupFilters>) => {+ setFilters((prev) => ({ ...prev, offset: 0, ...patch }));+ setSelected(new Set());+ setBatchResult(null);+ };+ const kinds = [+ { value: "all", label: t(($) => $.wakeups.all_triggers) },+ { value: "event", label: t(($) => $.wakeups.event) },+ { value: "at", label: t(($) => $.wakeups.at) },+ { value: "recurring", label: t(($) => $.wakeups.recurring) },+ ];+ const agents = [+ { value: "", label: t(($) => $.wakeups.all_agents) },+ ...(query.data?.agents ?? []).map((a) => ({ value: a.id, label: a.name })),+ ];+ return (+ <>+ <div className="flex shrink-0 flex-wrap items-center gap-2 border-b px-4 py-2">+ <div+ className="flex gap-1"+ role="group"+ aria-label={t(($) => $.wakeups.scope)}+ >+ {(["active", "all", "disabled", "ended"] as const).map((scope) => (+ <Button+ key={scope}+ size="sm"+ variant={filters.scope === scope ? "secondary" : "ghost"}+ aria-pressed={filters.scope === scope}+ disabled={batch.isPending}+ onClick={() => change({ scope })}+ >+ {t(($) => $.wakeups.scopes[scope])}+ <span className="ml-1 text-muted-foreground tabular-nums">+ {query.data?.counts[scope] ?? "—"}+ </span>+ </Button>+ ))}+ </div>+ <div className="ml-auto flex flex-wrap items-center gap-2">+ <form+ onSubmit={(event) => {+ event.preventDefault();+ change({ search: search.trim() });+ }}+ className="flex items-center gap-1"+ >+ <Input+ type="search"+ className="h-8 w-48"+ value={search}+ maxLength={256}+ disabled={batch.isPending}+ onChange={(event) => {+ setSearch(event.target.value);+ if (!event.target.value) change({ search: "" });+ }}+ aria-label={t(($) => $.wakeups.search)}+ placeholder={t(($) => $.wakeups.search)}+ />+ <Button+ size="sm"+ variant="ghost"+ type="submit"+ disabled={batch.isPending}+ >+ {t(($) => $.wakeups.search_action)}+ </Button>+ </form>+ <Select+ items={kinds}+ value={filters.kind}+ disabled={batch.isPending}+ onValueChange={(kind) => {+ if (+ kind === "all" ||+ kind === "event" ||+ kind === "at" ||+ kind === "recurring"+ )+ change({ kind });+ }}+ >+ <SelectTrigger size="sm" aria-label={t(($) => $.wakeups.trigger)}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {kinds.map((item) => (+ <SelectItem key={item.value} value={item.value}>+ {item.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Select+ items={agents}+ value={filters.agent_id}+ disabled={batch.isPending}+ onValueChange={(agent_id) => {+ if (agent_id !== null) change({ agent_id });+ }}+ >+ <SelectTrigger+ size="sm"+ className="max-w-48"+ aria-label={t(($) => $.wakeups.target_agent)}+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {agents.map((item) => (+ <SelectItem key={item.value} value={item.value}>+ {item.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ </div>+ {batchResult && (+ <p+ role="status"+ className={`px-4 py-2 text-caption ${batchResult.failed.length ? "text-destructive" : "text-muted-foreground"}`}+ >+ {t(+ ($) =>+ batchResult.failed.length+ ? $.wakeups.batch_partial+ : $.wakeups.batch_success,+ {+ count: batchResult.succeeded,+ succeeded: batchResult.succeeded,+ failed: batchResult.failed.length,+ },+ )}+ </p>+ )}+ {query.isError ? (+ <CollectionPageState+ icon={AlertCircle}+ tone="destructive"+ role="alert"+ title={t(($) => $.wakeups.load_error)}+ actions={+ <Button+ variant="outline"+ size="sm"+ onClick={() => void query.refetch()}+ >+ {t(($) => $.page.retry)}+ </Button>+ }+ />+ ) : query.isPending ? (+ <CollectionPageState+ icon={Clock3}+ title={t(($) => $.wakeups.loading)}+ />+ ) : !rows.length ? (+ <CollectionPageState+ icon={Bell}+ title={t(($) =>+ (query.data?.counts.all ?? 0) > 0 ||+ filters.search ||+ filters.kind !== "all" ||+ filters.agent_id+ ? $.wakeups.empty_filtered+ : $.wakeups.empty,+ )}+ actions={+ (filters.scope !== "all" ||+ !!filters.search ||+ filters.kind !== "all" ||+ !!filters.agent_id) &&+ (query.data?.counts.all ?? 0) > 0 ? (+ <Button+ variant="outline"+ size="sm"+ onClick={() => {+ setSearch("");+ change({+ scope: "all",+ kind: "all",+ search: "",+ agent_id: "",+ });+ }}+ >+ {t(($) => $.wakeups.clear_filters)}+ </Button>+ ) : undefined+ }+ />+ ) : (+ <div className="min-h-0 flex-1 overflow-auto">+ <Table className="min-w-[1050px]">+ <TableHeader>+ <TableRow>+ <TableHead className="pl-4">+ <Checkbox+ disabled={!selectable.length || batch.isPending}+ checked={+ picked.length > 0 && picked.length === selectable.length+ }+ indeterminate={+ picked.length > 0 && picked.length < selectable.length+ }+ onCheckedChange={() =>+ setSelected(+ picked.length === selectable.length+ ? new Set()+ : new Set(selectable.map((row) => row.id)),+ )+ }+ aria-label={t(($) => $.wakeups.select_page)}+ />+ </TableHead>+ <TableHead>{t(($) => $.wakeups.issue)}</TableHead>+ <TableHead>{t(($) => $.wakeups.target_agent)}</TableHead>+ <TableHead>{t(($) => $.wakeups.trigger)}</TableHead>+ <TableHead>{t(($) => $.wakeups.next)}</TableHead>+ <TableHead>{t(($) => $.wakeups.wakeup_run)}</TableHead>+ <TableHead className="w-px pr-4 text-right">+ {t(($) => $.wakeups.enabled)}+ </TableHead>+ <TableHead className="w-px pl-0 pr-4">+ <span className="sr-only">+ {ti(($) => $.wakeups.edit_instruction)}+ </span>+ </TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {rows.map((row) => (+ <WakeupListRow+ key={row.id}+ row={row}+ busy={batch.isPending}+ selected={selected.has(row.id)}+ onSelect={() =>+ setSelected((prev) => {+ const next = new Set(prev);+ if (next.has(row.id)) next.delete(row.id);+ else next.add(row.id);+ return next;+ })+ }+ />+ ))}+ </TableBody>+ </Table>+ </div>+ )}+ <div className="mt-auto flex shrink-0 flex-wrap items-center gap-2 border-t px-4 py-2 text-caption text-muted-foreground">+ {picked.length > 0 && (+ <>+ <span>+ {t(($) => $.wakeups.selected, { count: picked.length })}+ </span>+ <Button+ size="sm"+ variant="outline"+ disabled={batch.isPending}+ onClick={() => setConfirmation(picked)}+ >+ {t(($) => $.wakeups.disable_selected)}+ </Button>+ <Button+ size="sm"+ variant="ghost"+ disabled={batch.isPending}+ onClick={() => setSelected(new Set())}+ >+ {t(($) => $.wakeups.clear)}+ </Button>+ </>+ )}+ <span className="ml-auto tabular-nums">+ {query.data && !query.isError+ ? t(($) => $.wakeups.results, {+ count: query.data?.total ?? 0,+ page: Math.floor(filters.offset / filters.limit) + 1,+ })+ : "—"}+ </span>+ <Button+ size="sm"+ variant="ghost"+ disabled={batch.isPending || !filters.offset}+ onClick={() =>+ change({ offset: Math.max(0, filters.offset - filters.limit) })+ }+ >+ {t(($) => $.wakeups.previous)}+ </Button>+ <Button+ size="sm"+ variant="ghost"+ disabled={+ batch.isPending ||+ !query.data ||+ filters.offset + filters.limit >= query.data.total+ }+ onClick={() => change({ offset: filters.offset + filters.limit })}+ >+ {t(($) => $.wakeups.next_page)}+ </Button>+ </div>+ <Dialog+ open={confirmation.length > 0}+ onOpenChange={(open) => {+ if (!open && !batch.isPending) setConfirmation([]);+ }}+ >+ <DialogContent>+ <DialogHeader>+ <DialogTitle>+ {t(($) => $.wakeups.confirm_title, {+ count: confirmation.length,+ })}+ </DialogTitle>+ <DialogDescription>+ {t(($) => $.wakeups.confirm_body)}+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button+ variant="outline"+ disabled={batch.isPending}+ onClick={() => setConfirmation([])}+ >+ {t(($) => $.wakeups.cancel)}+ </Button>+ <Button+ disabled={batch.isPending}+ onClick={async () => {+ const result = await batch.mutateAsync(confirmation);+ setBatchResult(result);+ setSelected(new Set(result.failed));+ setConfirmation([]);+ }}+ >+ {batch.isPending+ ? t(($) => $.wakeups.disabling)+ : t(($) => $.wakeups.confirm)}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ );+}diff --git a/packages/views/issues/components/execution-log-section.tsx b/packages/views/issues/components/execution-log-section.tsxindex 9b964b0dcc..c3889d19cb 100644--- a/packages/views/issues/components/execution-log-section.tsx+++ b/packages/views/issues/components/execution-log-section.tsx@@ -284,6 +284,7 @@ export function IssueUsageTotal({const STATUS_TONE: Record<AgentTask["status"], string> = {queued: "text-warning",+ deferred: "text-warning",dispatched: "text-warning",// Same tone as queued/dispatched — visually "stopped" so users see the// task is parked, but distinguished by the status label.diff --git a/packages/views/issues/components/issue-agent-activity-indicator.test.tsx b/packages/views/issues/components/issue-agent-activity-indicator.test.tsxindex 54eb31ff89..e98d361ae9 100644--- a/packages/views/issues/components/issue-agent-activity-indicator.test.tsx+++ b/packages/views/issues/components/issue-agent-activity-indicator.test.tsx@@ -1,9 +1,11 @@import { cleanup, render, screen } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";+import en from "../../locales/en/issues.json";import type { AgentTask } from "@multica/core/types";const mockState = vi.hoisted(() => ({snapshot: [] as unknown[],+ summaries: [] as unknown[],}));vi.mock("@multica/core/hooks", () => ({@@ -27,7 +29,16 @@ vi.mock("../../agents/components/agent-activity-hover-content", () => ({}));vi.mock("../../i18n", () => ({- useT: () => ({ t: () => "Working" }),+ useT: () => ({+ t: (+ selector: (strings: typeof en) => string,+ params: Record<string, unknown> = {},+ ) =>+ selector(en).replace(/{{(\w+)}}/g, (_, key: string) =>+ String(params[key] ?? ""),+ ),+ }),+ useLocale: () => "en",}));// The hover card only portals its content once open, so absence of the body@@ -60,10 +71,9 @@ vi.mock("@multica/ui/components/ui/hover-card", () => ({}));vi.mock("@tanstack/react-query", async () => {- const actual =- await vi.importActual<typeof import("@tanstack/react-query")>(- "@tanstack/react-query",- );+ const actual = await vi.importActual<typeof import("@tanstack/react-query")>(+ "@tanstack/react-query",+ );return {...actual,useQuery: (opts: {@@ -77,6 +87,12 @@ vi.mock("@tanstack/react-query", async () => {: mockState.snapshot,};}+ if (opts.queryKey?.[0] === "issue-wakeup-summaries")+ return {+ data: opts.select+ ? opts.select(mockState.summaries)+ : mockState.summaries,+ };return { data: undefined };},};@@ -105,6 +121,7 @@ function makeTask(overrides: Partial<AgentTask> = {}): AgentTask {beforeEach(() => {cleanup();mockState.snapshot = [makeTask()];+ mockState.summaries = [];});describe("IssueAgentActivityIndicator", () => {@@ -142,3 +159,50 @@ describe("IssueAgentActivityIndicator", () => {expect(container.firstChild).toBeNull();});});++const eventSummary = {+ id: "wake-1",+ issue_id: "issue-1",+ agent_id: "agent-1",+ agent_name: "Emacs",+ kind: "event",+ mode: "continuous",+ event_types: ["task.completed"],+ timezone: "UTC",+ next_fire_at: null,+ active_count: 2,+ event_count: 2,+};+it("shows waiting and aggregate count even without an active run", () => {+ mockState.snapshot = [];+ mockState.summaries = [eventSummary];+ render(<IssueAgentActivityIndicator issueId="issue-1" hoverCard={false} />);+ expect(screen.getByText("Waiting for trigger")).toBeInTheDocument();+ expect(screen.getByText("+1")).toBeInTheDocument();+ expect(screen.queryByTestId("agent-avatar-stack")).toBeNull();+});+it("prioritizes active runs, marking wakeup origin separately from future count", () => {+ mockState.snapshot = [+ makeTask(),+ makeTask({ id: "task-2", status: "deferred", wakeup_id: "wake-2" }),+ ];+ mockState.summaries = [eventSummary];+ render(<IssueAgentActivityIndicator issueId="issue-1" hoverCard={false} />);+ expect(screen.getByText("Working")).toBeInTheDocument();+ expect(screen.getByLabelText("Triggered by wakeup")).toBeInTheDocument();+ expect(screen.getByText("+2")).toBeInTheDocument();+ expect(screen.queryByText("Waiting for trigger")).toBeNull();+});+it("does not expose another issue's wakeups", () => {+ mockState.snapshot = [];+ mockState.summaries = [{ ...eventSummary, issue_id: "other-issue" }];+ const { container } = render(+ <IssueAgentActivityIndicator issueId="issue-1" />,+ );+ expect(container.firstChild).toBeNull();+});+it("shows deferred wakeup retries as queued", () => {+ mockState.snapshot = [makeTask({ status: "deferred", wakeup_id: "wake-1" })];+ render(<IssueAgentActivityIndicator issueId="issue-1" hoverCard={false} />);+ expect(screen.getByText("Queued")).toBeInTheDocument();+});diff --git a/packages/views/issues/components/issue-agent-activity-indicator.tsx b/packages/views/issues/components/issue-agent-activity-indicator.tsxindex 97d6a76e17..d9ac7e7fc8 100644--- a/packages/views/issues/components/issue-agent-activity-indicator.tsx+++ b/packages/views/issues/components/issue-agent-activity-indicator.tsx@@ -1,6 +1,7 @@"use client";-import { memo, useCallback, useMemo } from "react";+import { memo, useCallback, useMemo, useState } from "react";+import { Bell, Clock3 } from "lucide-react";import { useQuery } from "@tanstack/react-query";import {HoverCard,@@ -9,13 +10,15 @@ import {} from "@multica/ui/components/ui/hover-card";import { useWorkspaceId } from "@multica/core/hooks";import { agentTaskSnapshotOptions } from "@multica/core/agents";-import type { AgentTask } from "@multica/core/types";+import type { AgentTask, IssueWakeupSummaryRow } from "@multica/core/types";+import { workspaceWakeupSummariesOptions } from "@multica/core/issues/wakeups";import { cn } from "@multica/ui/lib/utils";import type { AvatarSize } from "@multica/ui/lib/avatar-size";import { AgentAvatarStack } from "../../agents/components/agent-avatar-stack";import { AgentActivityHoverContent } from "../../agents/components/agent-activity-hover-content";import { selectIssueTasks, type IssueTaskGroups } from "../surface/activity";import { useT } from "../../i18n";+import { useWakeupText } from "./wakeup-presentation";const EMPTY_GROUPS: IssueTaskGroups = { running: [], queued: [] };@@ -56,7 +59,8 @@ interface IssueAgentActivityIndicatorProps {** - has ≥1 running task → tiny avatar stack + shimmering "Working"* - 0 running, ≥1 queued → half-opacity stack + muted "Queued"- * - nothing → return null (no chrome, no placeholder)+ * - future wakeups only → next time/event + remaining count+ * - no tasks or wakeups → return null (no chrome, no placeholder)** The shimmer reuses chat's `animate-chat-text-shimmer` utility (defined* in packages/ui/styles/base.css). Earlier iterations layered a brand@@ -86,85 +90,181 @@ interface IssueAgentActivityIndicatorProps {* lists cheap when agents are busy (MUL-4474). 30s staleTime is the offline* fallback only.*/-export const IssueAgentActivityIndicator = memo(function IssueAgentActivityIndicator({- issueId,- size = "xs",- hoverCard = true,-}: IssueAgentActivityIndicatorProps) {- const { t } = useT("issues");- const wsId = useWorkspaceId();- const select = useCallback(- (snapshot: AgentTask[]) => selectIssueTasks(snapshot, issueId),- [issueId],- );- const { data: groups = EMPTY_GROUPS } = useQuery({- ...agentTaskSnapshotOptions(wsId),- select,- });+export const IssueAgentActivityIndicator = memo(+ function IssueAgentActivityIndicator({+ issueId,+ size = "xs",+ hoverCard = true,+ }: IssueAgentActivityIndicatorProps) {+ const { t } = useT("issues");+ const wsId = useWorkspaceId();+ const text = useWakeupText();+ const [open, setOpen] = useState(false);+ const selectWakeups = useCallback(+ (rows: IssueWakeupSummaryRow[]) =>+ rows.filter((row) => row.issue_id === issueId),+ [issueId],+ );+ const { data: wakeups = [] } = useQuery({+ ...workspaceWakeupSummariesOptions(wsId),+ select: selectWakeups,+ });+ const select = useCallback(+ (snapshot: AgentTask[]) => selectIssueTasks(snapshot, issueId),+ [issueId],+ );+ const { data: groups = EMPTY_GROUPS } = useQuery({+ ...agentTaskSnapshotOptions(wsId),+ select,+ });- const { agentIds, opacity } = useMemo(() => {- // Stack heads: prefer running. If 0 running, fall back to queued.- // Each case is visually distinct (running gets shimmer, queued gets- // muted text) so the indicator always offers a face to hover.- const primary = groups.running.length > 0 ? groups.running : groups.queued;- const uniqueAgents = [...new Set(primary.map((t) => t.agent_id))];- return {- agentIds: uniqueAgents,- opacity: (groups.running.length > 0 ? "full" : "half") as "full" | "half",- };- }, [groups]);+ const { agentIds, opacity } = useMemo(() => {+ // Stack heads: prefer running. If 0 running, fall back to queued.+ // Each case is visually distinct (running gets shimmer, queued gets+ // muted text) so the indicator always offers a face to hover.+ const primary =+ groups.running.length > 0 ? groups.running : groups.queued;+ const uniqueAgents = [...new Set(primary.map((t) => t.agent_id))];+ return {+ agentIds: uniqueAgents,+ opacity: (groups.running.length > 0 ? "full" : "half") as+ | "full"+ | "half",+ };+ }, [groups]);- if (agentIds.length === 0) return null;- const isRunning = opacity === "full";+ const wakeupCount = wakeups[0]?.active_count ?? 0;+ const hasTasks = agentIds.length > 0;+ const hoverTasks = [...groups.running, ...groups.queued];+ const wakeupTriggered = hoverTasks.some((task) => !!task.wakeup_id);+ if (!hasTasks && !wakeupCount) return null;+ const isRunning = opacity === "full";+ const waitingLabel =+ wakeups[0]?.kind === "event"+ ? t(($) => $.wakeups.waiting_event)+ : wakeups[0]+ ? text.trigger(wakeups[0])+ : "";+ const label = hasTasks+ ? isRunning+ ? t(($) => $.agent_activity.status_running)+ : t(($) => $.agent_activity.status_queued)+ : waitingLabel;- const badge = (- <>- <AgentAvatarStack- agentIds={agentIds}- size={size}- opacity={opacity}- max={3}- />- {/* No leading-none: the shimmer paints glyphs via background-clip:+ const badge = hasTasks ? (+ <>+ <AgentAvatarStack+ agentIds={agentIds}+ size={size}+ opacity={opacity}+ max={3}+ />+ {/* No leading-none: the shimmer paints glyphs via background-clip:text, and the background only covers the line box — a squeezedline box leaves descenders transparent. */}- <span- className={cn(- "text-micro",- isRunning- ? "animate-chat-text-shimmer"- : "text-muted-foreground",+ <span+ className={cn(+ "text-micro",+ isRunning ? "animate-chat-text-shimmer" : "text-muted-foreground",+ )}+ >+ {isRunning+ ? t(($) => $.agent_activity.status_running)+ : t(($) => $.agent_activity.status_queued)}+ </span>+ {wakeupTriggered && (+ <Bell+ className="size-3 text-muted-foreground"+ aria-label={t(($) => $.wakeups.triggered_by_wakeup)}+ />)}- >- {isRunning- ? t(($) => $.agent_activity.status_running)- : t(($) => $.agent_activity.status_queued)}- </span>- </>- );-- if (!hoverCard) {- return (- <span className="inline-flex shrink-0 items-center gap-1">{badge}</span>+ {wakeupCount > 0 && (+ <span+ className="inline-flex items-center gap-1 text-micro tabular-nums text-muted-foreground"+ title={t(($) => $.wakeups.upcoming, { count: wakeupCount })}+ >+ {!wakeupTriggered && <Bell className="size-3" aria-hidden="true" />}+ +{wakeupCount}+ </span>+ )}+ </>+ ) : (+ <>+ {wakeups[0]?.kind === "event" ? (+ <Bell className="size-3 text-muted-foreground" aria-hidden="true" />+ ) : (+ <Clock3 className="size-3 text-muted-foreground" aria-hidden="true" />+ )}+ <span className="max-w-36 truncate text-micro text-muted-foreground">+ {waitingLabel}+ </span>+ {wakeupCount > 1 && (+ <span className="text-micro tabular-nums text-muted-foreground">+ +{wakeupCount - 1}+ </span>+ )}+ </>);- }- const hoverTasks = [...groups.running, ...groups.queued];+ if (!hoverCard) {+ return (+ <span className="inline-flex shrink-0 items-center gap-1">{badge}</span>+ );+ }- return (- <HoverCard>- <HoverCardTrigger- delay={OPEN_DELAY_MS}- closeDelay={CLOSE_DELAY_MS}- render={- <span className="inline-flex shrink-0 items-center gap-1" />- }- >- {badge}- </HoverCardTrigger>- <HoverCardContent align="end" className="w-72">- <AgentActivityHoverContent tasks={hoverTasks} />- </HoverCardContent>- </HoverCard>- );-});+ return (+ <HoverCard open={open} onOpenChange={setOpen}>+ <HoverCardTrigger+ delay={OPEN_DELAY_MS}+ closeDelay={CLOSE_DELAY_MS}+ render={+ <span+ tabIndex={0}+ aria-label={`${label}${wakeupTriggered ? ` · ${t(($) => $.wakeups.triggered_by_wakeup)}` : ""}${wakeupCount ? ` · ${t(($) => $.wakeups.upcoming, { count: wakeupCount })}` : ""}`}+ onFocus={() => setOpen(true)}+ onBlur={() => setOpen(false)}+ className="inline-flex shrink-0 items-center gap-1 rounded-sm focus-visible:outline-2 focus-visible:outline-ring"+ />+ }+ >+ {badge}+ </HoverCardTrigger>+ <HoverCardContent align="end" className="w-72">+ {hasTasks && <AgentActivityHoverContent tasks={hoverTasks} />}+ {wakeupCount > 0 && (+ <div+ className={cn(+ "space-y-2 text-caption",+ hasTasks && "mt-2 border-t border-border pt-2",+ )}+ >+ <p className="text-muted-foreground">+ {t(($) => $.wakeups.upcoming, { count: wakeupCount })}+ </p>+ {wakeups.map((wakeup) => (+ <div key={wakeup.id}>+ <p className="break-words font-medium">+ {text.trigger(wakeup)}+ </p>+ <p className="text-muted-foreground">+ {t(($) => $.wakeups.wake_agent, {+ agent: wakeup.agent_name,+ })}{" "}+ · {text.schedule(wakeup)}+ </p>+ </div>+ ))}+ {wakeupCount > wakeups.length && (+ <p className="text-muted-foreground">+ {t(($) => $.wakeups.more, {+ count: wakeupCount - wakeups.length,+ })}+ </p>+ )}+ </div>+ )}+ </HoverCardContent>+ </HoverCard>+ );+ },+);diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex c522e3b946..c47f9519d7 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -99,6 +99,7 @@ import { ThreadMinimap, type ThreadMinimapThread } from "./thread-minimap";import { collectThreadParticipants, collectThreadReplies, deriveThreadResolution } from "./thread-utils";import { IssueAgentHeaderChip } from "./issue-agent-header-chip";import { ExecutionLogSection } from "./execution-log-section";+import { WakeupsSection } from "./wakeups-section";import { QuickActionsSection } from "./quick-actions-section";import { PluginPanelSection } from "../../plugins";import { PullRequestList } from "./pull-request-list";@@ -2507,6 +2508,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trclick an action they cannot run, and the refusal is explained at runtime rather than by a silently shorter list. */}<QuickActionsSection issueId={issue.id} />+ <WakeupsSection issueId={issue.id} closed={["done", "closed"].includes(resolveStatusCategory(issue.status))} /><PluginPanelSection issueId={issue.id} />{/* Parent issue — standalone section, only when the issue has adiff --git a/packages/views/issues/components/wakeup-control.tsx b/packages/views/issues/components/wakeup-control.tsxnew file mode 100644index 0000000000..26f2d0b599--- /dev/null+++ b/packages/views/issues/components/wakeup-control.tsx@@ -0,0 +1,204 @@+"use client";++import { useId, useState } from "react";+import { toast } from "sonner";+import type { AgentTask, IssueWakeup } from "@multica/core/types";+import { Switch } from "@multica/ui/components/ui/switch";+import { Input } from "@multica/ui/components/ui/input";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import { Button } from "@multica/ui/components/ui/button";+import { useT } from "../../i18n";+import { isActiveWakeupRun, useWakeupText } from "./wakeup-presentation";++export function WakeupControl({+ wakeup,+ task,+ pending,+ closed,+ onDisable,+ onEnable,+}: {+ wakeup: Omit<IssueWakeup, "instruction">;+ task?: AgentTask;+ pending: boolean;+ closed: boolean;+ onDisable: () => void;+ onEnable: (input?: { at?: string; rearm?: boolean }) => Promise<void>;+}) {+ const { t } = useT("issues");+ const text = useWakeupText();+ const status = task?.status ?? wakeup.last_task_status;+ const canDisable =+ !wakeup.disabled_at &&+ (wakeup.enabled ||+ (["queued", "deferred"].includes(status ?? "") && !task?.started_at));+ const activeRun = isActiveWakeupRun(status);+ const consumed =+ !wakeup.enabled &&+ wakeup.mode === "once" &&+ (!wakeup.disabled_at || !!wakeup.last_task_id);+ const expired =+ wakeup.kind === "at" &&+ (!wakeup.next_fire_at ||+ new Date(wakeup.next_fire_at).getTime() <= Date.now());+ const needsRearm = !wakeup.enabled && (consumed || expired);+ const canEnable = !closed && (!activeRun || wakeup.mode === "continuous");+ return (+ <div className="flex min-h-11 shrink-0 items-center px-2">+ {wakeup.enabled || (!needsRearm && !canDisable) ? (+ <Switch+ checked={wakeup.enabled}+ disabled={pending || (!wakeup.enabled && !canEnable)}+ aria-label={t(($) => $.wakeups.toggle, {+ agent: wakeup.agent_name,+ })}+ onCheckedChange={(checked) => {+ if (checked)+ void onEnable().catch((err) =>+ toast.error(+ text.error(+ err,+ t(($) => $.wakeups.enable_error),+ ),+ ),+ );+ else onDisable();+ }}+ />+ ) : canDisable ? (+ <Button+ variant="ghost"+ size="sm"+ disabled={pending}+ onClick={onDisable}+ >+ {t(($) => $.wakeups.withdraw)}+ </Button>+ ) : wakeup.kind === "at" ? (+ <RescheduleWakeup+ disabled={pending || !canEnable}+ pending={pending}+ onSubmit={(at) => onEnable({ at, rearm: true })}+ />+ ) : (+ <Button+ variant="ghost"+ size="sm"+ disabled={pending || !canEnable}+ onClick={() =>+ void onEnable({ rearm: true }).catch((err) =>+ toast.error(+ text.error(+ err,+ t(($) => $.wakeups.enable_error),+ ),+ ),+ )+ }+ >+ {t(($) => $.wakeups.resubscribe)}+ </Button>+ )}+ </div>+ );+}++function RescheduleWakeup({+ disabled,+ pending,+ onSubmit,+}: {+ disabled: boolean;+ pending: boolean;+ onSubmit: (at: string) => Promise<void>;+}) {+ const { t } = useT("issues");+ const text = useWakeupText();+ const id = useId();+ const [open, setOpen] = useState(false);+ const [value, setValue] = useState("");+ const [error, setError] = useState("");+ return (+ <Dialog open={open} onOpenChange={setOpen}>+ <Button+ variant="ghost"+ size="sm"+ disabled={disabled}+ onClick={() => {+ setError("");+ setValue("");+ setOpen(true);+ }}+ >+ {t(($) => $.wakeups.reschedule)}+ </Button>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t(($) => $.wakeups.reschedule)}</DialogTitle>+ </DialogHeader>+ <form+ className="space-y-3"+ onSubmit={async (event) => {+ event.preventDefault();+ if (pending) return;+ const date = new Date(value);+ if (+ !Number.isFinite(date.getTime()) ||+ date.getTime() <= Date.now()+ ) {+ setError(t(($) => $.wakeups.future_time));+ return;+ }+ try {+ await onSubmit(date.toISOString());+ setOpen(false);+ } catch (err) {+ setError(+ text.error(+ err,+ t(($) => $.wakeups.enable_error),+ ),+ );+ }+ }}+ >+ <label htmlFor={id} className="text-caption">+ {t(($) => $.wakeups.local_time, {+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,+ })}+ </label>+ <Input+ id={id}+ type="datetime-local"+ required+ value={value}+ disabled={pending}+ aria-invalid={!!error}+ aria-describedby={error ? `${id}-error` : undefined}+ onChange={(event) => {+ setValue(event.target.value);+ setError("");+ }}+ />+ {error && (+ <p+ id={`${id}-error`}+ role="alert"+ className="text-caption text-destructive"+ >+ {error}+ </p>+ )}+ <Button type="submit" disabled={pending}>+ {t(($) => $.wakeups.reschedule)}+ </Button>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/packages/views/issues/components/wakeup-instruction-editor.test.tsx b/packages/views/issues/components/wakeup-instruction-editor.test.tsxnew file mode 100644index 0000000000..a860cddb14--- /dev/null+++ b/packages/views/issues/components/wakeup-instruction-editor.test.tsx@@ -0,0 +1,84 @@+import { beforeEach, expect, it, vi } from "vitest";+import { fireEvent, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { api } from "@multica/core/api";+import type { IssueWakeup } from "@multica/core/types";+import { renderWithI18n } from "../../test/i18n";+import { WakeupInstructionEditor } from "./wakeup-instruction-editor";++vi.mock("@multica/core/api", () => ({ api: { listIssueWakeups: vi.fn(), editIssueWakeupInstruction: vi.fn() } }));+const list = vi.mocked(api.listIssueWakeups);+const edit = vi.mocked(api.editIssueWakeupInstruction);+let rule: IssueWakeup;+beforeEach(() => {+ rule = { id: "wake", issue_id: "issue", agent_id: "agent", agent_name: "Emacs", instruction: "Check CI", revision: 2, kind: "event", mode: "continuous", event_types: ["comment.created"], filter_agent_id: null, filter_task_id: null, interval_seconds: null, cron_expression: null, timezone: "UTC", next_fire_at: null, enabled: false, disabled_at: null, last_task_id: null, last_error: null };+ list.mockReset().mockImplementation(async () => [rule]);+ edit.mockReset().mockResolvedValue(undefined);+});+function mount() {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });+ renderWithI18n(<QueryClientProvider client={client}><WakeupInstructionEditor workspaceId="ws" issueId="issue" wakeupId="wake" /></QueryClientProvider>);+ return client;+}+async function open() {+ fireEvent.click(screen.getByRole("button", { name: "Edit prompt" }));+ return screen.findByRole("textbox", { name: "What to do when woken" });+}+it("loads instructions only on demand and saves only prompt fields with its editing snapshot", async () => {+ mount();+ expect(list).not.toHaveBeenCalled();+ const input = await open();+ expect(input).toHaveValue("Check CI");+ fireEvent.change(input, { target: { value: "Check deployment\nReport failure" } });+ fireEvent.keyDown(input, { key: "Enter", ctrlKey: true });+ await waitFor(() => expect(edit).toHaveBeenCalledWith("issue", "wake", { instruction: "Check deployment\nReport failure", expected_instruction: "Check CI", revision: 2 }));+ await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());+});+it("cancels a draft without saving", async () => {+ mount();+ fireEvent.change(await open(), { target: { value: "discard this" } });+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));+ expect(edit).not.toHaveBeenCalled();+ expect(await open()).toHaveValue("Check CI");+});+it("keeps the draft after a conflict and never silently uses the refreshed revision", async () => {+ const client = mount();+ const input = await open();+ fireEvent.change(input, { target: { value: "my draft" } });+ rule = { ...rule, instruction: "someone else's edit", revision: 3 };+ await client.invalidateQueries({ queryKey: ["issue-wakeups", "ws", "issue"] });+ edit.mockRejectedValue({ status: 409 });+ fireEvent.click(screen.getByRole("button", { name: "Save" }));+ expect(await screen.findByRole("alert")).toHaveTextContent("This rule has changed");+ expect(input).toHaveValue("my draft");+ expect(edit).toHaveBeenCalledWith("issue", "wake", expect.objectContaining({ expected_instruction: "Check CI", revision: 2 }));+});+it("validates empty and oversized multi-byte instructions, and retains a forbidden draft", async () => {+ mount();+ const input = await open();+ for (const value of [" ", "中".repeat(4001)]) {+ fireEvent.change(input, { target: { value } });+ fireEvent.click(screen.getByRole("button", { name: "Save" }));+ expect(await screen.findByRole("alert")).toHaveTextContent("12,000");+ }+ expect(edit).not.toHaveBeenCalled();+ edit.mockRejectedValue({ status: 403 });+ fireEvent.change(input, { target: { value: "keep this draft" } });+ fireEvent.click(screen.getByRole("button", { name: "Save" }));+ expect(await screen.findByRole("alert")).toHaveTextContent("You cannot manage this wakeup");+ expect(input).toHaveValue("keep this draft");+});+it("prevents duplicate saves and dismissal while saving", async () => {+ let resolve!: () => void;+ edit.mockImplementation(() => new Promise<void>((done) => { resolve = done; }));+ mount();+ const input = await open();+ fireEvent.change(input, { target: { value: "new prompt" } });+ fireEvent.click(screen.getByRole("button", { name: "Save" }));+ await waitFor(() => expect(screen.getByRole("button", { name: "Saving..." })).toBeDisabled());+ fireEvent.keyDown(input, { key: "Enter", ctrlKey: true });+ expect(edit).toHaveBeenCalledTimes(1);+ expect(screen.getByRole("button", { name: "Cancel" })).toBeDisabled();+ resolve();+ await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());+});diff --git a/packages/views/issues/components/wakeup-instruction-editor.tsx b/packages/views/issues/components/wakeup-instruction-editor.tsxnew file mode 100644index 0000000000..feaa3864fc--- /dev/null+++ b/packages/views/issues/components/wakeup-instruction-editor.tsx@@ -0,0 +1,214 @@+"use client";++import { useId, useRef, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { Pencil } from "lucide-react";+import {+ issueWakeupsOptions,+ useEditWakeupInstruction,+} from "@multica/core/issues/wakeups";+import type { IssueWakeup } from "@multica/core/types";+import { Button } from "@multica/ui/components/ui/button";+import { Textarea } from "@multica/ui/components/ui/textarea";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@multica/ui/components/ui/tooltip";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogTrigger,+} from "@multica/ui/components/ui/dialog";+import { useT } from "../../i18n";+import { useWakeupText } from "./wakeup-presentation";++export function WakeupInstructionEditor({+ workspaceId,+ issueId,+ wakeupId,+ disabled = false,+ triggerStyle = "text",+}: {+ workspaceId: string;+ issueId: string;+ wakeupId: string;+ disabled?: boolean;+ triggerStyle?: "text" | "icon";+}) {+ const { t } = useT("issues");+ const [open, setOpen] = useState(false);+ const [saving, setSaving] = useState(false);+ const label = t(($) => $.wakeups.edit_instruction);+ const trigger = (+ <DialogTrigger+ render={+ <Button+ variant="ghost"+ size={triggerStyle === "icon" ? "icon" : "sm"}+ className={triggerStyle === "icon" ? "size-11 text-muted-foreground" : undefined}+ disabled={disabled}+ aria-label={label}+ />+ }+ >+ <Pencil className="size-3.5" aria-hidden="true" />+ {triggerStyle === "text" && label}+ </DialogTrigger>+ );+ return (+ <Dialog+ open={open}+ onOpenChange={(next) => {+ if (!saving) setOpen(next);+ }}+ >+ {triggerStyle === "icon" ? (+ <Tooltip>+ <TooltipTrigger render={trigger} />+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>+ ) : trigger}+ <DialogContent className="sm:max-w-xl" showCloseButton={!saving}>+ <DialogHeader>+ <DialogTitle>{t(($) => $.wakeups.edit_instruction)}</DialogTitle>+ <DialogDescription>+ {t(($) => $.wakeups.instruction_effect)}+ </DialogDescription>+ </DialogHeader>+ {open && (+ <InstructionLoader+ workspaceId={workspaceId}+ issueId={issueId}+ wakeupId={wakeupId}+ onSaved={() => setOpen(false)}+ onSaving={setSaving}+ onCancel={() => setOpen(false)}+ />+ )}+ </DialogContent>+ </Dialog>+ );+}++function InstructionLoader({+ workspaceId, issueId, wakeupId, ...actions+}: {+ workspaceId: string;+ issueId: string;+ wakeupId: string;+ onSaved: () => void;+ onSaving: (value: boolean) => void;+ onCancel: () => void;+}) {+ const { t } = useT("issues");+ const query = useQuery({+ ...issueWakeupsOptions(workspaceId, issueId),+ refetchInterval: false,+ });+ const wakeup = query.data?.find((row) => row.id === wakeupId);+ if (query.isPending) {+ return <p role="status">{t(($) => $.wakeups.instruction_loading)}</p>;+ }+ if (!wakeup) {+ return (+ <Button variant="ghost" onClick={() => void query.refetch()}>+ {t(($) => $.wakeups.retry)}+ </Button>+ );+ }+ return (+ <InstructionForm key={wakeupId} wakeup={wakeup} workspaceId={workspaceId} {...actions} />+ );+}++function InstructionForm({+ wakeup, workspaceId, onSaved, onSaving, onCancel+}: {+ wakeup: IssueWakeup;+ workspaceId: string;+ onSaved: () => void;+ onSaving: (value: boolean) => void;+ onCancel: () => void;+}) {+ const { t } = useT("issues");+ const text = useWakeupText();+ const id = useId();+ // Keep the editing snapshot through query refreshes; a stale save conflicts+ // instead of replacing another person's changes or silently resetting drafts.+ const [original] = useState(wakeup);+ const [value, setValue] = useState(wakeup.instruction);+ const [error, setError] = useState("");+ const busy = useRef(false);+ const mutation = useEditWakeupInstruction(workspaceId, wakeup.issue_id);+ return (+ <form+ className="space-y-3"+ onSubmit={async (event) => {+ event.preventDefault();+ if (busy.current) return;+ const instruction = value.trim();+ if (!instruction || new TextEncoder().encode(instruction).length > 12000) {+ setError(t(($) => $.wakeups.instruction_invalid));+ return;+ }+ busy.current = true;+ onSaving(true);+ setError("");+ try {+ await mutation.mutateAsync({+ id: wakeup.id,+ instruction,+ expected_instruction: original.instruction,+ revision: original.revision ?? 0,+ });+ onSaved();+ } catch (err) {+ setError(text.error(err, t(($) => $.wakeups.instruction_save_error)));+ } finally {+ busy.current = false;+ onSaving(false);+ }+ }}+ >+ <label htmlFor={id} className="text-caption font-medium">+ {t(($) => $.wakeups.instruction_title)}+ </label>+ <Textarea+ id={id}+ value={value}+ rows={8}+ className="max-h-[45dvh] resize-y text-base md:text-body"+ disabled={mutation.isPending}+ aria-invalid={!!error}+ aria-describedby={error ? `${id}-error` : undefined}+ onChange={(event) => {+ setValue(event.target.value);+ setError("");+ }}+ onKeyDown={(event) => {+ if ((event.metaKey || event.ctrlKey) && event.key === "Enter" && !event.nativeEvent.isComposing) {+ event.preventDefault();+ event.currentTarget.form?.requestSubmit();+ }+ }}+ />+ {error && (+ <p id={`${id}-error`} role="alert" className="text-caption text-destructive">+ {error}+ </p>+ )}+ <div className="flex justify-end gap-2">+ <Button type="button" variant="outline" disabled={mutation.isPending} onClick={onCancel}>+ {t(($) => $.wakeups.instruction_cancel)}+ </Button>+ <Button type="submit" disabled={mutation.isPending || value.trim() === original.instruction}>+ {t(($) => mutation.isPending ? $.wakeups.instruction_saving : $.wakeups.instruction_save)}+ </Button>+ </div>+ </form>+ );+}diff --git a/packages/views/issues/components/wakeup-presentation.test.ts b/packages/views/issues/components/wakeup-presentation.test.tsnew file mode 100644index 0000000000..e1d5cacff6--- /dev/null+++ b/packages/views/issues/components/wakeup-presentation.test.ts@@ -0,0 +1,13 @@+import { expect, it } from "vitest";+import { formatWakeupTime } from "./wakeup-presentation";++it("uses the configured timezone to distinguish today from the next day", () => {+ const now = new Date("2026-09-16T15:00:00Z");+ expect(formatWakeupTime("2026-09-16T15:30:00Z", "en-US", "Asia/Shanghai", now)).not.toContain("Sep");+ expect(formatWakeupTime("2026-09-16T16:30:00Z", "en-US", "Asia/Shanghai", now)).toContain("Sep 17");+});++it("includes the year across the configured timezone's new year", () => {+ const now = new Date("2026-12-31T15:00:00Z");+ expect(formatWakeupTime("2026-12-31T16:30:00Z", "en-US", "Asia/Shanghai", now)).toContain("2027");+});diff --git a/packages/views/issues/components/wakeup-presentation.ts b/packages/views/issues/components/wakeup-presentation.tsnew file mode 100644index 0000000000..4bfd558130--- /dev/null+++ b/packages/views/issues/components/wakeup-presentation.ts@@ -0,0 +1,244 @@+"use client";++import type {+ AgentTask,+ IssueWakeup,+ WakeupPreview,+} from "@multica/core/types";+import { useLocale, useT } from "../../i18n";+import { parseCron } from "../../autopilots/components/schedule-editor/cron-mapping";+import { useDescribeSchedule } from "../../autopilots/components/schedule-editor/describe";++export function wakeupState(+ w: Omit<IssueWakeup, "instruction">,+ closed = false,+ now = Date.now(),+) {+ if (closed) return "issue_closed";+ if (w.enabled) return w.kind === "event" ? "waiting" : "scheduled";+ if (w.disabled_at) return "disabled";+ if (w.last_task_id) return "triggered";+ if (w.kind === "at" && w.next_fire_at && Date.parse(w.next_fire_at) <= now)+ return "expired";+ return "inactive";+}++export function isActiveWakeupRun(status?: string | null) {+ return (+ !!status &&+ [+ "queued",+ "deferred",+ "dispatched",+ "running",+ "waiting_local_directory",+ ].includes(status)+ );+}++export function wakeupRun(wakeup: IssueWakeup, tasks: readonly AgentTask[]) {+ return (+ tasks.find(+ (task) => task.wakeup_id === wakeup.id && isActiveWakeupRun(task.status),+ ) ?? tasks.find((task) => task.id === wakeup.last_task_id)+ );+}++export function isCurrentWakeup(wakeup: IssueWakeup, task?: AgentTask) {+ return (+ wakeup.enabled || isActiveWakeupRun(task?.status ?? wakeup.last_task_status)+ );+}++export function formatWakeupTime(+ value: string,+ locale: string,+ timezone = "UTC",+ now = new Date(),+) {+ const date = new Date(value);+ if (!Number.isFinite(date.getTime())) return value;+ const day = new Intl.DateTimeFormat(locale, {+ timeZone: timezone,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ });+ const sameDay = day.format(date) === day.format(now);+ const year = new Intl.DateTimeFormat(locale, {+ timeZone: timezone,+ year: "numeric",+ });+ return new Intl.DateTimeFormat(locale, {+ timeZone: timezone,+ hour: "2-digit",+ minute: "2-digit",+ ...(sameDay ? {} : { month: "short" as const, day: "numeric" as const }),+ ...(year.format(date) === year.format(now)+ ? {}+ : { year: "numeric" as const }),+ }).format(date);+}++export function useWakeupText() {+ const { t } = useT("issues");+ const locale = useLocale();+ const describe = useDescribeSchedule();+ const eventLabels = (agent: string): Record<string, string> => ({+ "task.queued": t(($) => $.wakeups.conditions.run_queued, { agent }),+ "task.dispatched": t(($) => $.wakeups.conditions.run_dispatched, { agent }),+ "task.started": t(($) => $.wakeups.conditions.run_started, { agent }),+ "task.deferred": t(($) => $.wakeups.conditions.run_deferred, { agent }),+ "task.waiting_local_directory": t(+ ($) => $.wakeups.conditions.run_waiting_local_directory,+ { agent },+ ),+ "issue.updated": t(($) => $.wakeups.conditions.issue_updated, { agent }),+ "issue.assignee_changed": t(($) => $.wakeups.conditions.assignee_changed, {+ agent,+ }),+ "issue.parent_changed": t(($) => $.wakeups.conditions.parent_changed, {+ agent,+ }),+ "issue.project_changed": t(($) => $.wakeups.conditions.project_changed, {+ agent,+ }),+ "issue.labels_changed": t(($) => $.wakeups.conditions.labels_changed, {+ agent,+ }),+ "issue.properties_changed": t(+ ($) => $.wakeups.conditions.properties_changed,+ { agent },+ ),+ "issue.metadata_changed": t(($) => $.wakeups.conditions.metadata_changed, {+ agent,+ }),+ "comment.updated": t(($) => $.wakeups.conditions.comment_updated, {+ agent,+ }),+ "comment.deleted": t(($) => $.wakeups.conditions.comment_deleted, {+ agent,+ }),+ "comment.resolved": t(($) => $.wakeups.conditions.comment_resolved, {+ agent,+ }),+ "comment.unresolved": t(($) => $.wakeups.conditions.comment_unresolved, {+ agent,+ }),+ "reaction.added": t(($) => $.wakeups.conditions.reaction_added, { agent }),+ "reaction.removed": t(($) => $.wakeups.conditions.reaction_removed, {+ agent,+ }),+ "attachment.attached": t(($) => $.wakeups.conditions.attachment_attached, {+ agent,+ }),+ "attachment.detached": t(($) => $.wakeups.conditions.attachment_detached, {+ agent,+ }),+ "task.completed": t(($) => $.wakeups.conditions.run_completed, { agent }),+ "task.failed": t(($) => $.wakeups.conditions.run_failed, { agent }),+ "task.cancelled": t(($) => $.wakeups.conditions.run_cancelled, { agent }),+ "comment.created": t(($) => $.wakeups.conditions.comment_created, {+ agent,+ }),+ "issue.status_changed": t(($) => $.wakeups.conditions.status_changed, {+ agent,+ }),+ });++ const eventName = (+ event: string,+ agent = t(($) => $.wakeups.agent_subject),+ ) =>+ eventLabels(agent)[event] ?? t(($) => $.wakeups.unknown_event, { event });+ const frequency = (w: WakeupPreview) =>+ w.mode === "once"+ ? t(($) => $.wakeups.once)+ : t(($) => $.wakeups.continuous);+ const schedule = (w: WakeupPreview) => {+ if (w.kind === "every") {+ const seconds = w.interval_seconds ?? 0;+ return seconds === 3600+ ? t(($) => $.wakeups.hourly)+ : seconds % 3600 === 0+ ? t(($) => $.wakeups.every_hours, { hours: seconds / 3600 })+ : seconds % 60 === 0+ ? t(($) => $.wakeups.every, { minutes: seconds / 60 })+ : t(($) => $.wakeups.every_seconds, { seconds });+ }+ if (w.kind === "cron")+ return (+ describe(parseCron(w.cron_expression ?? "", w.timezone)) ??+ `${w.cron_expression} · ${w.timezone}`+ );+ return frequency(w);+ };+ const time = (value: string, timezone: string) => {+ if (!Number.isFinite(Date.parse(value))) return value;+ const day = new Intl.DateTimeFormat(locale, {+ timeZone: timezone,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ });+ const formatted = formatWakeupTime(value, locale, timezone);+ return day.format(new Date(value)) === day.format(new Date())+ ? t(($) => $.wakeups.today_time, { time: formatted })+ : formatted;+ };+ const actorName = (w: WakeupPreview) => w.filter_actor_name ||+ (w.filter_actor_type === "member" ? t(($) => $.wakeups.selected_member) : t(($) => $.wakeups.selected_agent));+ const eventCondition = (event: string, w: WakeupPreview) => {+ const label = eventName(event, w.filter_agent_name || undefined);+ const actor = w.filter_actor_type ? actorName(w) : w.filter_agent_name;+ return actor && !event.startsWith("task.")+ ? t(($) => $.wakeups.by_actor, { condition: label, agent: actor })+ : label;+ };+ const trigger = (w: WakeupPreview) => {+ if (w.kind === "every" || w.kind === "cron") return schedule(w);+ if (w.kind === "at")+ return w.next_fire_at+ ? t(($) => $.wakeups.at_time, {+ time: time(w.next_fire_at, w.timezone),+ })+ : t(($) => $.wakeups.scheduled_time);+ const event = w.event_types[0] ?? "";+ let label = eventCondition(event, w);+ if (w.filter_task_id)+ label += ` · ${t(($) => $.wakeups.specific_run, { id: w.filter_task_id.slice(0, 8) })}`;+ return `${label}${w.event_types.length > 1 ? ` +${w.event_types.length - 1}` : ""}`;+ };+ const runLabels: Record<string, string> = {+ queued: t(($) => $.wakeups.run_states.queued),+ deferred: t(($) => $.wakeups.run_states.deferred),+ dispatched: t(($) => $.wakeups.run_states.dispatched),+ running: t(($) => $.wakeups.run_states.running),+ waiting_local_directory: t(+ ($) => $.wakeups.run_states.waiting_local_directory,+ ),+ completed: t(($) => $.wakeups.run_states.completed),+ failed: t(($) => $.wakeups.run_states.failed),+ cancelled: t(($) => $.wakeups.run_states.cancelled),+ };+ const runState = (status?: string | null) =>+ status ? (runLabels[status] ?? status) : t(($) => $.wakeups.no_run);+ const state = (w: Omit<IssueWakeup, "instruction">, closed = false) => {+ const key = wakeupState(w, closed);+ return key === "scheduled" && w.next_fire_at+ ? t(($) => $.wakeups.next_at, { time: time(w.next_fire_at, w.timezone) })+ : t(($) => $.wakeups.rule_states[key]);+ };+ const error = (err: unknown, fallback: string) => {+ const status =+ err && typeof err === "object" && "status" in err+ ? err.status+ : undefined;+ return status === 403+ ? t(($) => $.wakeups.permission_error)+ : status === 409+ ? t(($) => $.wakeups.conflict_error)+ : fallback;+ };+ return { eventName, eventCondition, actorName, trigger, schedule, frequency, runState, state, error };+}diff --git a/packages/views/issues/components/wakeups-section.test.tsx b/packages/views/issues/components/wakeups-section.test.tsxnew file mode 100644index 0000000000..7b41270f6f--- /dev/null+++ b/packages/views/issues/components/wakeups-section.test.tsx@@ -0,0 +1,268 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { fireEvent, screen, waitFor } from "@testing-library/react";+import type { IssueWakeup } from "@multica/core/types";+import { renderWithI18n } from "../../test/i18n";+import { WakeupsSection } from "./wakeups-section";+const mutate = vi.fn();+const enable = vi.fn();+let pending = false;+let wakeup: IssueWakeup;+let status = "queued";+vi.mock("@multica/core/paths", () => ({+ useCurrentWorkspace: () => ({ id: "ws" }),+}));+vi.mock("@multica/core/issues", () => ({+ issueWakeupsOptions: () => ({ queryKey: ["wakeups"] }),+ issueTasksOptions: () => ({ queryKey: ["tasks"] }),+ useDisableIssueWakeup: () => ({ mutate, isPending: false }),+ useEnableIssueWakeup: () => ({ mutateAsync: enable, isPending: pending }),+}));+vi.mock("@tanstack/react-query", () => ({+ useQuery: ({ queryKey }: { queryKey: string[] }) => ({+ data: queryKey[0] === "wakeups" ? [wakeup] : [{ id: "task", status }],+ }),+}));+vi.mock("../../common/task-transcript", () => ({+ TranscriptButton: () => <button>Transcript</button>,+}));+vi.mock("./wakeup-instruction-editor", () => ({+ WakeupInstructionEditor: () => <button>Edit prompt</button>,+}));+beforeEach(() => {+ mutate.mockReset();+ enable.mockReset().mockResolvedValue(undefined);+ pending = false;+ status = "queued";+ wakeup = {+ id: "wake",+ revision: 2,+ issue_id: "issue",+ agent_id: "agent",+ agent_name: "Emacs",+ instruction: "Check CI",+ kind: "every",+ mode: "continuous",+ event_types: [],+ interval_seconds: 3600,+ enabled: true,+ disabled_at: null,+ last_task_id: "task",+ last_error: null,+ timezone: "UTC",+ next_fire_at: null,+ cron_expression: null,+ filter_agent_id: null,+ filter_task_id: null,+ };+});+describe("Wakeups sidebar", () => {+ it("describes hourly schedules without exposing interval seconds", () => {+ renderWithI18n(<WakeupsSection issueId="issue" />, { locale: "zh-Hans" });+ expect(screen.getByRole("button", { name: /唤醒 Emacs/ })).toHaveTextContent("每小时唤醒");+ expect(screen.queryByText(/3600/)).toBeNull();+ });+ it("describes a daily cron and preserves its expression in details", async () => {+ wakeup.kind = "cron";+ wakeup.cron_expression = "0 9 * * *";+ renderWithI18n(<WakeupsSection issueId="issue" />);+ const row = screen.getByRole("button", { name: /Wake Emacs/ });+ expect(row).toHaveTextContent("09:00");+ expect(row).not.toHaveTextContent("0 9 * * *");+ fireEvent.click(row);+ await waitFor(() => expect(screen.getByText("0 9 * * * · UTC")).toBeVisible());+ });+ it("exposes the toggle and reveals the full prompt only on opening details", async () => {+ renderWithI18n(<WakeupsSection issueId="issue" />);+ expect(screen.queryByText("Check CI")).not.toBeVisible();+ fireEvent.click(screen.getByRole("switch", { name: "Wakeup for Emacs" }));+ expect(mutate).toHaveBeenCalledWith("wake", expect.any(Object));+ fireEvent.click(screen.getByRole("button", { name: /Wake Emacs/ }));+ await waitFor(() => expect(screen.getByText("Check CI")).toBeVisible());+ expect(screen.getByRole("button", { name: "Transcript" })).toBeVisible();+ expect(screen.getByRole("button", { name: "Edit prompt" })).toBeVisible();+ });+ it("keeps a consumed one-shot queued run in the current list with withdrawal", () => {+ wakeup.enabled = false;+ wakeup.kind = "event";+ wakeup.mode = "once";+ wakeup.event_types = ["task.completed"];+ renderWithI18n(<WakeupsSection issueId="issue" />);+ expect(screen.queryByText(/Wakeup history/)).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "Cancel this execution" }));+ expect(mutate).toHaveBeenCalled();+ });+ it("keeps an already claimed single run visible without offering withdrawal", () => {+ wakeup.enabled = false;+ status = "running";+ renderWithI18n(<WakeupsSection issueId="issue" />);+ expect(screen.queryByText(/Wakeup history/)).toBeNull();+ expect(+ screen.queryByRole("button", { name: /Turn off wakeup/ }),+ ).toBeNull();+ expect(screen.getByRole("button", { name: /Wake Emacs/ })).toBeVisible();+ });+ it("folds ended configurations into history with an off toggle", () => {+ wakeup.enabled = false;+ status = "completed";+ renderWithI18n(<WakeupsSection issueId="issue" />);+ expect(screen.queryByRole("button", { name: /Wake Emacs/ })).toBeNull();+ expect(screen.queryByRole("switch")).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "Wakeup history 1" }));+ expect(screen.getByRole("button", { name: /Wake Emacs/ })).toBeVisible();+ });+ it("uses server run status while the run detail query is still incomplete", () => {+ wakeup.enabled = false;+ wakeup.last_task_id = "missing";+ wakeup.last_task_status = "dispatched";+ renderWithI18n(<WakeupsSection issueId="issue" />);+ expect(screen.queryByText(/Wakeup history/)).toBeNull();+ expect(+ screen.queryByRole("button", { name: /Turn off wakeup/ }),+ ).toBeNull();+ });+});++it("re-enables a manually disabled recurring configuration with its revision", async () => {+ wakeup.enabled = false;+ wakeup.disabled_at = "2026-09-16T00:00:00Z";+ status = "completed";+ renderWithI18n(<WakeupsSection issueId="issue" />);+ fireEvent.click(screen.getByRole("button", { name: "Wakeup history 1" }));+ const toggle = screen.getByRole("switch", { name: "Wakeup for Emacs" });+ expect(toggle).not.toBeChecked();+ fireEvent.click(toggle);+ await waitFor(() =>+ expect(enable).toHaveBeenCalledWith({ id: "wake", revision: 2 }),+ );+ expect(toggle).not.toBeChecked(); // Wait for server state; no optimistic success.+});+it("blocks re-enabling on terminal issues", () => {+ wakeup.enabled = false;+ status = "completed";+ renderWithI18n(<WakeupsSection issueId="issue" closed />);+ fireEvent.click(screen.getByRole("button", { name: "Wakeup history 1" }));+ expect(screen.getByRole("switch")).toHaveAttribute("aria-disabled", "true");+ fireEvent.click(screen.getByRole("switch"));+ expect(enable).not.toHaveBeenCalled();+ expect(mutate).not.toHaveBeenCalled();+ expect(screen.getByText(/cannot be enabled/)).toBeVisible();+});+it("requires a new future time for an expired one-shot", async () => {+ wakeup.enabled = false;+ wakeup.disabled_at = "2020-01-01T00:00:00Z";+ wakeup.kind = "at";+ wakeup.mode = "once";+ wakeup.next_fire_at = "2020-01-01T00:00:00Z";+ status = "completed";+ renderWithI18n(<WakeupsSection issueId="issue" />);+ fireEvent.click(screen.getByRole("button", { name: "Wakeup history 1" }));+ expect(screen.queryByRole("switch")).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "Set a new time" }));+ const input = await screen.findByLabelText(/Time \(/);+ fireEvent.change(input, { target: { value: "2020-01-01T12:00" } });+ fireEvent.submit(input.closest("form")!);+ expect(await screen.findByRole("alert")).toHaveTextContent(+ "Choose a future time",+ );+ expect(enable).not.toHaveBeenCalled();+ fireEvent.change(input, { target: { value: "2099-01-01T12:00" } });+ fireEvent.submit(input.closest("form")!);+ await waitFor(() =>+ expect(enable).toHaveBeenCalledWith({+ id: "wake",+ revision: 2,+ at: new Date("2099-01-01T12:00").toISOString(),+ rearm: true,+ }),+ );+});+it("uses explicit resubscribe for a completed one-shot event", async () => {+ wakeup.enabled = false;+ wakeup.kind = "event";+ wakeup.mode = "once";+ status = "completed";+ renderWithI18n(<WakeupsSection issueId="issue" />);+ fireEvent.click(screen.getByRole("button", { name: "Wakeup history 1" }));+ expect(screen.queryByRole("switch")).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "Enable again" }));+ await waitFor(() =>+ expect(enable).toHaveBeenCalledWith({+ id: "wake",+ revision: 2,+ rearm: true,+ }),+ );+});+it("disables controls during a pending mutation", () => {+ pending = true;+ renderWithI18n(<WakeupsSection issueId="issue" />);+ expect(screen.getByRole("switch")).toHaveAttribute("aria-disabled", "true");+ fireEvent.click(screen.getByRole("switch"));+ expect(enable).not.toHaveBeenCalled();+ expect(mutate).not.toHaveBeenCalled();+});++it("describes the source condition in Chinese, keeping instructions in details", async () => {+ wakeup.kind = "event";+ wakeup.mode = "once";+ wakeup.event_types = ["task.completed", "task.failed"];+ wakeup.filter_agent_name = "Grok";+ wakeup.filter_agent_id = "grok";+ renderWithI18n(<WakeupsSection issueId="issue" />, { locale: "zh-Hans" });+ const trigger = screen.getByRole("button", { name: /当 Grok 的运行成功结束时/ });+ expect(trigger).toHaveTextContent("唤醒 Emacs · 仅触发一次");+ expect(screen.queryByText("Check CI")).not.toBeVisible();+ fireEvent.click(trigger);+ await waitFor(() => expect(screen.getByText("唤醒后要做什么")).toBeVisible());+ expect(screen.getByText(/以下任一事件发生时/)).toHaveTextContent("当 Grok 的运行失败时");+ expect(screen.getByText(/监听范围/)).toHaveTextContent("当前任务");+});++it("shows a disabled rule independently from its last successful execution", () => {+ wakeup.enabled = false;+ wakeup.disabled_at = "2026-09-16T00:00:00Z";+ status = "completed";+ renderWithI18n(<WakeupsSection issueId="issue" />);+ fireEvent.click(screen.getByRole("button", { name: "Wakeup history 1" }));+ const row = screen.getByRole("button", { name: /Wake Emacs/ });+ expect(row).toHaveTextContent("Turned off");+ expect(row).toHaveTextContent("Last execution: Run succeeded");+});++it("keeps a failed one-shot triggered without calling the rule completed", () => {+ wakeup.enabled = false;+ wakeup.kind = "event";+ wakeup.mode = "once";+ wakeup.event_types = ["comment.created"];+ status = "failed";+ renderWithI18n(<WakeupsSection issueId="issue" />);+ fireEvent.click(screen.getByRole("button", { name: "Wakeup history 1" }));+ const row = screen.getByRole("button", { name: /Wake Emacs/ });+ expect(row).toHaveTextContent("Triggered");+ expect(row).toHaveTextContent("This execution: Run failed");+ expect(row).not.toHaveTextContent("Completed");+});++it("names the monitored member in the condition and details", async () => {+ wakeup.kind = "event";+ wakeup.event_types = ["comment.created", "comment.updated"];+ wakeup.filter_actor_type = "member";+ wakeup.filter_actor_id = "member-id";+ wakeup.filter_actor_name = "Jiayuan";+ renderWithI18n(<WakeupsSection issueId="issue" />, { locale: "zh-Hans" });+ const trigger = screen.getByRole("button", { name: /由 Jiayuan 触发/ });+ expect(trigger).toHaveTextContent("Jiayuan");+ fireEvent.click(trigger);+ await waitFor(() => expect(screen.getByText(/监听的成员或智能体/)).toBeVisible());+ expect(screen.getByText(/以下任一事件发生时/)).toHaveTextContent("由 Jiayuan 触发");+});++it("keeps a redacted actor restriction visible without exposing an ID", () => {+ wakeup.kind = "event";+ wakeup.event_types = ["comment.created"];+ wakeup.filter_actor_type = "agent";+ wakeup.filter_actor_id = null;+ wakeup.filter_actor_name = null;+ renderWithI18n(<WakeupsSection issueId="issue" />);+ expect(screen.getByRole("button", { name: /triggered by Selected agent/ })).toBeInTheDocument();+});diff --git a/packages/views/issues/components/wakeups-section.tsx b/packages/views/issues/components/wakeups-section.tsxnew file mode 100644index 0000000000..18efb147ba--- /dev/null+++ b/packages/views/issues/components/wakeups-section.tsx@@ -0,0 +1,317 @@+"use client";++import { useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { Bell, Clock3, ChevronRight } from "lucide-react";+import { toast } from "sonner";+import {+ issueWakeupsOptions,+ useDisableIssueWakeup,+ useEnableIssueWakeup,+ issueTasksOptions,+} from "@multica/core/issues";+import type { AgentTask, IssueWakeup } from "@multica/core/types";+import { useCurrentWorkspace } from "@multica/core/paths";+import {+ Popover,+ PopoverTrigger,+ PopoverContent,+ PopoverTitle,+} from "@multica/ui/components/ui/popover";+import { WakeupInstructionEditor } from "./wakeup-instruction-editor";+import { WakeupControl } from "./wakeup-control";+import { TranscriptButton } from "../../common/task-transcript";+import { useT } from "../../i18n";+import {+ isCurrentWakeup,+ isActiveWakeupRun,+ useWakeupText,+ wakeupRun,+} from "./wakeup-presentation";++function WakeupRow({+ wakeup,+ task,+ sourceTask,+ pending,+ onDisable,+ onEnable,+ closed,+}: {+ wakeup: IssueWakeup;+ task?: AgentTask;+ sourceTask?: AgentTask;+ pending: boolean;+ onDisable: () => void;+ closed: boolean;+ onEnable: (input?: { at?: string; rearm?: boolean }) => Promise<void>;+}) {+ const { t } = useT("issues");+ const workspaceId = useCurrentWorkspace()?.id ?? "";+ const text = useWakeupText();+ const status = task?.status ?? wakeup.last_task_status;+ const activeRun = isActiveWakeupRun(status);+ const Icon = wakeup.kind === "event" ? Bell : Clock3;+ return (+ <div+ className="grid grid-cols-[minmax(0,1fr)_auto]"+ aria-busy={pending}+ >+ <Popover>+ <PopoverTrigger+ render={+ <button+ type="button"+ className="col-span-2 col-start-1 row-start-1 grid min-w-0 grid-cols-subgrid rounded-md py-1.5 text-left text-caption hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring"+ />+ }+ >+ <span className="flex min-h-8 min-w-0 items-center gap-2 pl-2 pr-1">+ <Icon+ className="size-3.5 shrink-0 text-muted-foreground"+ aria-hidden="true"+ />+ <span className="truncate font-medium">+ {text.trigger(wakeup)}+ </span>+ </span>+ <span className="col-span-2 min-w-0 break-words pl-7.5 pr-2">+ <span className="block text-muted-foreground">+ {t(($) => $.wakeups.wake_agent, { agent: wakeup.agent_name })} ·{" "}+ {wakeup.kind === "event" || wakeup.kind === "at"+ ? text.frequency(wakeup)+ : text.state(wakeup, closed)}+ {!wakeup.enabled &&+ (wakeup.kind === "event" || wakeup.kind === "at") && (+ <> · {text.state(wakeup, closed)}</>+ )}+ </span>+ {status && (+ <span className="block text-muted-foreground">+ {t(+ ($) =>+ activeRun || wakeup.mode === "once"+ ? $.wakeups.execution_summary+ : $.wakeups.recent_execution,+ { state: text.runState(status) },+ )}+ </span>+ )}+ {(wakeup.disabled_at || closed) && activeRun && (+ <span className="block text-muted-foreground">+ {t(($) => $.wakeups.stopped_running)}+ </span>+ )}+ {wakeup.last_error && (+ <span className="block text-destructive">+ {t(($) => $.wakeups.needs_attention)}+ </span>+ )}+ </span>+ </PopoverTrigger>+ <PopoverContent+ align="end"+ className="max-h-[70dvh] w-80 max-w-[calc(100vw-2rem)] overflow-y-auto"+ keepMounted+ >+ <PopoverTitle>{text.trigger(wakeup)}</PopoverTitle>+ <p className="text-caption text-muted-foreground">+ {t(($) => $.wakeups.wake_agent, { agent: wakeup.agent_name })} ·{" "}+ {text.schedule(wakeup)}+ </p>+ <p className="text-caption text-muted-foreground">+ {t(($) => $.wakeups.scope_title)}:{" "}+ {t(($) => $.wakeups.scope_current)}+ </p>+ <div className="flex items-center justify-between gap-2">+ <p className="text-caption font-medium">{t(($) => $.wakeups.instruction_title)}</p>+ <WakeupInstructionEditor workspaceId={workspaceId} issueId={wakeup.issue_id} wakeupId={wakeup.id} />+ </div>+ <p className="whitespace-pre-wrap break-words text-caption">+ {wakeup.instruction}+ </p>+ {wakeup.kind === "event" && (+ <p className="break-words text-caption text-muted-foreground">+ {t(($) => $.wakeups.any_event)}:{" "}+ {wakeup.event_types+ .map((event) =>+ text.eventCondition(event, wakeup),+ )+ .join("; ")}+ </p>+ )}+ {wakeup.filter_actor_type && (+ <p className="break-words text-caption text-muted-foreground">+ {t(($) => $.wakeups.source_actor)}: {text.actorName(wakeup)}+ </p>+ )}+ {wakeup.filter_agent_id && (+ <p className="break-all text-caption text-muted-foreground">+ {t(($) => $.wakeups.source_agent)}:{" "}+ {wakeup.filter_agent_name ?? wakeup.filter_agent_id}+ </p>+ )}+ {sourceTask && (+ <TranscriptButton+ task={sourceTask}+ agentName={wakeup.filter_agent_name ?? ""}+ title={t(($) => $.wakeups.source_run)}+ />+ )}+ {wakeup.filter_task_id && (+ <p className="break-all text-caption text-muted-foreground">+ {t(($) => $.wakeups.source_run)}: {wakeup.filter_task_id}+ </p>+ )}+ {wakeup.next_fire_at && (+ <p className="text-caption text-muted-foreground">+ {new Date(wakeup.next_fire_at).toLocaleString(undefined, {+ timeZone: wakeup.timezone,+ })}{" "}+ · {wakeup.timezone}+ </p>+ )}+ {wakeup.cron_expression && (+ <code className="block text-caption text-muted-foreground">+ {wakeup.cron_expression} · {wakeup.timezone}+ </code>+ )}+ {wakeup.last_error && (+ <p className="break-words text-caption text-destructive">+ {wakeup.last_error}+ </p>+ )}+ {task && (+ <div className="flex items-center gap-1 text-caption text-muted-foreground">+ <span>{t(($) => $.wakeups.last_run)}</span>+ <TranscriptButton+ task={task}+ agentName={wakeup.agent_name}+ title={t(($) => $.wakeups.last_run)}+ />+ </div>+ )}+ </PopoverContent>+ </Popover>+ <div className="z-10 col-start-2 row-start-1 self-start">+ <WakeupControl+ wakeup={wakeup}+ task={task}+ pending={pending}+ closed={closed}+ onDisable={onDisable}+ onEnable={onEnable}+ />+ </div>+ </div>+ );+}++export function WakeupsSection({+ issueId,+ closed = false,+}: {+ issueId: string;+ closed?: boolean;+}) {+ const { t } = useT("issues");+ const workspaceId = useCurrentWorkspace()?.id ?? "";+ const [open, setOpen] = useState(true);+ const [historyOpen, setHistoryOpen] = useState(false);+ const {+ data = [],+ isError,+ refetch,+ } = useQuery(issueWakeupsOptions(workspaceId, issueId));+ const { data: tasks = [] } = useQuery(issueTasksOptions(issueId));+ const text = useWakeupText();+ const disable = useDisableIssueWakeup(workspaceId, issueId);+ const enable = useEnableIssueWakeup(workspaceId, issueId);+ if (!data.length && !isError) return null;+ const current = data.filter((w) => isCurrentWakeup(w, wakeupRun(w, tasks)));+ const history = data.filter((w) => !isCurrentWakeup(w, wakeupRun(w, tasks)));+ const row = (wakeup: IssueWakeup) => (+ <WakeupRow+ key={wakeup.id}+ wakeup={wakeup}+ task={wakeupRun(wakeup, tasks)}+ sourceTask={tasks.find((task) => task.id === wakeup.filter_task_id)}+ pending={disable.isPending || enable.isPending}+ closed={closed}+ onEnable={async (input = {}) => {+ await enable.mutateAsync({+ id: wakeup.id,+ revision: wakeup.revision ?? 0,+ ...input,+ });+ }}+ onDisable={() =>+ disable.mutate(wakeup.id, {+ onError: (err) =>+ toast.error(+ text.error(+ err,+ t(($) => $.wakeups.disable_error),+ ),+ ),+ onSuccess: () => setHistoryOpen(true),+ })+ }+ />+ );+ return (+ <section>+ <button+ type="button"+ aria-expanded={open}+ onClick={() => setOpen(!open)}+ className="mb-1 flex min-h-9 w-full items-center gap-1 rounded-md px-2 py-1 text-caption font-medium hover:bg-accent/70 focus-visible:outline-2 focus-visible:outline-ring"+ >+ {t(($) => $.wakeups.title)}{" "}+ <span className="text-muted-foreground tabular-nums">+ {current.length}+ </span>+ <ChevronRight+ className={`size-3 text-muted-foreground ${open ? "rotate-90" : ""}`}+ aria-hidden="true"+ />+ </button>+ {open && (+ <div>+ {isError && (+ <button+ type="button"+ className="px-2 text-caption text-muted-foreground hover:text-foreground"+ onClick={() => void refetch()}+ >+ {t(($) => $.wakeups.retry)}+ </button>+ )}+ {closed && (+ <p className="px-2 text-caption text-muted-foreground">+ {t(($) => $.wakeups.closed_hint)}+ </p>+ )}+ {current.map(row)}+ {history.length > 0 && (+ <>+ <button+ type="button"+ aria-expanded={historyOpen}+ onClick={() => setHistoryOpen(!historyOpen)}+ className="flex min-h-9 w-full items-center gap-1 rounded-md px-2 py-1 text-caption text-muted-foreground hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring"+ >+ <ChevronRight+ className={`size-3 ${historyOpen ? "rotate-90" : ""}`}+ aria-hidden="true"+ />+ {t(($) => $.wakeups.ended, { count: history.length })}+ </button>+ {historyOpen && history.map(row)}+ </>+ )}+ </div>+ )}+ </section>+ );+}diff --git a/packages/views/issues/surface/activity.ts b/packages/views/issues/surface/activity.tsindex 60130924c0..5395a87566 100644--- a/packages/views/issues/surface/activity.ts+++ b/packages/views/issues/surface/activity.ts@@ -18,11 +18,11 @@ export interface IssueSurfaceActivity {runningIssueIds: Set<string>;}-function isQueuedTaskStatus(status: AgentTask["status"]) {+function isQueuedTaskStatus(status: AgentTask["status"], wakeupId?: string) {return (status === "queued" ||status === "dispatched" ||- status === "waiting_local_directory"+ status === "waiting_local_directory" || (status === "deferred" && !!wakeupId));}@@ -49,7 +49,7 @@ export function selectIssueTasks(for (const task of snapshot) {if (task.issue_id !== issueId) continue;if (task.status === "running") running.push(task);- else if (isQueuedTaskStatus(task.status)) queued.push(task);+ else if (isQueuedTaskStatus(task.status, task.wakeup_id)) queued.push(task);}return { running, queued };}@@ -61,7 +61,7 @@ export function deriveIssueSurfaceActivity(for (const task of tasks) {if (!task.issue_id) continue;- if (task.status !== "running" && !isQueuedTaskStatus(task.status)) {+ if (task.status !== "running" && !isQueuedTaskStatus(task.status, task.wakeup_id)) {continue;}diff --git a/packages/views/issues/surface/issue-surface.tsx b/packages/views/issues/surface/issue-surface.tsxindex 17ba2bb06f..6a0bf2e232 100644--- a/packages/views/issues/surface/issue-surface.tsx+++ b/packages/views/issues/surface/issue-surface.tsx@@ -9,6 +9,8 @@ import { Button } from "@multica/ui/components/ui/button";import { Skeleton } from "@multica/ui/components/ui/skeleton";import { cn } from "@multica/ui/lib/utils";import { useWorkspaceId } from "@multica/core/hooks";+import { useQuery } from "@tanstack/react-query";+import { workspaceWakeupSummariesOptions } from "@multica/core/issues/wakeups";import {useViewStore,ViewStoreProvider,@@ -194,6 +196,9 @@ function IssueSurfaceContent({batchToolbar,contentClassName,}: Omit<IssueSurfaceComponentProps, "surfaceKey">) {+ const workspaceId = useWorkspaceId();+ // One polling owner for the whole surface; individual cards only select cache data.+ useQuery({ ...workspaceWakeupSummariesOptions(workspaceId), refetchInterval: 10_000 });const { t } = useT("projects");const controller = useIssueSurfaceController({scope,diff --git a/packages/views/locales/en/autopilots.json b/packages/views/locales/en/autopilots.jsonindex dc90858d97..52771fa43d 100644--- a/packages/views/locales/en/autopilots.json+++ b/packages/views/locales/en/autopilots.json@@ -473,5 +473,53 @@"confirm": "Delete permanently","deleting": "Deleting…"}+ },+ "wakeups": {+ "title": "Issue wakeups",+ "scope": "Scope",+ "issue": "Issue",+ "trigger": "Trigger",+ "next": "Wakeup state",+ "enabled": "Enabled",+ "all_triggers": "All triggers",+ "event": "Event",+ "at": "One-time",+ "recurring": "Recurring",+ "all_agents": "All agents",+ "search": "Search issues or agents",+ "search_action": "Search",+ "running": "Running",+ "active_runs": "{{count}} active runs",+ "issue_closed": "Issue closed",+ "read_only": "Only the creator or a workspace admin can manage this wakeup",+ "select_row": "Select {{issue}}, {{agent}}",+ "select_page": "Select enabled wakeups on this page",+ "load_error": "Could not load wakeups",+ "loading": "Loading wakeups…",+ "empty": "No wakeup rules yet",+ "selected": "{{count}} selected",+ "disable_selected": "Turn off selected",+ "clear": "Clear selection",+ "results": "Page {{page}} · {{count}} results",+ "previous": "Previous",+ "next_page": "Next",+ "confirm_title": "Turn off {{count}} wakeups?",+ "confirm_body": "Future wakeups will stop. Runs still queued and not handed to an agent will be withdrawn. Dispatched runs will continue; stop them from the execution log.",+ "cancel": "Cancel",+ "confirm": "Turn off",+ "disabling": "Turning off…",+ "batch_result": "Turned off: {{succeeded}}. Failed: {{failed}}.",+ "scopes": {+ "active": "Waiting or executing",+ "all": "All",+ "disabled": "Turned off",+ "ended": "Ended"+ },+ "target_agent": "Wake agent",+ "wakeup_run": "Runs from wakeup",+ "empty_filtered": "No matching wakeups",+ "clear_filters": "Clear filters",+ "batch_success": "Turned off {{count}} wakeup rules",+ "batch_partial": "Turned off {{succeeded}}; {{failed}} failed. Failed items remain selected for retry."}}diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 946355f808..a150471b1a 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -940,5 +940,140 @@"surface_loading": "Loading {{name}}…","surface_unavailable": "{{name}} could not load its interface. The installed version may not include it.","surface_navigated": "{{name}} tried to replace its panel with a page loaded from elsewhere. It has been stopped and disconnected — tell your workspace admin."+ },+ "wakeups": {+ "title": "Wakeups",+ "retry": "Could not load wakeups. Retry",+ "every": "Every {{minutes}} min",+ "once": "Trigger once",+ "continuous": "Repeat wakeups",+ "disable": "Turn off wakeup for {{agent}}",+ "disable_error": "Could not turn off wakeup",+ "source_run": "Run being monitored",+ "source_agent": "Agent being monitored",+ "next": "Next:",+ "last_run": "View run record",+ "run_completed": "Run completed",+ "run_failed": "Run failed",+ "run_cancelled": "Run cancelled",+ "comment_created": "New comment",+ "status_changed": "Issue status changed",+ "run_queued": "Run queued",+ "run_dispatched": "Run dispatched",+ "run_started": "Run started",+ "run_deferred": "Run deferred",+ "run_waiting_local_directory": "Waiting for local directory",+ "issue_updated": "Issue updated",+ "assignee_changed": "Assignee changed",+ "parent_changed": "Parent issue changed",+ "project_changed": "Project changed",+ "labels_changed": "Labels changed",+ "properties_changed": "Properties changed",+ "metadata_changed": "Metadata changed",+ "comment_updated": "Comment edited",+ "comment_deleted": "Comment deleted",+ "comment_resolved": "Thread resolved",+ "comment_unresolved": "Thread reopened",+ "reaction_added": "Reaction added",+ "reaction_removed": "Reaction removed",+ "attachment_attached": "Attachment added",+ "attachment_detached": "Attachment removed",+ "at_time": "Wake at {{time}}",+ "wake_agent": "Wake {{agent}}",+ "needs_attention": "Needs attention",+ "turn_off": "Turn off",+ "ended": "Wakeup history {{count}}",+ "waiting_event": "Waiting for trigger",+ "triggered_by_wakeup": "Triggered by wakeup",+ "upcoming": "{{count}} enabled wakeup rules",+ "more": "{{count}} more",+ "toggle": "Wakeup for {{agent}}",+ "enable_error": "Could not enable wakeup. Try again.",+ "withdraw": "Cancel this execution",+ "resubscribe": "Enable again",+ "reschedule": "Set a new time",+ "future_time": "Choose a future time.",+ "local_time": "Time ({{timezone}})",+ "closed_hint": "Wakeups cannot be enabled while this issue is completed or canceled.",+ "completed": "Completed",+ "expired": "Expired",+ "disabled_state": "Turned off",+ "agent_subject": "an agent",+ "unknown_event": "When event {{event}} occurs",+ "source_actor": "Person or agent being monitored",+ "selected_member": "Selected member",+ "selected_agent": "Selected agent",+ "by_actor": "{{condition}} (triggered by {{agent}})",+ "specific_run": "Specific run {{id}}",+ "scheduled_time": "Wake at the scheduled time",+ "every_hours": "Wake every {{hours}} hours",+ "every_seconds": "Wake every {{seconds}} seconds",+ "edit_instruction": "Edit prompt",+ "instruction_effect": "Future wakeups use these instructions. Runs already in progress are not affected.",+ "instruction_loading": "Loading prompt...",+ "instruction_invalid": "Enter instructions within 12,000 UTF-8 bytes.",+ "instruction_save_error": "Could not save the prompt.",+ "instruction_cancel": "Cancel",+ "instruction_save": "Save",+ "instruction_saving": "Saving...",+ "instruction_title": "What to do when woken",+ "scope_title": "Monitored scope",+ "scope_current": "This issue",+ "any_event": "When any of these events occurs",+ "execution_summary": "This execution: {{state}}",+ "recent_execution": "Last execution: {{state}}",+ "stopped_running": "Future wakeups are off · An execution has not finished",+ "next_at": "Next: {{time}}",+ "no_run": "Not run yet",+ "permission_error": "You cannot manage this wakeup. Contact its creator or a workspace admin.",+ "conflict_error": "This rule has changed. Refresh and try again.",+ "conditions": {+ "run_queued": "When {{agent}}’s run is queued",+ "run_dispatched": "When a run is dispatched to {{agent}}",+ "run_started": "When {{agent}} starts a run",+ "run_deferred": "When {{agent}}’s run is deferred",+ "run_waiting_local_directory": "When {{agent}}’s run waits for a local directory",+ "issue_updated": "When this issue is updated",+ "assignee_changed": "When this issue’s assignee changes",+ "parent_changed": "When this issue’s parent changes",+ "project_changed": "When this issue’s project changes",+ "labels_changed": "When this issue’s labels change",+ "properties_changed": "When this issue’s properties change",+ "metadata_changed": "When this issue’s metadata changes",+ "comment_updated": "When a comment is edited",+ "comment_deleted": "When a comment is deleted",+ "comment_resolved": "When a thread is resolved",+ "comment_unresolved": "When a thread is reopened",+ "reaction_added": "When a reaction is added",+ "reaction_removed": "When a reaction is removed",+ "attachment_attached": "When an attachment is added to this issue",+ "attachment_detached": "When an attachment is removed from this issue",+ "run_completed": "When {{agent}} finishes a run successfully",+ "run_failed": "When {{agent}}’s run fails",+ "run_cancelled": "When {{agent}}’s run is cancelled",+ "comment_created": "When this issue receives a new comment",+ "status_changed": "When this issue’s status changes"+ },+ "rule_states": {+ "waiting": "Waiting for trigger",+ "scheduled": "Waiting for scheduled time",+ "disabled": "Turned off",+ "triggered": "Triggered",+ "expired": "Expired",+ "inactive": "Not enabled",+ "issue_closed": "Issue ended; wakeups stopped"+ },+ "run_states": {+ "queued": "Queued",+ "deferred": "Deferred",+ "dispatched": "Dispatched to agent",+ "running": "Running",+ "waiting_local_directory": "Waiting for local directory",+ "completed": "Run succeeded",+ "failed": "Run failed",+ "cancelled": "Cancelled"+ },+ "hourly": "Wake every hour",+ "today_time": "Today {{time}}"}}diff --git a/packages/views/locales/fr/autopilots.json b/packages/views/locales/fr/autopilots.jsonindex 0ba61ec528..deea859a91 100644--- a/packages/views/locales/fr/autopilots.json+++ b/packages/views/locales/fr/autopilots.json@@ -473,5 +473,53 @@"confirm": "Supprimer définitivement","deleting": "Suppression…"}+ },+ "wakeups": {+ "title": "Réveils de tâches",+ "scope": "Périmètre",+ "issue": "Tâche",+ "trigger": "Déclencheur",+ "next": "État du réveil",+ "enabled": "Activé",+ "all_triggers": "Tous les déclencheurs",+ "event": "Événement",+ "at": "Ponctuel",+ "recurring": "Récurrent",+ "all_agents": "Tous les agents",+ "search": "Rechercher des tâches ou agents",+ "search_action": "Rechercher",+ "running": "En cours",+ "active_runs": "{{count}} exécutions actives",+ "issue_closed": "Tâche fermée",+ "read_only": "Seuls le créateur ou un administrateur peuvent gérer ce réveil",+ "select_row": "Sélectionner {{issue}}, {{agent}}",+ "select_page": "Sélectionner les réveils activés sur cette page",+ "load_error": "Impossible de charger les réveils",+ "loading": "Chargement des réveils…",+ "empty": "Aucune règle de réveil",+ "selected": "{{count}} sélectionnés",+ "disable_selected": "Désactiver la sélection",+ "clear": "Effacer la sélection",+ "results": "Page {{page}} · {{count}} résultats",+ "previous": "Précédent",+ "next_page": "Suivant",+ "confirm_title": "Désactiver {{count}} réveils ?",+ "confirm_body": "Les réveils futurs seront arrêtés. Les exécutions en file non confiées à un agent seront retirées. Les exécutions déjà confiées continueront ; arrêtez-les depuis le journal d’exécution.",+ "cancel": "Annuler",+ "confirm": "Désactiver",+ "disabling": "Désactivation…",+ "batch_result": "Désactivés : {{succeeded}}. Échecs : {{failed}}.",+ "scopes": {+ "active": "En attente ou en cours",+ "all": "Tous",+ "disabled": "Désactivés",+ "ended": "Terminés"+ },+ "target_agent": "Agent à réveiller",+ "wakeup_run": "Exécutions du réveil",+ "empty_filtered": "Aucun réveil correspondant",+ "clear_filters": "Effacer les filtres",+ "batch_success": "{{count}} règles désactivées",+ "batch_partial": "{{succeeded}} désactivées ; {{failed}} échecs. Les éléments en échec restent sélectionnés pour réessayer."}}diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex 765ab404a3..c7a740b184 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -940,5 +940,140 @@"surface_loading": "Chargement de {{name}}…","surface_unavailable": "{{name}} n'a pas pu charger son interface. La version installée ne la contient peut-être pas.","surface_navigated": "{{name}} a tenté de remplacer son panneau par une page chargée depuis une autre source. Il a été arrêté et déconnecté : prévenez l'administrateur de votre espace de travail."+ },+ "wakeups": {+ "title": "Réveils",+ "retry": "Chargement impossible. Réessayer",+ "every": "Toutes les {{minutes}} min",+ "once": "Déclencher une fois",+ "continuous": "Réveils répétés",+ "disable": "Désactiver le réveil de {{agent}}",+ "disable_error": "Impossible de désactiver le réveil",+ "source_run": "Exécution surveillée",+ "source_agent": "Agent surveillé",+ "next": "Prochain :",+ "last_run": "Voir l’exécution",+ "run_completed": "Exécution terminée",+ "run_failed": "Échec de l’exécution",+ "run_cancelled": "Exécution annulée",+ "comment_created": "Nouveau commentaire",+ "status_changed": "Statut de la tâche modifié",+ "run_queued": "Exécution en attente",+ "run_dispatched": "Exécution envoyée",+ "run_started": "Exécution démarrée",+ "run_deferred": "Exécution différée",+ "run_waiting_local_directory": "En attente du répertoire local",+ "issue_updated": "Tâche mise à jour",+ "assignee_changed": "Responsable modifié",+ "parent_changed": "Tâche parente modifiée",+ "project_changed": "Projet modifié",+ "labels_changed": "Étiquettes modifiées",+ "properties_changed": "Propriétés modifiées",+ "metadata_changed": "Métadonnées modifiées",+ "comment_updated": "Commentaire modifié",+ "comment_deleted": "Commentaire supprimé",+ "comment_resolved": "Discussion résolue",+ "comment_unresolved": "Discussion rouverte",+ "reaction_added": "Réaction ajoutée",+ "reaction_removed": "Réaction supprimée",+ "attachment_attached": "Pièce jointe ajoutée",+ "attachment_detached": "Pièce jointe retirée",+ "at_time": "Réveil à {{time}}",+ "wake_agent": "Réveiller {{agent}}",+ "needs_attention": "Action requise",+ "turn_off": "Désactiver",+ "ended": "Historique des réveils {{count}}",+ "waiting_event": "En attente du déclencheur",+ "triggered_by_wakeup": "Déclenché par un réveil",+ "upcoming": "{{count}} règles de réveil activées",+ "more": "{{count}} de plus",+ "toggle": "Réveil de {{agent}}",+ "enable_error": "Impossible d’activer le réveil. Réessayez.",+ "withdraw": "Annuler cette exécution",+ "resubscribe": "Réactiver",+ "reschedule": "Choisir une nouvelle heure",+ "future_time": "Choisissez une date future.",+ "local_time": "Date ({{timezone}})",+ "closed_hint": "Impossible d’activer les réveils pour une tâche terminée ou annulée.",+ "completed": "Terminé",+ "expired": "Expiré",+ "disabled_state": "Désactivé",+ "agent_subject": "un agent",+ "unknown_event": "Quand l’événement {{event}} se produit",+ "source_actor": "Membre ou agent surveillé",+ "selected_member": "Membre sélectionné",+ "selected_agent": "Agent sélectionné",+ "by_actor": "{{condition}} (déclenché par {{agent}})",+ "specific_run": "Exécution précise {{id}}",+ "scheduled_time": "Réveil à l’heure prévue",+ "every_hours": "Réveil toutes les {{hours}} heures",+ "every_seconds": "Réveil toutes les {{seconds}} secondes",+ "edit_instruction": "Modifier le prompt",+ "instruction_effect": "Les prochains réveils utiliseront ces instructions. Les exécutions en cours ne sont pas affectées.",+ "instruction_loading": "Chargement du prompt...",+ "instruction_invalid": "Saisissez des instructions de 12 000 octets UTF-8 maximum.",+ "instruction_save_error": "Impossible d’enregistrer le prompt.",+ "instruction_cancel": "Annuler",+ "instruction_save": "Enregistrer",+ "instruction_saving": "Enregistrement...",+ "instruction_title": "Action au réveil",+ "scope_title": "Périmètre surveillé",+ "scope_current": "Cette tâche",+ "any_event": "Quand l’un de ces événements se produit",+ "execution_summary": "Cette exécution : {{state}}",+ "recent_execution": "Dernière exécution : {{state}}",+ "stopped_running": "Réveils futurs désactivés · Une exécution n’est pas terminée",+ "next_at": "Prochain : {{time}}",+ "no_run": "Pas encore exécuté",+ "permission_error": "Vous ne pouvez pas gérer ce réveil. Contactez son créateur ou un administrateur.",+ "conflict_error": "La règle a changé. Actualisez et réessayez.",+ "conditions": {+ "run_queued": "Quand une exécution de {{agent}} est mise en file",+ "run_dispatched": "Quand une exécution est confiée à {{agent}}",+ "run_started": "Quand {{agent}} démarre une exécution",+ "run_deferred": "Quand une exécution de {{agent}} est différée",+ "run_waiting_local_directory": "Quand une exécution de {{agent}} attend un dossier local",+ "issue_updated": "Quand cette tâche est modifiée",+ "assignee_changed": "Quand le responsable de cette tâche change",+ "parent_changed": "Quand la tâche parente change",+ "project_changed": "Quand le projet de cette tâche change",+ "labels_changed": "Quand les étiquettes de cette tâche changent",+ "properties_changed": "Quand les propriétés de cette tâche changent",+ "metadata_changed": "Quand les métadonnées de cette tâche changent",+ "comment_updated": "Quand un commentaire est modifié",+ "comment_deleted": "Quand un commentaire est supprimé",+ "comment_resolved": "Quand une discussion est résolue",+ "comment_unresolved": "Quand une discussion est rouverte",+ "reaction_added": "Quand une réaction est ajoutée",+ "reaction_removed": "Quand une réaction est supprimée",+ "attachment_attached": "Quand une pièce jointe est ajoutée à cette tâche",+ "attachment_detached": "Quand une pièce jointe est retirée de cette tâche",+ "run_completed": "Quand {{agent}} termine une exécution avec succès",+ "run_failed": "Quand une exécution de {{agent}} échoue",+ "run_cancelled": "Quand une exécution de {{agent}} est annulée",+ "comment_created": "Quand cette tâche reçoit un commentaire",+ "status_changed": "Quand le statut de cette tâche change"+ },+ "rule_states": {+ "waiting": "En attente du déclencheur",+ "scheduled": "En attente de l’heure prévue",+ "disabled": "Désactivé",+ "triggered": "Déclenché",+ "expired": "Expiré",+ "inactive": "Non activé",+ "issue_closed": "Tâche terminée ; réveils arrêtés"+ },+ "run_states": {+ "queued": "En file",+ "deferred": "Différée",+ "dispatched": "Confiée à l’agent",+ "running": "En cours",+ "waiting_local_directory": "En attente du dossier local",+ "completed": "Exécution réussie",+ "failed": "Échec de l’exécution",+ "cancelled": "Annulée"+ },+ "hourly": "Réveil chaque heure",+ "today_time": "Aujourd’hui {{time}}"}}diff --git a/packages/views/locales/ja/autopilots.json b/packages/views/locales/ja/autopilots.jsonindex 16131d812d..62e1365a00 100644--- a/packages/views/locales/ja/autopilots.json+++ b/packages/views/locales/ja/autopilots.json@@ -470,5 +470,53 @@"confirm": "完全に削除","deleting": "削除中…"}+ },+ "wakeups": {+ "title": "タスクのウェイクアップ",+ "scope": "範囲",+ "issue": "タスク",+ "trigger": "トリガー",+ "next": "ウェイクアップ状態",+ "enabled": "有効",+ "all_triggers": "すべてのトリガー",+ "event": "イベント",+ "at": "一回限り",+ "recurring": "繰り返し",+ "all_agents": "すべてのエージェント",+ "search": "タスク・エージェントを検索",+ "search_action": "検索",+ "running": "実行中",+ "active_runs": "{{count}} 件の実行が進行中",+ "issue_closed": "タスクは終了済み",+ "read_only": "作成者またはワークスペース管理者のみが管理できます",+ "select_row": "{{issue}}、{{agent}} を選択",+ "select_page": "このページの有効な項目を選択",+ "load_error": "読み込めませんでした",+ "loading": "読み込み中…",+ "empty": "ルールはまだありません",+ "selected": "{{count}} 件選択中",+ "disable_selected": "選択項目を無効化",+ "clear": "選択を解除",+ "results": "{{page}} ページ · {{count}} 件",+ "previous": "前へ",+ "next_page": "次へ",+ "confirm_title": "{{count}} 件を無効にしますか?",+ "confirm_body": "今後の起動を停止し、エージェントに渡されていない待機中の実行を取り消します。割り当て済みの実行は継続します。実行ログから停止できます。",+ "cancel": "キャンセル",+ "confirm": "無効にする",+ "disabling": "無効化中…",+ "batch_result": "無効化:{{succeeded}} 件。失敗:{{failed}} 件。",+ "scopes": {+ "active": "起動待ち・実行中",+ "all": "すべて",+ "disabled": "無効",+ "ended": "終了"+ },+ "target_agent": "起動するエージェント",+ "wakeup_run": "起動後の実行",+ "empty_filtered": "一致するルールがありません",+ "clear_filters": "フィルターを解除",+ "batch_success": "{{count}} 件のルールを無効化しました",+ "batch_partial": "{{succeeded}} 件を無効化、{{failed}} 件が失敗しました。失敗した項目を選択したまま再試行できます。"}}diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 640574274c..145e71095d 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -908,5 +908,140 @@"surface_loading": "{{name}} を読み込んでいます…","surface_unavailable": "{{name}} のインターフェースを読み込めません。インストール済みのバージョンに含まれていない可能性があります。","surface_navigated": "{{name}} がパネルを外部から読み込んだページに置き換えようとしました。停止して接続を切りました。ワークスペース管理者に知らせてください。"+ },+ "wakeups": {+ "title": "ウェイクアップ",+ "retry": "読み込めませんでした。再試行",+ "every": "{{minutes}} 分ごと",+ "once": "一度だけ起動",+ "continuous": "繰り返し起動",+ "disable": "{{agent}} のウェイクアップを停止",+ "disable_error": "停止できませんでした",+ "source_run": "監視対象の実行",+ "source_agent": "監視対象のエージェント",+ "next": "次回:",+ "last_run": "実行記録を見る",+ "run_completed": "実行完了",+ "run_failed": "実行失敗",+ "run_cancelled": "実行キャンセル",+ "comment_created": "新しいコメント",+ "status_changed": "タスクの状態変更",+ "run_queued": "実行がキューに追加",+ "run_dispatched": "実行を配信",+ "run_started": "実行開始",+ "run_deferred": "実行を延期",+ "run_waiting_local_directory": "ローカルディレクトリ待ち",+ "issue_updated": "タスクを更新",+ "assignee_changed": "担当者を変更",+ "parent_changed": "親タスクを変更",+ "project_changed": "プロジェクトを変更",+ "labels_changed": "ラベルを変更",+ "properties_changed": "プロパティを変更",+ "metadata_changed": "メタデータを変更",+ "comment_updated": "コメントを編集",+ "comment_deleted": "コメントを削除",+ "comment_resolved": "スレッドを解決",+ "comment_unresolved": "スレッドを再開",+ "reaction_added": "リアクションを追加",+ "reaction_removed": "リアクションを削除",+ "attachment_attached": "添付ファイルを追加",+ "attachment_detached": "添付ファイルを削除",+ "at_time": "{{time}} に起動",+ "wake_agent": "{{agent}} を起動",+ "needs_attention": "対応が必要",+ "turn_off": "オフにする",+ "ended": "ウェイクアップ履歴 {{count}}",+ "waiting_event": "トリガー待ち",+ "triggered_by_wakeup": "自動起動による実行",+ "upcoming": "有効なルール {{count}} 件",+ "more": "ほか {{count}} 件",+ "toggle": "{{agent}} の起動",+ "enable_error": "有効にできませんでした。再試行してください。",+ "withdraw": "今回の実行をキャンセル",+ "resubscribe": "再度有効にする",+ "reschedule": "時刻を再設定",+ "future_time": "未来の日時を選択してください。",+ "local_time": "日時({{timezone}})",+ "closed_hint": "課題が完了またはキャンセル済みのため、有効にできません。",+ "completed": "完了",+ "expired": "期限切れ",+ "disabled_state": "無効",+ "agent_subject": "エージェント",+ "unknown_event": "イベント {{event}} が発生したとき",+ "source_actor": "監視対象のメンバーまたはエージェント",+ "selected_member": "指定されたメンバー",+ "selected_agent": "指定されたエージェント",+ "by_actor": "{{condition}}({{agent}} による操作)",+ "specific_run": "指定した実行 {{id}}",+ "scheduled_time": "指定時刻に起動",+ "every_hours": "{{hours}} 時間ごとに起動",+ "every_seconds": "{{seconds}} 秒ごとに起動",+ "edit_instruction": "プロンプトを編集",+ "instruction_effect": "今後の起動には新しい指示を使用します。実行中の処理には影響しません。",+ "instruction_loading": "プロンプトを読み込み中...",+ "instruction_invalid": "指示を入力してください(UTF-8 で最大12,000バイト)。",+ "instruction_save_error": "プロンプトを保存できませんでした。",+ "instruction_cancel": "キャンセル",+ "instruction_save": "保存",+ "instruction_saving": "保存中...",+ "instruction_title": "起動後に行うこと",+ "scope_title": "監視範囲",+ "scope_current": "このタスク",+ "any_event": "次のいずれかのイベントが発生したとき",+ "execution_summary": "今回の実行:{{state}}",+ "recent_execution": "前回の実行:{{state}}",+ "stopped_running": "今後の起動は無効 · まだ終了していない実行があります",+ "next_at": "次回:{{time}}",+ "no_run": "未実行",+ "permission_error": "管理権限がありません。作成者または管理者に連絡してください。",+ "conflict_error": "ルールが更新されました。再読み込みしてください。",+ "conditions": {+ "run_queued": "{{agent}} の実行がキューに入ったとき",+ "run_dispatched": "実行が {{agent}} に割り当てられたとき",+ "run_started": "{{agent}} が実行を開始したとき",+ "run_deferred": "{{agent}} の実行が延期されたとき",+ "run_waiting_local_directory": "{{agent}} の実行がローカルディレクトリを待つとき",+ "issue_updated": "このタスクが更新されたとき",+ "assignee_changed": "このタスクの担当者が変わったとき",+ "parent_changed": "このタスクの親タスクが変わったとき",+ "project_changed": "このタスクのプロジェクトが変わったとき",+ "labels_changed": "このタスクのラベルが変わったとき",+ "properties_changed": "このタスクのプロパティが変わったとき",+ "metadata_changed": "このタスクのメタデータが変わったとき",+ "comment_updated": "コメントが編集されたとき",+ "comment_deleted": "コメントが削除されたとき",+ "comment_resolved": "スレッドが解決済みになったとき",+ "comment_unresolved": "スレッドが再開されたとき",+ "reaction_added": "リアクションが追加されたとき",+ "reaction_removed": "リアクションが削除されたとき",+ "attachment_attached": "このタスクに添付ファイルが追加されたとき",+ "attachment_detached": "このタスクの添付ファイルが削除されたとき",+ "run_completed": "{{agent}} の実行が成功したとき",+ "run_failed": "{{agent}} の実行が失敗したとき",+ "run_cancelled": "{{agent}} の実行がキャンセルされたとき",+ "comment_created": "このタスクに新しいコメントが届いたとき",+ "status_changed": "このタスクのステータスが変わったとき"+ },+ "rule_states": {+ "waiting": "トリガー待ち",+ "scheduled": "指定時刻待ち",+ "disabled": "無効",+ "triggered": "起動済み",+ "expired": "期限切れ",+ "inactive": "未有効化",+ "issue_closed": "タスク終了により無効"+ },+ "run_states": {+ "queued": "キュー待ち",+ "deferred": "延期",+ "dispatched": "エージェントに割り当て済み",+ "running": "実行中",+ "waiting_local_directory": "ローカルディレクトリ待ち",+ "completed": "実行成功",+ "failed": "実行失敗",+ "cancelled": "キャンセル済み"+ },+ "hourly": "毎時起動",+ "today_time": "今日 {{time}}"}}diff --git a/packages/views/locales/ko/autopilots.json b/packages/views/locales/ko/autopilots.jsonindex 04f618a7d4..006c7014c5 100644--- a/packages/views/locales/ko/autopilots.json+++ b/packages/views/locales/ko/autopilots.json@@ -470,5 +470,53 @@"confirm": "영구 삭제","deleting": "삭제 중…"}+ },+ "wakeups": {+ "title": "작업 깨우기",+ "scope": "범위",+ "issue": "작업",+ "trigger": "트리거",+ "next": "깨우기 상태",+ "enabled": "활성화",+ "all_triggers": "모든 트리거",+ "event": "이벤트",+ "at": "일회성",+ "recurring": "반복",+ "all_agents": "모든 에이전트",+ "search": "작업 또는 에이전트 검색",+ "search_action": "검색",+ "running": "실행 중",+ "active_runs": "진행 중인 실행 {{count}}개",+ "issue_closed": "종료된 작업",+ "read_only": "생성자 또는 워크스페이스 관리자만 관리할 수 있습니다",+ "select_row": "{{issue}}, {{agent}} 선택",+ "select_page": "이 페이지의 활성 항목 선택",+ "load_error": "깨우기를 불러오지 못했습니다",+ "loading": "불러오는 중…",+ "empty": "깨우기 규칙이 없습니다",+ "selected": "{{count}}개 선택됨",+ "disable_selected": "선택 항목 끄기",+ "clear": "선택 해제",+ "results": "{{page}}페이지 · {{count}}개",+ "previous": "이전",+ "next_page": "다음",+ "confirm_title": "깨우기 {{count}}개를 끄시겠습니까?",+ "confirm_body": "이후 깨우기를 중지하고 아직 에이전트에게 전달되지 않은 대기 중 실행을 취소합니다. 전달된 실행은 계속되며 실행 로그에서 중지할 수 있습니다.",+ "cancel": "취소",+ "confirm": "끄기",+ "disabling": "끄는 중…",+ "batch_result": "꺼짐: {{succeeded}}개. 실패: {{failed}}개.",+ "scopes": {+ "active": "깨우기 대기 또는 실행 중",+ "all": "전체",+ "disabled": "꺼짐",+ "ended": "종료됨"+ },+ "target_agent": "깨울 에이전트",+ "wakeup_run": "깨운 후 실행",+ "empty_filtered": "일치하는 깨우기가 없습니다",+ "clear_filters": "필터 지우기",+ "batch_success": "깨우기 규칙 {{count}}개를 껐습니다",+ "batch_partial": "{{succeeded}}개를 껐고 {{failed}}개는 실패했습니다. 실패 항목은 선택된 상태로 남아 다시 시도할 수 있습니다."}}diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex cd0b3c7a7e..93107faf05 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -908,5 +908,140 @@"surface_loading": "{{name}} 불러오는 중…","surface_unavailable": "{{name}}의 인터페이스를 불러올 수 없습니다. 설치된 버전에 포함되어 있지 않을 수 있습니다.","surface_navigated": "{{name}}이(가) 패널을 외부에서 불러온 페이지로 바꾸려 했습니다. 중지하고 연결을 끊었습니다. 워크스페이스 관리자에게 알리세요."+ },+ "wakeups": {+ "title": "깨우기",+ "retry": "불러오지 못했습니다. 다시 시도",+ "every": "{{minutes}}분마다",+ "once": "한 번만 트리거",+ "continuous": "반복 깨우기",+ "disable": "{{agent}} 깨우기 끄기",+ "disable_error": "깨우기를 끌 수 없습니다",+ "source_run": "감시할 실행",+ "source_agent": "감시할 에이전트",+ "next": "다음:",+ "last_run": "실행 기록 보기",+ "run_completed": "실행 완료",+ "run_failed": "실행 실패",+ "run_cancelled": "실행 취소",+ "comment_created": "새 댓글",+ "status_changed": "작업 상태 변경",+ "run_queued": "실행 대기열에 추가됨",+ "run_dispatched": "실행 전달됨",+ "run_started": "실행 시작됨",+ "run_deferred": "실행 연기됨",+ "run_waiting_local_directory": "로컬 디렉터리 대기 중",+ "issue_updated": "태스크 업데이트됨",+ "assignee_changed": "담당자 변경됨",+ "parent_changed": "상위 태스크 변경됨",+ "project_changed": "프로젝트 변경됨",+ "labels_changed": "라벨 변경됨",+ "properties_changed": "속성 변경됨",+ "metadata_changed": "메타데이터 변경됨",+ "comment_updated": "댓글 수정됨",+ "comment_deleted": "댓글 삭제됨",+ "comment_resolved": "스레드 해결됨",+ "comment_unresolved": "스레드 다시 열림",+ "reaction_added": "반응 추가됨",+ "reaction_removed": "반응 삭제됨",+ "attachment_attached": "첨부 파일 추가됨",+ "attachment_detached": "첨부 파일 삭제됨",+ "at_time": "{{time}}에 깨우기",+ "wake_agent": "{{agent}} 깨우기",+ "needs_attention": "확인 필요",+ "turn_off": "끄기",+ "ended": "깨우기 기록 {{count}}",+ "waiting_event": "트리거 대기 중",+ "triggered_by_wakeup": "자동 깨우기로 시작됨",+ "upcoming": "활성 깨우기 규칙 {{count}}개",+ "more": "{{count}}개 더",+ "toggle": "{{agent}} 깨우기",+ "enable_error": "깨우기를 활성화하지 못했습니다. 다시 시도하세요.",+ "withdraw": "이번 실행 취소",+ "resubscribe": "다시 활성화",+ "reschedule": "시간 다시 설정",+ "future_time": "미래 시간을 선택하세요.",+ "local_time": "시간 ({{timezone}})",+ "closed_hint": "이슈가 완료되거나 취소되어 활성화할 수 없습니다.",+ "completed": "완료됨",+ "expired": "만료됨",+ "disabled_state": "꺼짐",+ "agent_subject": "에이전트",+ "unknown_event": "{{event}} 이벤트가 발생할 때",+ "source_actor": "감시할 멤버 또는 에이전트",+ "selected_member": "지정된 멤버",+ "selected_agent": "지정된 에이전트",+ "by_actor": "{{condition}} ({{agent}}에 의해 발생)",+ "specific_run": "지정 실행 {{id}}",+ "scheduled_time": "지정 시간에 깨우기",+ "every_hours": "{{hours}}시간마다 깨우기",+ "every_seconds": "{{seconds}}초마다 깨우기",+ "edit_instruction": "프롬프트 편집",+ "instruction_effect": "다음 깨우기부터 새 지침을 사용합니다. 진행 중인 실행에는 영향을 주지 않습니다.",+ "instruction_loading": "프롬프트 로딩 중...",+ "instruction_invalid": "지침을 입력하세요. UTF-8 기준 최대 12,000바이트입니다.",+ "instruction_save_error": "프롬프트를 저장할 수 없습니다.",+ "instruction_cancel": "취소",+ "instruction_save": "저장",+ "instruction_saving": "저장 중...",+ "instruction_title": "깨운 후 수행할 일",+ "scope_title": "감시 범위",+ "scope_current": "이 작업",+ "any_event": "다음 이벤트 중 하나가 발생할 때",+ "execution_summary": "이번 실행: {{state}}",+ "recent_execution": "최근 실행: {{state}}",+ "stopped_running": "이후 깨우기는 꺼짐 · 아직 끝나지 않은 실행이 있음",+ "next_at": "다음: {{time}}",+ "no_run": "아직 실행하지 않음",+ "permission_error": "관리 권한이 없습니다. 생성자 또는 관리자에게 문의하세요.",+ "conflict_error": "규칙이 변경되었습니다. 새로고침 후 다시 시도하세요.",+ "conditions": {+ "run_queued": "{{agent}}의 실행이 대기열에 들어갈 때",+ "run_dispatched": "실행이 {{agent}}에게 전달될 때",+ "run_started": "{{agent}}가 실행을 시작할 때",+ "run_deferred": "{{agent}}의 실행이 연기될 때",+ "run_waiting_local_directory": "{{agent}}의 실행이 로컬 디렉터리를 기다릴 때",+ "issue_updated": "이 작업이 수정될 때",+ "assignee_changed": "이 작업의 담당자가 바뀔 때",+ "parent_changed": "이 작업의 상위 작업이 바뀔 때",+ "project_changed": "이 작업의 프로젝트가 바뀔 때",+ "labels_changed": "이 작업의 라벨이 바뀔 때",+ "properties_changed": "이 작업의 속성이 바뀔 때",+ "metadata_changed": "이 작업의 메타데이터가 바뀔 때",+ "comment_updated": "댓글이 수정될 때",+ "comment_deleted": "댓글이 삭제될 때",+ "comment_resolved": "스레드가 해결될 때",+ "comment_unresolved": "스레드가 다시 열릴 때",+ "reaction_added": "반응이 추가될 때",+ "reaction_removed": "반응이 삭제될 때",+ "attachment_attached": "이 작업에 첨부 파일이 추가될 때",+ "attachment_detached": "이 작업의 첨부 파일이 삭제될 때",+ "run_completed": "{{agent}}의 실행이 성공적으로 끝날 때",+ "run_failed": "{{agent}}의 실행이 실패할 때",+ "run_cancelled": "{{agent}}의 실행이 취소될 때",+ "comment_created": "이 작업에 새 댓글이 달릴 때",+ "status_changed": "이 작업의 상태가 바뀔 때"+ },+ "rule_states": {+ "waiting": "트리거 대기 중",+ "scheduled": "지정 시간 대기 중",+ "disabled": "꺼짐",+ "triggered": "트리거됨",+ "expired": "만료됨",+ "inactive": "비활성",+ "issue_closed": "작업 종료로 깨우기 중지됨"+ },+ "run_states": {+ "queued": "대기열에 있음",+ "deferred": "연기됨",+ "dispatched": "에이전트에게 전달됨",+ "running": "실행 중",+ "waiting_local_directory": "로컬 디렉터리 대기 중",+ "completed": "실행 성공",+ "failed": "실행 실패",+ "cancelled": "취소됨"+ },+ "hourly": "매시간 깨우기",+ "today_time": "오늘 {{time}}"}}diff --git a/packages/views/locales/zh-Hans/autopilots.json b/packages/views/locales/zh-Hans/autopilots.jsonindex e7a9f0270f..317f262364 100644--- a/packages/views/locales/zh-Hans/autopilots.json+++ b/packages/views/locales/zh-Hans/autopilots.json@@ -470,5 +470,53 @@"confirm": "永久删除","deleting": "删除中…"}+ },+ "wakeups": {+ "title": "任务唤醒",+ "scope": "范围",+ "issue": "任务",+ "trigger": "触发条件",+ "next": "唤醒状态",+ "enabled": "开启",+ "all_triggers": "所有触发方式",+ "event": "事件",+ "at": "单次定时",+ "recurring": "周期",+ "all_agents": "所有智能体",+ "search": "搜索任务或智能体",+ "search_action": "搜索",+ "running": "运行中",+ "active_runs": "{{count}} 个运行未结束",+ "issue_closed": "任务已关闭",+ "read_only": "仅创建者或工作区管理员可管理此唤醒",+ "select_row": "选择 {{issue}},{{agent}}",+ "select_page": "选择本页已开启的唤醒",+ "load_error": "无法加载唤醒",+ "loading": "正在加载唤醒…",+ "empty": "暂无唤醒规则",+ "selected": "已选择 {{count}} 项",+ "disable_selected": "关闭所选",+ "clear": "清除选择",+ "results": "第 {{page}} 页 · 共 {{count}} 项",+ "previous": "上一页",+ "next_page": "下一页",+ "confirm_title": "关闭 {{count}} 个唤醒?",+ "confirm_body": "关闭后将停止后续唤醒,并撤回仍在排队、尚未交给智能体的运行。已交给智能体的运行会继续,可在执行日志中停止。",+ "cancel": "取消",+ "confirm": "关闭",+ "disabling": "正在关闭…",+ "batch_result": "已关闭 {{succeeded}} 项,失败 {{failed}} 项。",+ "scopes": {+ "active": "待唤醒或执行中",+ "all": "全部",+ "disabled": "已关闭",+ "ended": "已结束"+ },+ "target_agent": "唤醒对象",+ "wakeup_run": "唤醒后的运行",+ "empty_filtered": "没有匹配的唤醒",+ "clear_filters": "清除筛选",+ "batch_success": "已关闭 {{count}} 条唤醒",+ "batch_partial": "已关闭 {{succeeded}} 条,{{failed}} 条失败;失败项仍保留选中,可重试。"}}diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex 8d6a3c444b..1b0963e94e 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -908,5 +908,140 @@"surface_loading": "正在加载 {{name}}…","surface_unavailable": "{{name}} 的界面无法加载,已安装的版本可能不包含它。","surface_navigated": "{{name}} 试图把面板替换成从别处加载的页面。已经拦下并断开连接,建议告知工作区管理员。"+ },+ "wakeups": {+ "title": "唤醒",+ "retry": "唤醒加载失败,点击重试",+ "every": "每 {{minutes}} 分钟",+ "once": "仅触发一次",+ "continuous": "重复唤醒",+ "disable": "关闭 {{agent}} 的唤醒",+ "disable_error": "无法关闭唤醒",+ "source_run": "监听的运行",+ "source_agent": "监听的智能体",+ "next": "下次:",+ "last_run": "查看运行记录",+ "run_completed": "运行完成",+ "run_failed": "运行失败",+ "run_cancelled": "运行取消",+ "comment_created": "新增评论",+ "status_changed": "任务状态变化",+ "run_queued": "运行已排队",+ "run_dispatched": "运行已分发",+ "run_started": "运行已开始",+ "run_deferred": "运行已延后",+ "run_waiting_local_directory": "等待本地目录",+ "issue_updated": "任务已更新",+ "assignee_changed": "负责人变更",+ "parent_changed": "父任务变更",+ "project_changed": "项目变更",+ "labels_changed": "标签变更",+ "properties_changed": "属性变更",+ "metadata_changed": "元数据变更",+ "comment_updated": "评论已编辑",+ "comment_deleted": "评论已删除",+ "comment_resolved": "讨论已解决",+ "comment_unresolved": "讨论重新打开",+ "reaction_added": "新增表态",+ "reaction_removed": "移除表态",+ "attachment_attached": "关联附件",+ "attachment_detached": "移除附件",+ "at_time": "{{time}} 唤醒",+ "wake_agent": "唤醒 {{agent}}",+ "needs_attention": "需要处理",+ "turn_off": "关闭",+ "ended": "历史唤醒 {{count}}",+ "waiting_event": "等待触发",+ "triggered_by_wakeup": "由唤醒触发",+ "upcoming": "已开启 {{count}} 条唤醒规则",+ "more": "另有 {{count}} 条",+ "toggle": "{{agent}} 的唤醒",+ "enable_error": "无法启用唤醒,请重试。",+ "withdraw": "取消本次执行",+ "resubscribe": "再次启用",+ "reschedule": "重新设置时间",+ "future_time": "请选择未来的时间。",+ "local_time": "时间({{timezone}})",+ "closed_hint": "任务已完成或取消,无法启用唤醒。",+ "completed": "已完成",+ "expired": "已过期",+ "disabled_state": "已关闭",+ "agent_subject": "智能体",+ "unknown_event": "当事件 {{event}} 发生时",+ "source_actor": "监听的成员或智能体",+ "selected_member": "指定成员",+ "selected_agent": "指定智能体",+ "by_actor": "{{condition}}(由 {{agent}} 触发)",+ "specific_run": "指定运行 {{id}}",+ "scheduled_time": "指定时间唤醒",+ "every_hours": "每 {{hours}} 小时唤醒",+ "every_seconds": "每 {{seconds}} 秒唤醒",+ "edit_instruction": "编辑提示词",+ "instruction_effect": "后续唤醒使用新指令,正在执行的运行不受影响。",+ "instruction_loading": "正在加载提示词...",+ "instruction_invalid": "请输入指令,最多 12,000 个 UTF-8 字节。",+ "instruction_save_error": "无法保存提示词。",+ "instruction_cancel": "取消",+ "instruction_save": "保存",+ "instruction_saving": "保存中...",+ "instruction_title": "唤醒后要做什么",+ "scope_title": "监听范围",+ "scope_current": "当前任务",+ "any_event": "以下任一事件发生时",+ "execution_summary": "本次执行:{{state}}",+ "recent_execution": "最近一次:{{state}}",+ "stopped_running": "后续唤醒已关闭 · 仍有执行未结束",+ "next_at": "下次 {{time}}",+ "no_run": "尚未运行",+ "permission_error": "无管理权限,请联系创建者或工作区管理员。",+ "conflict_error": "规则已更新,请刷新后重试。",+ "conditions": {+ "run_queued": "当 {{agent}} 的运行进入队列时",+ "run_dispatched": "当运行被交给 {{agent}} 时",+ "run_started": "当 {{agent}} 开始运行时",+ "run_deferred": "当 {{agent}} 的运行被延后时",+ "run_waiting_local_directory": "当 {{agent}} 的运行等待本地目录时",+ "issue_updated": "当此任务被更新时",+ "assignee_changed": "当此任务的负责人变化时",+ "parent_changed": "当此任务的父任务变化时",+ "project_changed": "当此任务所属项目变化时",+ "labels_changed": "当此任务的标签变化时",+ "properties_changed": "当此任务的属性变化时",+ "metadata_changed": "当此任务的元数据变化时",+ "comment_updated": "当评论被编辑时",+ "comment_deleted": "当评论被删除时",+ "comment_resolved": "当讨论被标记为已解决时",+ "comment_unresolved": "当讨论被重新打开时",+ "reaction_added": "当新增表态时",+ "reaction_removed": "当表态被移除时",+ "attachment_attached": "当此任务关联新附件时",+ "attachment_detached": "当此任务移除附件时",+ "run_completed": "当 {{agent}} 的运行成功结束时",+ "run_failed": "当 {{agent}} 的运行失败时",+ "run_cancelled": "当 {{agent}} 的运行被取消时",+ "comment_created": "当此任务有新评论时",+ "status_changed": "当此任务的状态变化时"+ },+ "rule_states": {+ "waiting": "等待触发",+ "scheduled": "等待指定时间",+ "disabled": "已关闭",+ "triggered": "已触发",+ "expired": "已过期",+ "inactive": "未启用",+ "issue_closed": "任务已结束,唤醒已停用"+ },+ "run_states": {+ "queued": "排队中",+ "deferred": "已延后",+ "dispatched": "已交给智能体",+ "running": "运行中",+ "waiting_local_directory": "等待本地目录可用",+ "completed": "运行成功",+ "failed": "运行失败",+ "cancelled": "已取消"+ },+ "hourly": "每小时唤醒",+ "today_time": "今天 {{time}}"}}diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 32ea66f26c..bcc95f45c9 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -140,6 +140,20 @@ var pgBigmOperatorClass = extensionOperatorClass{// they are still pending: a fresh self-hosted install, which is exactly where an// interrupted build would otherwise leave a permanently unusable index.var concurrentIndexCleanups = map[string]string{+ "510_wakeup_id": "issue_wakeup_id_idx",+ "511_wakeup_issue": "issue_wakeup_issue_idx",+ "512_wakeup_due": "issue_wakeup_due_idx",+ "513_wakeup_receipt_id": "issue_wakeup_receipt_id_idx",+ "514_wakeup_receipt_key": "issue_wakeup_receipt_key_idx",+ "515_wakeup_receipt_pending": "issue_wakeup_receipt_pending_idx",+ "519_wakeup_event_issue": "idx_wakeup_event_issue",+ "521_wakeup_workspace_summary": "idx_wakeup_workspace_enabled",+ "522_wakeup_run_lookup": "agent_task_wakeup_lookup_idx",+ "524_wakeup_workspace_history": "issue_wakeup_workspace_history_idx",+ "525_wakeup_active_runs": "agent_task_wakeup_active_idx",+ "526_wakeup_terminal_runs": "agent_task_wakeup_terminal_idx",+ "527_wakeup_receipt_expiry": "issue_wakeup_receipt_expiry_idx",+ "529_wakeup_pending_event": "issue_wakeup_pending_event_idx","508_comment_agent_delivery_pending_index": "idx_comment_agent_delivery_task_pending","503_channel_reply_delivery_turn_index": "idx_channel_reply_delivery_turn","504_channel_reply_delivery_installation_index": "idx_channel_reply_delivery_installation",diff --git a/server/cmd/multica/cmd_issue_wakeup.go b/server/cmd/multica/cmd_issue_wakeup.gonew file mode 100644index 0000000000..49e9d1ba08--- /dev/null+++ b/server/cmd/multica/cmd_issue_wakeup.go@@ -0,0 +1,176 @@+package main++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "net/http"+ "net/url"+ "os"+ "time"++ "github.com/multica-ai/multica/server/internal/cli"+ "github.com/multica-ai/multica/server/pkg/eventcontract"+ "github.com/spf13/cobra"+)++func init() { issueCmd.AddCommand(newIssueWakeupCommand()) }++func newIssueWakeupCommand() *cobra.Command {+ wake := &cobra.Command{Use: "wakeup", Short: "Manage event and time wakeups that start ordinary runs"}+ wake.AddCommand(&cobra.Command{Use: "events", Short: "List supported event types and filters", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error {+ return cli.PrintJSON(os.Stdout, map[string]any{"event_types": eventcontract.WakeupTypes, "platform_only_event_types": eventcontract.LifecycleTypes, "platform_only_reason": "Creation precedes subscription; deletion withdraws the issue's wakeups. Cross-issue subscriptions are not supported.", "scope": "current issue", "filters": []string{"filter_agent_id (task events; legacy mutation alias)", "filter_task_id (task events only)", "filter_actor_type + filter_actor_id (member or agent; mutation events only)"}, "modes": []string{"once (default)", "continuous"}, "loop_protection": "Events from the registering run and runs started by the same rule are excluded when source identity is available. Cross-rule cycles are not prevented; avoid mutually triggering continuous comment subscriptions."})+ }})+ for _, action := range []string{"list", "get", "disable", "create", "update"} {+ action := action+ count := 1+ if action == "get" || action == "disable" || action == "update" {+ count = 2+ }+ use := action + " <issue-id>"+ if count == 2 {+ use += " <wakeup-id>"+ }+ c := &cobra.Command{Use: use, Args: cobra.ExactArgs(count), Short: action + " issue wakeups", RunE: func(cmd *cobra.Command, args []string) error { return runIssueWakeup(cmd, args, action) }}+ c.Flags().String("output", "json", "Output format (json or table)")+ if action == "create" || action == "update" {+ c.Long = "Create or replace the complete configuration. Events default to once; every/cron use continuous. Updating explicitly re-enables the configuration. Runs use normal comment delivery."+ c.Long += " For task events, use --task-id for one run or --filter-agent-id for its agent. For comment/issue/reaction/attachment changes, use --filter-actor-type member|agent with --filter-actor-id. To wait for a person to comment, use --event comment.created --filter-actor-type member --filter-actor-id USER_ID. Actor filters identify who made the change, not the original author of an edited comment. Without a source filter, all matching events on this issue can wake the target."+ c.Flags().String("agent-id", "", "Agent to wake (defaults to authenticated agent)")+ c.Flags().String("instruction", "", "Instruction for the next run")+ c.Flags().String("instruction-file", "", "Read instruction from a UTF-8 file")+ c.Flags().String("kind", "event", "event, at, every or cron")+ c.Flags().String("mode", "", "once or continuous")+ c.Flags().StringSlice("event", nil, "Event types (comma-separated); see wakeup events")+ c.Flags().String("filter-actor-type", "", "Event actor: member or agent (requires --filter-actor-id)")+ c.Flags().String("filter-actor-id", "", "Actor user/agent UUID in this workspace; mutation events only")+ c.Flags().String("filter-agent-id", "", "Run agent filter; legacy alias of actor=agent for mutation-only events")+ c.Flags().String("task-id", "", "Match this specific run; terminal state is checked on registration")+ c.Flags().String("parent", "", "Comment thread for result delivery")+ c.Flags().String("after", "", "Delay for at, e.g. 10m")+ c.Flags().String("at", "", "Single RFC3339 timestamp")+ c.Flags().String("every", "", "Fixed interval, e.g. 1h (minimum 1m)")+ c.Flags().String("cron", "", "Five-field cron expression")+ c.Flags().String("timezone", "UTC", "IANA timezone for cron")+ }+ wake.AddCommand(c)+ }+ return wake+}++func runIssueWakeup(cmd *cobra.Command, args []string, action string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()+ ref, err := resolveIssueRef(ctx, client, args[0])+ if err != nil {+ return err+ }+ path := "/api/issues/" + url.PathEscape(ref.ID) + "/wakeups"+ var result any+ if action == "list" || action == "get" {+ var rows []map[string]any+ if err = client.GetJSON(ctx, path, &rows); err != nil {+ return err+ }+ result = rows+ if action == "get" {+ result = nil+ for _, row := range rows {+ if strVal(row, "id") == args[1] {+ result = row+ break+ }+ }+ if result == nil {+ return fmt.Errorf("wakeup not found")+ }+ }+ } else if action == "disable" {+ var row map[string]any+ err = client.PostJSON(ctx, path+"/"+url.PathEscape(args[1])+"/disable", map[string]any{}, &row)+ result = row+ } else {+ body := map[string]any{}+ for flag, key := range map[string]string{"agent-id": "agent_id", "kind": "kind", "mode": "mode", "filter-agent-id": "filter_agent_id", "filter-actor-type": "filter_actor_type", "filter-actor-id": "filter_actor_id", "task-id": "filter_task_id", "parent": "parent_comment_id", "at": "at", "cron": "cron_expression", "timezone": "timezone"} {+ v, _ := cmd.Flags().GetString(flag)+ if v != "" {+ body[key] = v+ }+ }+ instruction, _, e := resolveTextFlag(cmd, "instruction")+ if e != nil {+ return e+ }+ body["instruction"] = instruction+ ev, _ := cmd.Flags().GetStringSlice("event")+ if len(ev) > 0 {+ body["event_types"] = ev+ }+ for flag, key := range map[string]string{"after": "after_seconds", "every": "interval_seconds"} {+ v, _ := cmd.Flags().GetString(flag)+ if v != "" {+ d, e := time.ParseDuration(v)+ if e != nil || d <= 0 || d%time.Second != 0 {+ return fmt.Errorf("--%s requires a positive whole-second duration", flag)+ }+ body[key] = int64(d / time.Second)+ }+ }+ var row map[string]any+ if action == "update" {+ err = client.PutJSON(ctx, path+"/"+url.PathEscape(args[1]), body, &row)+ } else {+ err = client.PostJSON(ctx, path, body, &row)+ if isWakeupSourceBusy(err) {+ // The server reports this only after rolling back the NOWAIT+ // transaction. Retry once after a short commit window; never retry+ // ambiguous transport failures or other non-idempotent POST errors.+ timer := time.NewTimer(250 * time.Millisecond)+ defer timer.Stop()+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-timer.C:+ err = client.PostJSON(ctx, path, body, &row)+ }+ }+ }+ result = row+ }+ if err != nil {+ return err+ }+ output, _ := cmd.Flags().GetString("output")+ if output == "table" {+ rows := []map[string]any{}+ switch r := result.(type) {+ case []map[string]any:+ rows = r+ case map[string]any:+ rows = append(rows, r)+ }+ cells := [][]string{}+ for _, r := range rows {+ cells = append(cells, []string{strVal(r, "id"), strVal(r, "kind"), strVal(r, "mode"), fmt.Sprint(r["enabled"]), strVal(r, "next_fire_at"), strVal(r, "last_task_id")})+ }+ cli.PrintTable(os.Stdout, []string{"ID", "KIND", "MODE", "ENABLED", "NEXT", "LAST RUN"}, cells)+ return nil+ }+ return cli.PrintJSON(os.Stdout, result)+}++func isWakeupSourceBusy(err error) bool {+ var httpErr *cli.HTTPError+ if !errors.As(err, &httpErr) || httpErr.StatusCode != http.StatusConflict {+ return false+ }+ var body struct {+ Code string `json:"code"`+ }+ return json.Unmarshal([]byte(httpErr.Body), &body) == nil && body.Code == "wakeup_source_busy"+}diff --git a/server/cmd/multica/cmd_issue_wakeup_test.go b/server/cmd/multica/cmd_issue_wakeup_test.gonew file mode 100644index 0000000000..f3fc9f8968--- /dev/null+++ b/server/cmd/multica/cmd_issue_wakeup_test.go@@ -0,0 +1,115 @@+package main++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "testing"+)++func TestIssueWakeupCLIPreservesInstructionAndDuration(t *testing.T) {+ t.Chdir(t.TempDir())+ const issue = "a57c0511-1ebc-471d-a314-438ca16cc75d"+ var body map[string]any+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != "POST" || r.URL.Path != "/api/issues/"+issue+"/wakeups" {+ t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)+ }+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Error(err)+ }+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "wake", "enabled": true, "kind": "at", "mode": "once"})+ }))+ defer srv.Close()+ t.Setenv("MULTICA_SERVER_URL", srv.URL)+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")+ const note = "检查部署\n保留真实换行"+ if err := os.WriteFile("instruction.md", []byte(note), 0600); err != nil {+ t.Fatal(err)+ }+ cmd := newIssueWakeupCommand()+ cmd.SetArgs([]string{"create", issue, "--kind", "at", "--after", "10m", "--instruction-file", "./instruction.md"})+ if err := cmd.Execute(); err != nil {+ t.Fatal(err)+ }+ if body["after_seconds"] != float64(600) || body["instruction"] != note {+ t.Fatalf("unexpected body %+v", body)+ }+}++func TestIssueWakeupCreateRetriesOnlyRolledBackSourceConflict(t *testing.T) {+ for _, tc := range []struct {+ name string+ status int+ body string+ want int+ success bool+ }{+ {"source busy", 409, `{"code":"wakeup_source_busy","error":"busy"}`, 2, false},+ {"source unlocked", 409, `{"code":"wakeup_source_busy","error":"busy"}`, 2, true},+ {"other conflict", 409, `{"code":"revision_conflict","error":"busy"}`, 1, false},+ {"server failure", 500, `{"error":"failed"}`, 1, false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Chdir(t.TempDir())+ calls := 0+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ calls+++ if tc.success && calls == 2 {+ w.WriteHeader(http.StatusCreated)+ _, _ = w.Write([]byte(`{"id":"wake","enabled":true}`))+ return+ }+ w.WriteHeader(tc.status)+ _, _ = w.Write([]byte(tc.body))+ }))+ defer srv.Close()+ t.Setenv("MULTICA_SERVER_URL", srv.URL)+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")+ cmd := newIssueWakeupCommand()+ cmd.SetArgs([]string{"create", "a57c0511-1ebc-471d-a314-438ca16cc75d", "--event", "task.completed", "--instruction", "inspect"})+ if (cmd.Execute() == nil) != tc.success || calls != tc.want {+ t.Fatalf("calls=%d want=%d", calls, tc.want)+ }+ })+ }+}++func TestIssueWakeupCLIActorFilter(t *testing.T) {+ t.Chdir(t.TempDir())+ const issue = "a57c0511-1ebc-471d-a314-438ca16cc75d"+ const person = "356c8712-6100-4fb2-ac42-513770588468"+ var body map[string]any+ var method string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ method = r.Method+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Error(err)+ }+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "wake", "enabled": true})+ }))+ defer srv.Close()+ t.Setenv("MULTICA_SERVER_URL", srv.URL)+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")+ for _, action := range []string{"create", "update"} {+ cmd := newIssueWakeupCommand()+ args := []string{action, issue}+ wantMethod := "POST"+ if action == "update" {+ args = append(args, "wake")+ wantMethod = "PUT"+ }+ args = append(args, "--event", "comment.created", "--filter-actor-type", "member", "--filter-actor-id", person, "--instruction", "wait")+ cmd.SetArgs(args)+ if err := cmd.Execute(); err != nil {+ t.Fatal(err)+ }+ if method != wantMethod || body["filter_actor_type"] != "member" || body["filter_actor_id"] != person {+ t.Fatalf("lost actor filter: %s %+v", method, body)+ }+ }+}diff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex 5fa135c206..cf862d43f9 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -797,6 +797,9 @@ func main() {// not fit). Crash recovery, occurrence-level idempotency, lease// theft, and retry are all reused from the manager + sys_cron_executions// — there is no separate goroutine for scheduled Autopilot anymore.+ if err := schedulerMgr.Register(scheduler.IssueWakeupJob(&service.IssueWakeupService{Tasks: taskSvc})); err != nil {+ slog.Error("scheduler: register issue wakeups", "error", err)+ }if err := schedulerMgr.Register(scheduler.AutopilotScheduleDispatchJob(pool, queries, autopilotSvc)); err != nil {slog.Warn("scheduler: failed to register autopilot_schedule_dispatch job", "error", err)}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 002e56bc5b..90315bf979 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1916,6 +1916,12 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/subscribe", h.SubscribeToIssue)r.Post("/unsubscribe", h.UnsubscribeFromIssue)r.Post("/unsubscribe/subtree", h.UnsubscribeFromIssueSubtree)+ r.Get("/wakeups", h.ListIssueWakeups)+ r.Post("/wakeups", h.CreateIssueWakeup)+ r.Put("/wakeups/{wakeupID}", h.CreateIssueWakeup)+ r.Post("/wakeups/{wakeupID}/disable", h.DisableIssueWakeup)+ r.Post("/wakeups/{wakeupID}/enable", h.EnableIssueWakeup)+ r.Patch("/wakeups/{wakeupID}/instruction", h.EditIssueWakeupInstruction)r.Get("/active-task", h.GetActiveTaskForIssue)r.Post("/tasks/{taskId}/cancel", h.CancelTask)r.Post("/rerun", h.RerunIssue)@@ -2243,6 +2249,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// Workspace-wide agent task snapshot for presence derivation:// every active task + each agent's most recent terminal task.r.Get("/api/agent-task-snapshot", h.ListWorkspaceAgentTaskSnapshot)+ r.Get("/api/issue-wakeup-summaries", h.ListWorkspaceWakeupSummaries)+ r.Get("/api/issue-wakeups", h.ListWorkspaceWakeups)// Independent workspace-level list backing the issues-header// "agents working" chip and its assignee-id Table filter.diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.goindex 05a97fbe72..37f6d1389c 100644--- a/server/internal/daemon/execenv/runtime_config_sections.go+++ b/server/internal/daemon/execenv/runtime_config_sections.go@@ -274,6 +274,7 @@ func writeAvailableCommands(b *strings.Builder, ctx TaskContextForEnv) {// ownership-only --no-start path if the command is hidden behind --help.b.WriteString("- `multica issue assign <id> (--to X | --to-id <uuid> | --unassign) [--no-start]` — change ownership. On assign/update/status, `--no-start` records the change without starting another run — use it when the work is already underway.\n")writeIssueStatusCommand(b, ctx)+ b.WriteString("- `multica issue wakeup <create|list|get|update|disable|events>` — persist an event or time wakeup on this issue, then finish the current run. Use `--event comment.created --filter-actor-type member --filter-actor-id USER_ID` to wait for a specific member to comment. See `multica issue wakeup --help` and the multica-platform issues reference.\n")b.WriteString("- `multica issue children <id> [--output json]` — list a parent's sub-issues grouped by stage.\n")b.WriteString("- `multica issue comment add <issue-id> [--content \"...\" | --content-file <path> | --content-stdin] [--parent <comment-id>] [--attachment <path>]` — post a comment. Agent-authored bodies MUST use `--content-file`; see `## Comment Formatting` for why. `multica issue comment add --help` for full flags.\n")b.WriteString("- `multica repo checkout <url> [--ref <branch-or-sha>] [--fresh]` — repository checkout on a dedicated branch. Re-running it keeps an existing checkout that has uncommitted or unpushed work, or is already on this task's branch, and only fetches. `--fresh` discards uncommitted and untracked files and starts a new branch; commits stay on the old branch, but push any you still need first.\n\n")diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.goindex 489d1d41f5..6a3c5e0b10 100644--- a/server/internal/daemon/prompt.go+++ b/server/internal/daemon/prompt.go@@ -199,6 +199,17 @@ func BuildPrompt(task Task, provider string, options ...PromptOption) string {}func buildPromptBody(task Task, provider string) string {+ if task.WakeupID != "" {+ var b strings.Builder+ fmt.Fprintf(&b, "You are running as a local coding agent for a Multica workspace.\n\nYour assigned issue ID is: %s\n\n[WAKEUP]\n%s\n\n", task.IssueID, task.HandoffNote)+ fmt.Fprintf(&b, "Start by running `multica issue get %s --output json`, then read current run/comment state. Decide whether the instruction's goal is met; the trigger reports a fact, not business completion. This is an ordinary run with normal result delivery.\n", task.IssueID)+ fmt.Fprintf(&b, "Scan comment threads with `multica issue comment list %s --roots-only --summary --compact --output json`, then expand relevant threads with `--thread <id> --tail 30`.\n", task.IssueID)+ fmt.Fprintf(&b, "Inspect this configuration with `multica issue wakeup get %s %s --output json`. If recurring work is no longer needed, disable it with `multica issue wakeup disable %s %s`.\n", task.IssueID, task.WakeupID, task.IssueID, task.WakeupID)+ if task.TriggerCommentID != "" {+ fmt.Fprintf(&b, "Post your result using `multica issue comment add %s --parent %s --content-file ./reply.md --output table && rm ./reply.md`. This is the original delivery thread, not a new comment trigger.\n", task.IssueID, task.TriggerCommentID)+ }+ return b.String()+ }if task.ChatSessionID != "" {return buildChatPrompt(task)}diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.goindex 0d8e13c798..183a7c1895 100644--- a/server/internal/daemon/types.go+++ b/server/internal/daemon/types.go@@ -143,7 +143,8 @@ type Task struct {QuickCreateDueDate string `json:"quick_create_due_date,omitempty"` // explicit calendar due date selected in quick-createQuickCreateAttachmentIDs []string `json:"quick_create_attachment_ids,omitempty"` // attachments uploaded in the quick-create prompt and bound by issue createQuickCreateSourceContext json.RawMessage `json:"quick_create_source_context,omitempty"` // immutable historical context, separate from the new instruction- HandoffNote string `json:"handoff_note,omitempty"` // legacy assignment handoff instruction; rendered only in the per-turn prompt+ WakeupID string `json:"wakeup_id,omitempty"`+ HandoffNote string `json:"handoff_note,omitempty"` // legacy assignment handoff instruction; rendered only in the per-turn promptSquadID string `json:"squad_id,omitempty"` // when the picker was a squad, the squad's UUID; Agent is still the resolved leaderSquadName string `json:"squad_name,omitempty"` // display name for the picker squad, used in prompt textdiff --git a/server/internal/daemon/wakeup_prompt_test.go b/server/internal/daemon/wakeup_prompt_test.gonew file mode 100644index 0000000000..0137475b87--- /dev/null+++ b/server/internal/daemon/wakeup_prompt_test.go@@ -0,0 +1,18 @@+package daemon++import (+ "strings"+ "testing"+)++func TestWakeupPromptPreservesInstructionAndDeliveryThread(t *testing.T) {+ p := BuildPrompt(Task{IssueID: "issue", WakeupID: "wake", TriggerCommentID: "original", TriggerCommentContent: "old instruction", HandoffNote: "task.completed run-x; check its result"}, "codex")+ for _, want := range []string{"[WAKEUP]", "check its result", "--parent original", "wakeup disable issue wake", "--roots-only"} {+ if !strings.Contains(p, want) {+ t.Errorf("missing %q", want)+ }+ }+ if strings.Contains(p, "[NEW COMMENT]") || strings.Contains(p, "old instruction") {+ t.Fatal("replayed the old comment instead of the wakeup")+ }+}diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 4356e4aae0..661acda1ca 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -506,11 +506,12 @@ type AgentTaskResponse struct {QuickCreateDueDate string `json:"quick_create_due_date,omitempty"` // explicit calendar due date selected in quick-createQuickCreateAttachmentIDs []string `json:"quick_create_attachment_ids,omitempty"` // attachment ids uploaded in the quick-create prompt and bound on issue createQuickCreateSourceContext json.RawMessage `json:"quick_create_source_context,omitempty"` // immutable historical context for source-context quick-create- HandoffNote string `json:"handoff_note,omitempty"` // legacy assignment handoff instruction retained for installed clients; rendered by the daemon only in the per-turn prompt- SquadID string `json:"squad_id,omitempty"` // for quick-create tasks where the picker was a squad; Agent is still the resolved leader- SquadName string `json:"squad_name,omitempty"` // display name for the picker squad- ParentIssueID string `json:"parent_issue_id,omitempty"` // for quick-create tasks opened from "Add sub issue" — UUID of the parent issue the new issue should be filed under- ParentIssueIdentifier string `json:"parent_issue_identifier,omitempty"` // human-readable identifier (e.g. MUL-123) of the quick-create parent issue, resolved on claim for prompt context+ WakeupID string `json:"wakeup_id,omitempty"`+ HandoffNote string `json:"handoff_note,omitempty"` // legacy assignment handoff instruction retained for installed clients; rendered by the daemon only in the per-turn prompt+ SquadID string `json:"squad_id,omitempty"` // for quick-create tasks where the picker was a squad; Agent is still the resolved leader+ SquadName string `json:"squad_name,omitempty"` // display name for the picker squad+ ParentIssueID string `json:"parent_issue_id,omitempty"` // for quick-create tasks opened from "Add sub issue" — UUID of the parent issue the new issue should be filed under+ ParentIssueIdentifier string `json:"parent_issue_identifier,omitempty"` // human-readable identifier (e.g. MUL-123) of the quick-create parent issue, resolved on claim for prompt context// RequestingUserName + RequestingUserProfileDescription mirror the user// the agent is acting on behalf of (see daemon/types.go). v1 sources them// from the runtime owner so they're populated for daemon runtimes and@@ -818,6 +819,10 @@ func taskToResponse(t db.AgentTaskQueue, workspaceID string) AgentTaskResponse {if t.BranchName.Valid {branchName = t.BranchName.String}+ var wakeupContext struct {+ ID string `json:"wakeup_id"`+ }+ _ = json.Unmarshal(t.Context, &wakeupContext)handoffNote := ""if t.HandoffNote.Valid {handoffNote = t.HandoffNote.String@@ -851,6 +856,7 @@ func taskToResponse(t db.AgentTaskQueue, workspaceID string) AgentTaskResponse {DeliveredCommentIDs: uuidStringsOrEmpty(t.DeliveredCommentIds),TriggerSummary: textToPtr(t.TriggerSummary),HandoffNote: handoffNote,+ WakeupID: wakeupContext.ID,WorkDir: workDir,RelativeWorkDir: relativeWorkDir(workDir, workspaceID, uuidToString(t.ID)),DurableWorkDir: durableWorkDir,diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex 9649d2706a..3d8a26b517 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -1703,6 +1703,7 @@ func taskCoversReplyParent(task db.AgentTaskQueue, parentID pgtype.UUID) bool {}func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)issueID := chi.URLParam(r, "id")issue, ok := h.loadIssueForUser(w, r, issueID)if !ok {@@ -1909,7 +1910,7 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {// still pins the requested set: an attachment deleted while this waited// is refused before the comment is committed, rather than the comment// committing without it.- tx, beginErr := h.TxStarter.Begin(r.Context())+ tx, beginErr := h.beginWakeupWrite(r.Context())if beginErr != nil {slog.Warn("create comment failed", append(logger.RequestAttrs(r), "error", beginErr, "issue_id", issueID)...)writeError(w, http.StatusInternalServerError, "failed to create comment: "+beginErr.Error())@@ -1937,7 +1938,9 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {err = tx.Commit(r.Context())}} else {- created, err = h.Queries.CreateComment(r.Context(), createParams)+ created, err = wakeupWrite(h, r, func(q *db.Queries) (db.CreateCommentRow, error) {+ return q.CreateComment(r.Context(), createParams)+ })}if errors.Is(err, pgx.ErrNoRows) {// The issue was deleted, possibly while this waited for its row lock.@@ -1969,7 +1972,7 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {// so the reply is visible regardless of the unresolve outcome. Shared with// the agent task path (TaskService.createAgentComment) — both reply paths// must keep the resolved root in sync.- h.TaskService.AutoUnresolveThreadOnReply(r.Context(), rootComment, uuidToString(issue.WorkspaceID), authorType, authorID)+ h.TaskService.AutoUnresolveThreadOnReply(r.Context(), rootComment, uuidToString(issue.WorkspaceID), authorType, authorID, h.wakeupSourceTaskID(r))originatorUserID := h.invokeOriginatorFromRequest(r, authorType, authorID)// The comment is already saved; a blocked mention must not fail the whole@@ -3417,6 +3420,7 @@ func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issu}func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)commentId := chi.URLParam(r, "commentId")userID, ok := requireUserID(w, r)@@ -3572,7 +3576,7 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {// lock before the attachment replacement, so two modern editors cannot// interleave their CAS check and attachment selection. A body + attachment// edit is one visible mutation and therefore bumps revision exactly once.- tx, beginErr := h.TxStarter.Begin(r.Context())+ tx, beginErr := h.beginWakeupWrite(r.Context())if beginErr != nil {writeError(w, http.StatusInternalServerError, "failed to prepare comment edit")return@@ -3613,7 +3617,9 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {}} else {var updated db.UpdateCommentRow- updated, err = h.Queries.UpdateComment(r.Context(), updateParams)+ updated, err = wakeupWrite(h, r, func(q *db.Queries) (db.UpdateCommentRow, error) {+ return q.UpdateComment(r.Context(), updateParams)+ })if err == nil {comment = updated.Comment()issueRevision = updated.IssueRevision@@ -3683,6 +3689,7 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {}func (h *Handler) DeleteComment(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)commentId := chi.URLParam(r, "commentId")userID, ok := requireUserID(w, r)@@ -3848,7 +3855,7 @@ func lockCommentAttachments(ctx context.Context, qtx *db.Queries, workspaceID, i// when the delete commits while this waits. Returns pgx.ErrNoRows when the// comment is gone or deleted.func (h *Handler) withLiveCommentLock(ctx context.Context, commentID, workspaceID pgtype.UUID, write func(*db.Queries) error) error {- tx, err := h.TxStarter.Begin(ctx)+ tx, err := h.beginWakeupWrite(ctx)if err != nil {return err}@@ -3876,7 +3883,7 @@ const commentTombstonePruneDepth = 256// Returns pgx.ErrNoRows when the comment is already gone or already deleted.func (h *Handler) deleteComment(ctx context.Context, commentID, workspaceID pgtype.UUID) (commentDeletion, error) {var out commentDeletion- tx, err := h.TxStarter.Begin(ctx)+ tx, err := h.beginWakeupWrite(ctx)if err != nil {return out, err}@@ -4108,6 +4115,7 @@ func (h *Handler) loadCommentForActor(w http.ResponseWriter, r *http.Request) (d}func (h *Handler) ResolveComment(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)comment, workspaceID, actorType, actorID, ok := h.loadCommentForActor(w, r)if !ok {return@@ -4124,7 +4132,7 @@ func (h *Handler) ResolveComment(w http.ResponseWriter, r *http.Request) {// resolving this one must clear any other resolution in the same thread. Both// writes run in one tx — clearing the old resolution and setting the new one// is atomic, so a crash can never leave two resolutions (or none) visible.- tx, err := h.TxStarter.Begin(r.Context())+ tx, err := h.beginWakeupWrite(r.Context())if err != nil {writeError(w, http.StatusInternalServerError, "failed to resolve comment")return@@ -4194,13 +4202,16 @@ func (h *Handler) ResolveComment(w http.ResponseWriter, r *http.Request) {}func (h *Handler) UnresolveComment(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)comment, workspaceID, actorType, actorID, ok := h.loadCommentForActor(w, r)if !ok {return}wasResolved := comment.ResolvedAt.Valid- updated, err := h.Queries.UnresolveComment(r.Context(), comment.ID)+ updated, err := wakeupWrite(h, r, func(q *db.Queries) (db.Comment, error) {+ return q.UnresolveComment(r.Context(), comment.ID)+ })if err != nil {slog.Warn("unresolve comment failed", append(logger.RequestAttrs(r), "error", err, "comment_id", uuidToString(comment.ID))...)writeError(w, http.StatusInternalServerError, "failed to unresolve comment")diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex eea44cce59..52dbd1f927 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -2346,6 +2346,12 @@ func claimResponseAgentIdentityMatches(resp AgentTaskResponse) bool {func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQueue, runtime db.AgentRuntime, runtimeID, runtimeWorkspaceID string) (resp AgentTaskResponse, deliveredCommentIDs []pgtype.UUID, issueSnapshot []byte, agentSkillCount, builtinSkillCount int, failure *claimBuildFailure) {// Build response with fresh agent data (name + skills + custom_env + custom_args).resp = taskToResponse(*task, runtimeWorkspaceID)+ if err := (&service.IssueWakeupService{Tasks: h.TaskService}).CheckClaim(r.Context(), *task); err != nil {+ if !errors.Is(err, service.ErrWakeupForbidden) {+ return resp, nil, nil, 0, 0, h.rejectClaimSourceLoad(r.Context(), task, err, "wakeup", resp.WakeupID)+ }+ return resp, nil, nil, 0, 0, h.failClaimedTaskBeforeLaunch(r.Context(), task, "Wakeup is disabled or its authorization is no longer available.", taskfailure.ReasonInvalidTaskIdentity, "wakeup_unavailable", http.StatusConflict, "wakeup unavailable")+ }var issueNumber int32// Claim-only capability: this server resolves the squad-leader role on the// wire (is_leader_task / squad_id), so the daemon must not re-derive itdiff --git a/server/internal/handler/file.go b/server/internal/handler/file.goindex 1963ccd24f..7efaf6cefa 100644--- a/server/internal/handler/file.go+++ b/server/internal/handler/file.go@@ -377,6 +377,7 @@ func (h *Handler) groupChatMessageAttachments(ctx context.Context, workspaceID s// ---------------------------------------------------------------------------func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)if h.Storage == nil {writeFeatureDisabled(w, "file_upload_not_configured", "file upload not configured")return@@ -580,7 +581,9 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {return}} else {- att, err = h.Queries.CreateAttachment(r.Context(), params)+ att, err = wakeupWrite(h, r, func(q *db.Queries) (db.CreateAttachmentRow, error) {+ return q.CreateAttachment(r.Context(), params)+ })}if err != nil {slog.Error("failed to create attachment record", "error", err)@@ -1408,6 +1411,7 @@ func isTextPreviewable(contentType, filename string) bool {// ---------------------------------------------------------------------------func (h *Handler) DeleteAttachment(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)attachmentID := chi.URLParam(r, "id")workspaceID := h.resolveWorkspaceID(r)if workspaceID == "" {@@ -1550,7 +1554,7 @@ func (h *Handler) withAttachmentOwnerLock(ctx context.Context, att db.Attachmentvar errAttachmentOwnerChanged = errors.New("attachment owner changed")func (h *Handler) attachmentOwnerLockAttempt(ctx context.Context, att db.Attachment, write func(*db.Queries) error) (db.Attachment, error) {- tx, err := h.TxStarter.Begin(ctx)+ tx, err := h.beginWakeupWrite(ctx)if err != nil {return db.Attachment{}, err}diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 963fda3bbb..5ec82a05dd 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -240,13 +240,14 @@ func assertIssueStatusStillActive(ctx context.Context, qtx *db.Queries, workspac// runWithIssueStatusGuard runs an issue write that lands on a custom status// inside a transaction that re-verifies the status under the shared catalog-// lock (see assertIssueStatusStillActive). A built-in target skips the-// transaction entirely.+// lock (see assertIssueStatusStillActive). Request writes also carry trusted+// wakeup actor identity in transaction-local settings, including built-in targets.func (h *Handler) runWithIssueStatusGuard(ctx context.Context, workspaceID pgtype.UUID, statusKey string, fn func(q *db.Queries) error) error {- if statusKey == "" || issuestatus.IsBuiltIn(statusKey) {+ _, hasActor := ctx.Value(wakeupActorKey{}).(wakeupActor)+ if !hasActor && (statusKey == "" || issuestatus.IsBuiltIn(statusKey)) {return fn(h.Queries)}- tx, err := h.TxStarter.Begin(ctx)+ tx, err := h.beginWakeupWrite(ctx)if err != nil {return err}@@ -2890,6 +2891,7 @@ func duplicateIssueMessage(issue IssueResponse) string {}func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)var req CreateIssueRequestif err := json.NewDecoder(r.Body).Decode(&req); err != nil {writeError(w, http.StatusBadRequest, "invalid request body")@@ -3321,7 +3323,7 @@ func (h *Handler) updateIssueAtomically(ctx context.Context, workspaceID pgtype.if h.TxStarter == nil {return db.Issue{}, db.Issue{}, false, errors.New("atomic issue update requires transaction starter")}- tx, err := h.TxStarter.Begin(ctx)+ tx, err := h.beginWakeupWrite(ctx)if err != nil {return db.Issue{}, db.Issue{}, false, fmt.Errorf("begin atomic issue update: %w", err)}@@ -3423,6 +3425,7 @@ func (h *Handler) updateIssueAtomically(ctx context.Context, workspaceID pgtype.}func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)id := chi.URLParam(r, "id")prevIssue, ok := h.loadIssueForUser(w, r, id)if !ok {@@ -3457,6 +3460,7 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {// Pre-fill nullable fields (bare sqlc.narg) with current valuesparams := db.UpdateIssueParams{+ SourceTaskID: h.wakeupSourceTaskID(r),ID: prevIssue.ID,AssigneeType: prevIssue.AssigneeType,AssigneeID: prevIssue.AssigneeID,@@ -3988,6 +3992,7 @@ func (h *Handler) isAgentAssigneeReady(ctx context.Context, issue db.Issue) bool}func (h *Handler) DeleteIssue(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)id := chi.URLParam(r, "id")issue, ok := h.loadIssueForUser(w, r, id)if !ok {@@ -4035,7 +4040,7 @@ func (h *Handler) deleteIssuesAndCollectAttachmentURLs(ctx context.Context, issusort.Slice(issues, func(i, j int) bool {return uuidToString(issues[i].ID) < uuidToString(issues[j].ID)})- tx, err := h.TxStarter.Begin(ctx)+ tx, err := h.beginWakeupWrite(ctx)if err != nil {return issueDeleteResult{}, fmt.Errorf("begin issue delete: %w", err)}@@ -4126,6 +4131,7 @@ type BatchUpdateIssuesRequest struct {}func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)bodyBytes, err := io.ReadAll(r.Body)if err != nil {writeError(w, http.StatusBadRequest, "failed to read request body")@@ -4253,6 +4259,7 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {}params := db.UpdateIssueParams{+ SourceTaskID: h.wakeupSourceTaskID(r),ID: prevIssue.ID,AssigneeType: prevIssue.AssigneeType,AssigneeID: prevIssue.AssigneeID,diff --git a/server/internal/handler/issue_metadata.go b/server/internal/handler/issue_metadata.goindex 157ab871de..799b63feba 100644--- a/server/internal/handler/issue_metadata.go+++ b/server/internal/handler/issue_metadata.go@@ -155,6 +155,7 @@ func (h *Handler) ListIssueMetadata(w http.ResponseWriter, r *http.Request) {}func (h *Handler) SetIssueMetadataKey(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)issueID := chi.URLParam(r, "id")key := chi.URLParam(r, "key")if err := validateIssueMetadataKey(key); err != nil {@@ -191,11 +192,13 @@ func (h *Handler) SetIssueMetadataKey(w http.ResponseWriter, r *http.Request) {}queryStarted := time.Now()- updated, err := h.Queries.SetIssueMetadataKey(r.Context(), db.SetIssueMetadataKeyParams{- ID: issue.ID,- WorkspaceID: issue.WorkspaceID,- Key: key,- Value: []byte(req.Value),+ updated, err := wakeupWrite(h, r, func(q *db.Queries) (db.SetIssueMetadataKeyRow, error) {+ return q.SetIssueMetadataKey(r.Context(), db.SetIssueMetadataKeyParams{+ ID: issue.ID,+ WorkspaceID: issue.WorkspaceID,+ Key: key,+ Value: []byte(req.Value),+ })})queryDuration := time.Since(queryStarted)if err != nil {@@ -247,6 +250,7 @@ func (h *Handler) SetIssueMetadataKey(w http.ResponseWriter, r *http.Request) {}func (h *Handler) DeleteIssueMetadataKey(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)issueID := chi.URLParam(r, "id")key := chi.URLParam(r, "key")if err := validateIssueMetadataKey(key); err != nil {@@ -264,10 +268,12 @@ func (h *Handler) DeleteIssueMetadataKey(w http.ResponseWriter, r *http.Request)}queryStarted := time.Now()- updated, err := h.Queries.DeleteIssueMetadataKey(r.Context(), db.DeleteIssueMetadataKeyParams{- ID: issue.ID,- WorkspaceID: issue.WorkspaceID,- Key: key,+ updated, err := wakeupWrite(h, r, func(q *db.Queries) (db.DeleteIssueMetadataKeyRow, error) {+ return q.DeleteIssueMetadataKey(r.Context(), db.DeleteIssueMetadataKeyParams{+ ID: issue.ID,+ WorkspaceID: issue.WorkspaceID,+ Key: key,+ })})queryDuration := time.Since(queryStarted)if err != nil {diff --git a/server/internal/handler/issue_reaction.go b/server/internal/handler/issue_reaction.goindex 96339b379b..cc5c115cea 100644--- a/server/internal/handler/issue_reaction.go+++ b/server/internal/handler/issue_reaction.go@@ -48,6 +48,7 @@ func addedIssueReactionToResponse(r db.AddIssueReactionRow) IssueReactionRespons}func (h *Handler) AddIssueReaction(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)issueID := chi.URLParam(r, "id")issue, ok := h.loadIssueForUser(w, r, issueID)if !ok {@@ -74,12 +75,14 @@ func (h *Handler) AddIssueReaction(w http.ResponseWriter, r *http.Request) {workspaceID := uuidToString(issue.WorkspaceID)actorType, actorID := h.resolveActor(r, userID, workspaceID)- reaction, err := h.Queries.AddIssueReaction(r.Context(), db.AddIssueReactionParams{- IssueID: issue.ID,- WorkspaceID: issue.WorkspaceID,- ActorType: actorType,- ActorID: parseUUID(actorID),- Emoji: req.Emoji,+ reaction, err := wakeupWrite(h, r, func(q *db.Queries) (db.AddIssueReactionRow, error) {+ return q.AddIssueReaction(r.Context(), db.AddIssueReactionParams{+ IssueID: issue.ID,+ WorkspaceID: issue.WorkspaceID,+ ActorType: actorType,+ ActorID: parseUUID(actorID),+ Emoji: req.Emoji,+ })})if err != nil {slog.Warn("add issue reaction failed", append(logger.RequestAttrs(r), "error", err, "issue_id", issueID)...)@@ -103,6 +106,7 @@ func (h *Handler) AddIssueReaction(w http.ResponseWriter, r *http.Request) {}func (h *Handler) RemoveIssueReaction(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)issueID := chi.URLParam(r, "id")issue, ok := h.loadIssueForUser(w, r, issueID)if !ok {@@ -129,11 +133,13 @@ func (h *Handler) RemoveIssueReaction(w http.ResponseWriter, r *http.Request) {workspaceID := uuidToString(issue.WorkspaceID)actorType, actorID := h.resolveActor(r, userID, workspaceID)- removed, err := h.Queries.RemoveIssueReaction(r.Context(), db.RemoveIssueReactionParams{- IssueID: issue.ID,- ActorType: actorType,- ActorID: parseUUID(actorID),- Emoji: req.Emoji,+ removed, err := wakeupWrite(h, r, func(q *db.Queries) (db.RemoveIssueReactionRow, error) {+ return q.RemoveIssueReaction(r.Context(), db.RemoveIssueReactionParams{+ IssueID: issue.ID,+ ActorType: actorType,+ ActorID: parseUUID(actorID),+ Emoji: req.Emoji,+ })})if err != nil {slog.Warn("remove issue reaction failed", append(logger.RequestAttrs(r), "error", err, "issue_id", issueID)...)diff --git a/server/internal/handler/issue_wakeup.go b/server/internal/handler/issue_wakeup.gonew file mode 100644index 0000000000..c21505f41f--- /dev/null+++ b/server/internal/handler/issue_wakeup.go@@ -0,0 +1,320 @@+package handler++import (+ "encoding/json"+ "errors"+ "net/http"+ "strconv"+ "strings"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/service"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func (h *Handler) ListWorkspaceWakeups(w http.ResponseWriter, r *http.Request) {+ workspaceID := h.resolveWorkspaceID(r)+ member, ok := h.workspaceMember(w, r, workspaceID)+ if !ok {+ return+ }+ params := r.URL.Query()+ scope, kind := params.Get("scope"), params.Get("kind")+ if scope == "" {+ scope = "active"+ }+ if kind == "" {+ kind = "all"+ }+ if scope != "active" && scope != "all" && scope != "disabled" && scope != "ended" {+ writeError(w, 400, "invalid wakeup scope")+ return+ }+ if kind != "all" && kind != "event" && kind != "at" && kind != "recurring" {+ writeError(w, 400, "invalid wakeup kind")+ return+ }+ page, limit := 0, 50+ for key, dst := range map[string]*int{"offset": &page, "limit": &limit} {+ if raw := params.Get(key); raw != "" {+ v, err := strconv.Atoi(raw)+ if err != nil || v < 0 || (key == "limit" && (v < 1 || v > 100)) || (key == "offset" && v > 1000000) {+ writeError(w, 400, "invalid pagination")+ return+ }+ *dst = v+ }+ }+ search := strings.TrimSpace(params.Get("search"))+ if len(search) > 256 {+ writeError(w, 400, "search too long")+ return+ }+ agentID := params.Get("agent_id")+ if agentID != "" {+ id, valid := parseUUIDOrBadRequest(w, agentID, "agent id")+ if !valid {+ return+ }+ agentID = uuidToString(id)+ }+ actorType, actorID := h.resolveActor(r, requestUserID(r), workspaceID)+ allowed, ok := h.accessibleAgentIDs(r.Context(), workspaceID, actorType, actorID, member.Role)+ if !ok {+ writeError(w, 500, "failed to resolve agent access")+ return+ }+ ids := make([]pgtype.UUID, 0, len(allowed))+ for id := range allowed {+ ids = append(ids, parseUUID(id))+ }+ // Management flags use the same initiating human as the mutation endpoints.+ originator := h.invokeOriginatorFromRequest(r, actorType, actorID)+ managerID, isAdmin := pgtype.UUID{}, false+ if originator != "" {+ manager, err := h.getWorkspaceMember(r.Context(), originator, workspaceID)+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {+ writeError(w, 500, "failed to resolve management access")+ return+ }+ if err == nil {+ managerID = manager.UserID+ isAdmin = roleAllowed(manager.Role, "owner", "admin")+ }+ }+ result, err := h.Queries.ListWorkspaceWakeups(r.Context(), db.ListWorkspaceWakeupsParams{+ WorkspaceID: parseUUID(workspaceID), AgentIds: ids, MemberID: managerID, IsAdmin: isAdmin,+ Scope: scope, Kind: kind, AgentID: agentID, Search: search, PageLimit: int32(limit), PageOffset: int32(page),+ })+ if err != nil {+ wakeupError(w, err)+ return+ }+ writeJSON(w, 200, json.RawMessage(result))+}++func wakeupError(w http.ResponseWriter, err error) {+ var pgErr *pgconn.PgError+ if errors.As(err, &pgErr) && pgErr.ConstraintName == "issue_wakeup_active_limit" {+ writeErrorCode(w, 400, "wakeup_capacity_exceeded", pgErr.Message)+ return+ }+ if errors.As(err, &pgErr) && pgErr.Code == "55P03" {+ writeErrorCode(w, 409, "wakeup_source_busy", "source run is changing; retry registration")+ return+ }+ switch {+ case errors.Is(err, service.ErrWakeupConflict):+ writeError(w, 409, err.Error())+ case errors.Is(err, service.ErrWakeupInput):+ writeError(w, 400, err.Error())+ case errors.Is(err, service.ErrWakeupForbidden):+ writeError(w, 403, "wakeup permission denied")+ case errors.Is(err, pgx.ErrNoRows):+ writeError(w, 404, "wakeup not found")+ default:+ writeError(w, 500, "could not save wakeup")+ }+}++func (h *Handler) ListIssueWakeups(w http.ResponseWriter, r *http.Request) {+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ workspaceID := uuidToString(issue.WorkspaceID)+ member, ok := h.workspaceMember(w, r, workspaceID)+ if !ok {+ return+ }+ actorType, actorID := h.resolveActor(r, requestUserID(r), workspaceID)+ allowed, ok := h.accessibleAgentIDs(r.Context(), workspaceID, actorType, actorID, member.Role)+ if !ok {+ writeError(w, 500, "failed to resolve agent access")+ return+ }+ ids := make([]pgtype.UUID, 0, len(allowed))+ for id := range allowed {+ ids = append(ids, parseUUID(id))+ }+ rows, err := h.Queries.ListIssueWakeups(r.Context(), db.ListIssueWakeupsParams{IssueID: issue.ID, WorkspaceID: issue.WorkspaceID, AgentIds: ids})+ if err != nil {+ wakeupError(w, err)+ return+ }+ if rows == nil {+ rows = []db.ListIssueWakeupsRow{}+ }+ writeJSON(w, 200, rows)+}++func (h *Handler) ListWorkspaceWakeupSummaries(w http.ResponseWriter, r *http.Request) {+ workspaceID := h.resolveWorkspaceID(r)+ member, ok := h.workspaceMember(w, r, workspaceID)+ if !ok {+ return+ }+ actorType, actorID := h.resolveActor(r, requestUserID(r), workspaceID)+ allowed, ok := h.accessibleAgentIDs(r.Context(), workspaceID, actorType, actorID, member.Role)+ if !ok {+ writeError(w, 500, "failed to resolve agent access")+ return+ }+ ids := make([]pgtype.UUID, 0, len(allowed))+ for id := range allowed {+ ids = append(ids, parseUUID(id))+ }+ rows, err := h.Queries.ListWorkspaceWakeupSummaryRows(r.Context(), db.ListWorkspaceWakeupSummaryRowsParams{WorkspaceID: parseUUID(workspaceID), AgentIds: ids})+ if err != nil {+ wakeupError(w, err)+ return+ }+ if rows == nil {+ rows = []db.ListWorkspaceWakeupSummaryRowsRow{}+ }+ writeJSON(w, 200, rows)+}++func (h *Handler) CreateIssueWakeup(w http.ResponseWriter, r *http.Request) {+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ var in service.WakeupInput+ dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 32768))+ dec.DisallowUnknownFields()+ if err := dec.Decode(&in); err != nil {+ writeError(w, 400, "invalid wakeup body")+ return+ }+ actorType, actorID := h.resolveActor(r, requestUserID(r), uuidToString(issue.WorkspaceID))+ if in.AgentID == "" && actorType == "agent" {+ in.AgentID = actorID+ }+ originator := h.invokeOriginatorFromRequest(r, actorType, actorID)+ if originator == "" {+ writeError(w, 403, "a human originator is required")+ return+ }+ member := parseUUID(originator)+ svc := service.IssueWakeupService{Tasks: h.TaskService}+ existingID := pgtype.UUID{}+ if rawID := chi.URLParam(r, "wakeupID"); rawID != "" {+ var valid bool+ existingID, valid = parseUUIDOrBadRequest(w, rawID, "wakeup id")+ if !valid {+ return+ }+ }+ if r.Method == http.MethodPut && !existingID.Valid {+ writeError(w, 400, "invalid wakeup id")+ return+ }+ result, err := svc.Save(r.Context(), issue.ID, member, h.wakeupSourceTaskID(r), existingID, in)+ if err != nil {+ wakeupError(w, err)+ return+ }+ status := http.StatusCreated+ if existingID.Valid {+ status = http.StatusOK+ }+ writeJSON(w, status, result)+}++func (h *Handler) DisableIssueWakeup(w http.ResponseWriter, r *http.Request) {+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ id, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "wakeupID"), "wakeup id")+ if !ok {+ return+ }+ actorType, actorID := h.resolveActor(r, requestUserID(r), uuidToString(issue.WorkspaceID))+ originator := h.invokeOriginatorFromRequest(r, actorType, actorID)+ if originator == "" {+ writeError(w, 403, "a human originator is required")+ return+ }+ member := parseUUID(originator)+ svc := service.IssueWakeupService{Tasks: h.TaskService}+ result, err := svc.Disable(r.Context(), issue.ID, id, member)+ if err != nil {+ wakeupError(w, err)+ return+ }+ writeJSON(w, 200, result)+}++func (h *Handler) wakeupSourceTaskID(r *http.Request) pgtype.UUID {+ actorType, _ := h.resolveActor(r, requestUserID(r), h.resolveWorkspaceID(r))+ if actorType != "agent" {+ return pgtype.UUID{}+ }+ return h.commentSourceTaskID(r)+}++func (h *Handler) EnableIssueWakeup(w http.ResponseWriter, r *http.Request) {+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ id, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "wakeupID"), "wakeup id")+ if !ok {+ return+ }+ var in service.WakeupEnableInput+ dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1024))+ dec.DisallowUnknownFields()+ if err := dec.Decode(&in); err != nil {+ writeError(w, 400, "invalid enable body")+ return+ }+ actorType, actorID := h.resolveActor(r, requestUserID(r), uuidToString(issue.WorkspaceID))+ originator := h.invokeOriginatorFromRequest(r, actorType, actorID)+ if originator == "" {+ writeError(w, 403, "a human originator is required")+ return+ }+ svc := service.IssueWakeupService{Tasks: h.TaskService}+ result, err := svc.Enable(r.Context(), issue.ID, parseUUID(originator), h.wakeupSourceTaskID(r), id, in)+ if err != nil {+ wakeupError(w, err)+ return+ }+ writeJSON(w, 200, result)+}++func (h *Handler) EditIssueWakeupInstruction(w http.ResponseWriter, r *http.Request) {+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ id, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "wakeupID"), "wakeup id")+ if !ok {+ return+ }+ var in service.WakeupInstructionInput+ dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 160000))+ dec.DisallowUnknownFields()+ if err := dec.Decode(&in); err != nil {+ writeError(w, 400, "invalid instruction body")+ return+ }+ actorType, actorID := h.resolveActor(r, requestUserID(r), uuidToString(issue.WorkspaceID))+ originator := h.invokeOriginatorFromRequest(r, actorType, actorID)+ if originator == "" {+ writeError(w, 403, "a human originator is required")+ return+ }+ svc := service.IssueWakeupService{Tasks: h.TaskService}+ if err := svc.EditInstruction(r.Context(), issue.ID, id, parseUUID(originator), in); err != nil {+ wakeupError(w, err)+ return+ }+ w.WriteHeader(http.StatusNoContent)+}diff --git a/server/internal/handler/issue_wakeup_test.go b/server/internal/handler/issue_wakeup_test.gonew file mode 100644index 0000000000..429779d39f--- /dev/null+++ b/server/internal/handler/issue_wakeup_test.go@@ -0,0 +1,366 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestIssueWakeupAPIAndTrustedOrigin(t *testing.T) {+ issue := dbfx.Issue(t, "wake api")+ agent := dbfx.Agent(t, "wake api", testRuntimeID)+ dbfx.Cleanup(t, "DELETE FROM issue_wakeup WHERE issue_id=$1", issue)+ dbfx.Cleanup(t, "DELETE FROM issue_wakeup_receipt WHERE wakeup_id IN(SELECT id FROM issue_wakeup WHERE issue_id=$1)", issue)+ body := map[string]any{"agent_id": agent, "kind": "at", "after_seconds": 600, "instruction": "check deployment"}+ req := withURLParam(newRequest("POST", "/api/issues/"+issue+"/wakeups", body), "id", issue)+ // An untrusted task header must not get stamped as delegation provenance.+ forged := dbfx.Task(t, agent, testutil.Cols{"runtime_id": testRuntimeID, "issue_id": issue})+ req.Header.Set("X-Task-ID", forged)+ rec := httptest.NewRecorder()+ testHandler.CreateIssueWakeup(rec, req)+ if rec.Code != 201 {+ t.Fatalf("create %d: %s", rec.Code, rec.Body.String())+ }+ var result db.IssueWakeup+ if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {+ t.Fatal(err)+ }+ if result.SourceTaskID.Valid || uuidToString(result.CreatedBy) != testUserID {+ t.Fatal("untrusted source identity")+ }+ update := withURLParams(newRequest("PUT", "/", body), "id", issue, "wakeupID", uuidToString(result.ID))+ updated := httptest.NewRecorder()+ testHandler.CreateIssueWakeup(updated, update)+ if updated.Code != http.StatusOK {+ t.Fatalf("update %d: %s", updated.Code, updated.Body.String())+ }+ if err := json.Unmarshal(updated.Body.Bytes(), &result); err != nil {+ t.Fatal(err)+ }+ req = withURLParam(newRequest("GET", "/", nil), "id", issue)+ rec = httptest.NewRecorder()+ testHandler.ListIssueWakeups(rec, req)+ if rec.Code != 200 {+ t.Fatal(rec.Body.String())+ }+ outsider := dbfx.User(t, "wake outsider", "[email protected]")+ dbfx.Member(t, testWorkspaceID, outsider, "member")+ // A task-scoped caller must use the initiating human's rights, never the+ // runtime owner's rights, even when registering a wakeup for itself.+ dbfx.Exec(t, "UPDATE agent_task_queue SET originator_user_id=$2,accountable_user_id=$2,status='running',started_at=now() WHERE id=$1", forged, outsider)+ req = withURLParam(newRequest("POST", "/", map[string]any{"kind": "at", "after_seconds": 600, "instruction": "check"}), "id", issue)+ req.Header.Set("X-Agent-ID", agent)+ req.Header.Set("X-Task-ID", forged)+ req.Header.Set("X-Actor-Source", "task_token")+ rec = httptest.NewRecorder()+ testHandler.CreateIssueWakeup(rec, req)+ if rec.Code != 403 {+ t.Fatalf("borrowed runtime owner permission: %d %s", rec.Code, rec.Body.String())+ }+ svc := service.IssueWakeupService{Tasks: testHandler.TaskService}+ if _, err := svc.Disable(context.Background(), parseUUID(issue), result.ID, parseUUID(outsider)); err != service.ErrWakeupForbidden {+ t.Fatalf("other member disabled: %v", err)+ }+ if _, err := svc.Disable(context.Background(), parseUUID(issue), result.ID, parseUUID(testUserID)); err != nil {+ t.Fatal(err)+ }+ for _, tc := range []struct {+ trusted bool+ revision int64+ want int+ }{+ {false, 0, 400}, {true, result.Revision, 403}, {false, result.Revision, 200}, {false, result.Revision, 409},+ } {+ req := withURLParams(newRequest("POST", "/", map[string]any{"revision": tc.revision}), "id", issue, "wakeupID", uuidToString(result.ID))+ req.Header.Set("X-Task-ID", forged)+ if tc.trusted {+ req.Header.Set("X-Agent-ID", agent)+ req.Header.Set("X-Actor-Source", "task_token")+ }+ rec := httptest.NewRecorder()+ testHandler.EnableIssueWakeup(rec, req)+ if rec.Code != tc.want {+ t.Fatalf("enable %d: %s", rec.Code, rec.Body.String())+ }+ if tc.want == 200 {+ var enabled db.IssueWakeup+ if err := json.Unmarshal(rec.Body.Bytes(), &enabled); err != nil {+ t.Fatal(err)+ }+ if !enabled.Enabled || enabled.SourceTaskID.Valid {+ t.Fatal("enable trusted a forged source")+ }+ }+ }+}++func TestWorkspaceWakeupSummariesScopeAndBounds(t *testing.T) {+ issue := dbfx.Issue(t, "wakeup summary")+ agent := dbfx.Agent(t, "summary target", testRuntimeID)+ svc := service.IssueWakeupService{Tasks: testHandler.TaskService}+ dbfx.Cleanup(t, "DELETE FROM issue_wakeup WHERE issue_id=$1", issue)+ dbfx.Cleanup(t, "DELETE FROM issue_wakeup_receipt WHERE wakeup_id IN(SELECT id FROM issue_wakeup WHERE issue_id=$1)", issue)+ var first db.IssueWakeup+ for i := 0; i < 5; i++ {+ in := service.WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"comment.created"}, Instruction: "PRIVATE PROMPT"}+ if i == 0 {+ in.Kind = "at"+ in.EventTypes = nil+ in.AfterSeconds = 3600+ }+ w, err := svc.Create(context.Background(), parseUUID(issue), parseUUID(testUserID), pgtype.UUID{}, in)+ if err != nil {+ t.Fatal(err)+ }+ if i == 0 {+ first = w+ }+ }+ read := func(req *http.Request, want int) []db.ListWorkspaceWakeupSummaryRowsRow {+ t.Helper()+ rec := httptest.NewRecorder()+ testHandler.ListWorkspaceWakeupSummaries(rec, req)+ if rec.Code != want {+ t.Fatalf("summary %d: %s", rec.Code, rec.Body.String())+ }+ if want != 200 {+ return nil+ }+ if strings.Contains(rec.Body.String(), "PRIVATE PROMPT") || strings.Contains(rec.Body.String(), "instruction") {+ t.Fatal("prompt leaked to summary")+ }+ var rows []db.ListWorkspaceWakeupSummaryRowsRow+ if err := json.Unmarshal(rec.Body.Bytes(), &rows); err != nil {+ t.Fatal(err)+ }+ return rows+ }+ rows := read(newRequest("GET", "/api/issue-wakeup-summaries", nil), 200)+ if len(rows) != 3 || rows[0].ID != first.ID || rows[0].ActiveCount != 5 || rows[0].EventCount != 4 {+ t.Fatalf("wrong bounded summary: %+v", rows)+ }+ outsider := dbfx.User(t, "summary outsider", "[email protected]")+ req := newRequest("GET", "/", nil)+ req.Header.Set("X-User-ID", outsider)+ read(req, 404)+ dbfx.Member(t, testWorkspaceID, outsider, "member")+ if got := read(req, 200); len(got) != 3 || got[0].ActiveCount != 5 {+ t.Fatal("shared issue rules disappeared from summary")+ }+ // Rule visibility follows the shared issue; all read surfaces consistently+ // redact private source-agent and source-run references.+ sourceRun := dbfx.Task(t, agent, testutil.Cols{"issue_id": issue, "runtime_id": testRuntimeID, "status": "completed"})+ dbfx.Exec(t, "UPDATE issue_wakeup SET filter_agent_id=$2,filter_task_id=$3 WHERE id=$1", first.ID, agent, sourceRun)+ for _, row := range read(req, 200) {+ if row.FilterAgentName.Valid || row.FilterTaskID.Valid {+ t.Fatal("private source exposed in summary")+ }+ }+ detail := httptest.NewRecorder()+ testHandler.ListIssueWakeups(detail, withURLParam(req, "id", issue))+ var details []db.ListIssueWakeupsRow+ if detail.Code != 200 || json.Unmarshal(detail.Body.Bytes(), &details) != nil || len(details) != 5 {+ t.Fatalf("detail response: %d %s", detail.Code, detail.Body.String())+ }+ for _, row := range details {+ if row.FilterAgentName.Valid || row.FilterAgentID.Valid || row.FilterTaskID.Valid {+ t.Fatal("private source exposed in detail")+ }+ if row.Instruction != "PRIVATE PROMPT" {+ t.Fatal("shared issue instruction missing")+ }+ }+ other := dbfx.Workspace(t, "other summary", "other-summary")+ dbfx.Member(t, other, testUserID, "owner")+ req = newRequest("GET", "/", nil)+ req.Header.Set("X-Workspace-ID", other)+ if got := read(req, 200); len(got) != 0 {+ t.Fatal("cross-workspace summary exposed")+ }+ if _, err := svc.Disable(context.Background(), parseUUID(issue), first.ID, parseUUID(testUserID)); err != nil {+ t.Fatal(err)+ }+ rows = read(newRequest("GET", "/", nil), 200)+ if len(rows) != 3 || rows[0].ActiveCount != 4 || rows[0].EventCount != 4 {+ t.Fatalf("disabled entry retained: %+v", rows)+ }+ dbfx.Exec(t, "UPDATE issue SET status='done' WHERE id=$1", issue)+ if got := read(newRequest("GET", "/", nil), 200); len(got) != 0 {+ t.Fatal("closed issue summary retained")+ }+}++func TestWakeupDeferredRunSnapshotPreservesOrigin(t *testing.T) {+ issue := dbfx.Issue(t, "deferred wakeup snapshot")+ agent := dbfx.Agent(t, "deferred wakeup", testRuntimeID)+ for _, contextJSON := range []string{`{}`, `{"wakeup_id":"01900000-0000-7000-8000-000000000001"}`} {+ dbfx.Task(t, agent, testutil.Cols{"issue_id": issue, "status": "deferred", "runtime_id": testRuntimeID, "context": contextJSON})+ }+ rec := httptest.NewRecorder()+ testHandler.ListWorkspaceAgentTaskSnapshot(rec, newRequest("GET", "/", nil))+ if rec.Code != 200 {+ t.Fatal(rec.Body.String())+ }+ var tasks []AgentTaskResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &tasks); err != nil {+ t.Fatal(err)+ }+ var found int+ for _, task := range tasks {+ if task.IssueID == issue {+ found+++ if task.WakeupID != "01900000-0000-7000-8000-000000000001" || task.Status != "deferred" {+ t.Fatalf("bad wakeup origin: %+v", task)+ }+ }+ }+ if found != 1 {+ t.Fatalf("wrong deferred snapshot count: %d", found)+ }+}++func TestIssueWakeupMutationTrustedActor(t *testing.T) {+ issue := dbfx.Issue(t, "wake mutation actor")+ agent := dbfx.Agent(t, "wake mutation actor", testRuntimeID)+ dbfx.Cleanup(t, "DELETE FROM issue_wakeup WHERE issue_id=$1", issue)+ dbfx.Cleanup(t, "DELETE FROM issue_wakeup_receipt WHERE wakeup_id IN(SELECT id FROM issue_wakeup WHERE issue_id=$1)", issue)+ comment := dbfx.Comment(t, issue, "agent original", testutil.Cols{"author_type": "agent", "author_id": agent})+ svc := service.IssueWakeupService{Tasks: testHandler.TaskService}+ w, err := svc.Create(context.Background(), parseUUID(issue), parseUUID(testUserID), pgtype.UUID{}, service.WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.updated", "issue.metadata_changed", "reaction.added", "reaction.removed"}, Instruction: "inspect"})+ if err != nil {+ t.Fatal(err)+ }+ run := dbfx.Task(t, agent, testutil.Cols{"runtime_id": testRuntimeID, "issue_id": issue, "status": "running", "started_at": testutil.Raw("now()"), "originator_user_id": testUserID, "accountable_user_id": testUserID})+ call := func(handler http.HandlerFunc, req *http.Request, trusted bool) {+ t.Helper()+ req.Header.Set("X-Task-ID", run)+ if trusted {+ req.Header.Set("X-Agent-ID", agent)+ req.Header.Set("X-Actor-Source", "task_token")+ }+ rec := httptest.NewRecorder()+ handler(rec, req)+ if rec.Code < 200 || rec.Code >= 300 {+ t.Fatalf("mutation %d: %s", rec.Code, rec.Body.String())+ }+ }+ // Admin editing another agent's comment: author stays agent; actor is member,+ // and a forged task header cannot suppress the event as the wakeup's own run.+ dbfx.Exec(t, "UPDATE agent_task_queue SET context=jsonb_build_object('wakeup_id',$2::text) WHERE id=$1", run, uuidToString(w.ID))+ call(testHandler.UpdateComment, withURLParam(newRequest("PATCH", "/", map[string]any{"content": "admin edit"}), "commentId", comment), false)+ var actorType, actorID string+ var source *string+ dbfx.QueryRow(t, "SELECT payload->>'actor_type',payload->>'actor_id',payload->>'source_task_id' FROM issue_wakeup_receipt WHERE wakeup_id=$1", w.ID).Scan(&actorType, &actorID, &source)+ if actorType != "member" || actorID != testUserID || source != nil {+ t.Fatalf("wrong editor identity %s %s %v", actorType, actorID, source)+ }+ count := func() int { return dbfx.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1", w.ID) }+ call(testHandler.UpdateComment, withURLParam(newRequest("PATCH", "/", map[string]any{"content": "own wakeup edit"}), "commentId", comment), true)+ req := withURLParams(newRequest("PUT", "/", map[string]any{"value": "secret"}), "id", issue, "key", "test")+ call(testHandler.SetIssueMetadataKey, req, true)+ call(testHandler.AddIssueReaction, withURLParam(newRequest("POST", "/", map[string]any{"emoji": "👍"}), "id", issue), true)+ call(testHandler.RemoveIssueReaction, withURLParam(newRequest("DELETE", "/", map[string]any{"emoji": "👍"}), "id", issue), true)+ if count() != 1 {+ t.Fatalf("own run caused wakeup: %d", count())+ }+ dbfx.Exec(t, "UPDATE agent_task_queue SET context='{}' WHERE id=$1", run)+ req = withURLParams(newRequest("PUT", "/", map[string]any{"value": "changed"}), "id", issue, "key", "test")+ call(testHandler.SetIssueMetadataKey, req, true)+ if count() != 2 {+ t.Fatalf("external run not captured: %d", count())+ }+ dbfx.QueryRow(t, "SELECT payload->>'actor_type',payload->>'actor_id',payload->>'source_task_id' FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND event_type='issue.metadata_changed'", w.ID).Scan(&actorType, &actorID, &source)+ if actorType != "agent" || actorID != agent || source == nil || *source != run {+ t.Fatalf("wrong source identity %s %s %v", actorType, actorID, source)+ }+}++func TestIssueWakeupCapacityReturnsActionableError(t *testing.T) {+ issue := dbfx.Issue(t, "wakeup capacity response")+ agent := dbfx.Agent(t, "wakeup capacity target", testRuntimeID)+ dbfx.Cleanup(t, "DELETE FROM issue_wakeup WHERE issue_id=$1", issue)+ dbfx.Exec(t, `INSERT INTO issue_wakeup(id,workspace_id,issue_id,agent_id,created_by,instruction,kind,mode,event_types)+ SELECT gen_random_uuid(),$1,$2,$3,$4,'check','event','continuous',ARRAY['comment.created'] FROM generate_series(1,32)`, testWorkspaceID, issue, agent, testUserID)+ req := withURLParam(newRequest("POST", "/", map[string]any{"agent_id": agent, "kind": "at", "after_seconds": 600, "instruction": "check"}), "id", issue)+ rec := httptest.NewRecorder()+ testHandler.CreateIssueWakeup(rec, req)+ if rec.Code != 400 || !strings.Contains(rec.Body.String(), "wakeup_capacity_exceeded") || !strings.Contains(rec.Body.String(), "32") {+ t.Fatalf("capacity error %d: %s", rec.Code, rec.Body.String())+ }+}++func TestIssueWakeupActorFilterAPIAndProjection(t *testing.T) {+ issue := dbfx.Issue(t, "actor filter API")+ target := dbfx.Agent(t, "actor filter target", testRuntimeID)+ source := dbfx.Agent(t, "hidden actor name", testRuntimeID)+ person := dbfx.User(t, "Monitored Person", "[email protected]")+ dbfx.Member(t, testWorkspaceID, person, "member")+ reader := dbfx.User(t, "actor reader", "[email protected]")+ dbfx.Member(t, testWorkspaceID, reader, "member")+ dbfx.Cleanup(t, "DELETE FROM issue_wakeup WHERE issue_id=$1", issue)+ dbfx.Cleanup(t, "DELETE FROM issue_wakeup_receipt WHERE wakeup_id IN(SELECT id FROM issue_wakeup WHERE issue_id=$1)", issue)+ for _, actor := range []struct{ kind, id string }{{"member", person}, {"agent", source}} {+ req := withURLParam(newRequest("POST", "/", map[string]any{"agent_id": target, "kind": "event", "event_types": []string{"comment.created"}, "filter_actor_type": actor.kind, "filter_actor_id": actor.id, "instruction": "wait for this actor"}), "id", issue)+ rec := httptest.NewRecorder()+ testHandler.CreateIssueWakeup(rec, req)+ if rec.Code != 201 {+ t.Fatalf("actor create %d: %s", rec.Code, rec.Body.String())+ }+ var rule db.IssueWakeup+ if err := json.Unmarshal(rec.Body.Bytes(), &rule); err != nil {+ t.Fatal(err)+ }+ if rule.FilterActorType.String != actor.kind || uuidToString(rule.FilterActorID) != actor.id {+ t.Fatal("actor filter not persisted")+ }+ }+ for _, endpoint := range []func(http.ResponseWriter, *http.Request){testHandler.ListIssueWakeups, testHandler.ListWorkspaceWakeupSummaries, testHandler.ListWorkspaceWakeups} {+ req := withURLParam(newRequest("GET", "/?scope=all", nil), "id", issue)+ req.Header.Set("X-User-ID", reader)+ rec := httptest.NewRecorder()+ endpoint(rec, req)+ if rec.Code != 200 {+ t.Fatal(rec.Body.String())+ }+ body := rec.Body.String()+ if !strings.Contains(body, "Monitored Person") || !strings.Contains(body, person) || !strings.Contains(body, `"filter_actor_type":"agent"`) {+ t.Fatalf("missing actor projection: %s", body)+ }+ if strings.Contains(body, "hidden actor name") || strings.Contains(body, source) {+ t.Fatalf("private actor exposed: %s", body)+ }+ }+}++func TestIssueWakeupInstructionAPI(t *testing.T) {+ issue := dbfx.Issue(t, "edit prompt api")+ agent := dbfx.Agent(t, "edit prompt", testRuntimeID)+ svc := service.IssueWakeupService{Tasks: testHandler.TaskService}+ dbfx.Cleanup(t, "DELETE FROM issue_wakeup WHERE issue_id=$1", issue)+ rule, err := svc.Create(context.Background(), parseUUID(issue), parseUUID(testUserID), pgtype.UUID{}, service.WakeupInput{AgentID: agent, Kind: "at", AfterSeconds: 600, Instruction: "old"})+ if err != nil {+ t.Fatal(err)+ }+ for _, tc := range []struct {+ id string+ body map[string]any+ want int+ }{+ {uuidToString(rule.ID), map[string]any{"instruction": "new", "expected_instruction": "old", "revision": rule.Revision}, 204},+ {uuidToString(rule.ID), map[string]any{"instruction": "overwritten", "expected_instruction": "old", "revision": rule.Revision}, 409},+ {uuidToString(rule.ID), map[string]any{"instruction": " ", "expected_instruction": "new", "revision": rule.Revision}, 400},+ {uuidToString(rule.ID), map[string]any{"instruction": "new", "expected_instruction": "new", "revision": rule.Revision, "enabled": true}, 400},+ {"not-a-uuid", map[string]any{"instruction": "new", "expected_instruction": "new", "revision": rule.Revision}, 400},+ } {+ req := withURLParams(newRequest("PATCH", "/", tc.body), "id", issue, "wakeupID", tc.id)+ testutil.Call(t, testHandler.EditIssueWakeupInstruction, req).Want(tc.want)+ }+}diff --git a/server/internal/handler/label.go b/server/internal/handler/label.goindex 324254579e..73c6dc1b8c 100644--- a/server/internal/handler/label.go+++ b/server/internal/handler/label.go@@ -307,6 +307,7 @@ func (h *Handler) UpdateLabel(w http.ResponseWriter, r *http.Request) {}func (h *Handler) DeleteLabel(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)id := chi.URLParam(r, "id")workspaceID := h.resolveWorkspaceID(r)userID, ok := requireUserID(w, r)@@ -321,7 +322,7 @@ func (h *Handler) DeleteLabel(w http.ResponseWriter, r *http.Request) {if !ok {return}- tx, err := h.TxStarter.Begin(r.Context())+ tx, err := h.beginWakeupWrite(r.Context())if err != nil {writeError(w, http.StatusInternalServerError, "failed to start transaction")return@@ -416,6 +417,7 @@ func (h *Handler) ListLabelsForIssue(w http.ResponseWriter, r *http.Request) {// AttachLabel attaches a label to an issue.func (h *Handler) AttachLabel(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)issueID := chi.URLParam(r, "id")userID, ok := requireUserID(w, r)if !ok {@@ -458,10 +460,12 @@ func (h *Handler) AttachLabel(w http.ResponseWriter, r *http.Request) {return}- attached, err := h.Queries.AttachLabelToIssue(r.Context(), db.AttachLabelToIssueParams{- IssueID: issue.ID,- LabelID: labelID,- WorkspaceID: issue.WorkspaceID,+ attached, err := wakeupWrite(h, r, func(q *db.Queries) (db.AttachLabelToIssueRow, error) {+ return q.AttachLabelToIssue(r.Context(), db.AttachLabelToIssueParams{+ IssueID: issue.ID,+ LabelID: labelID,+ WorkspaceID: issue.WorkspaceID,+ })})if err != nil {slog.Warn("AttachLabelToIssue failed", append(logger.RequestAttrs(r), "error", err)...)@@ -495,6 +499,7 @@ func (h *Handler) AttachLabel(w http.ResponseWriter, r *http.Request) {// DetachLabel removes a label from an issue.func (h *Handler) DetachLabel(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)issueID := chi.URLParam(r, "id")labelID := chi.URLParam(r, "labelId")userID, ok := requireUserID(w, r)@@ -531,10 +536,12 @@ func (h *Handler) DetachLabel(w http.ResponseWriter, r *http.Request) {return}- detached, err := h.Queries.DetachLabelFromIssue(r.Context(), db.DetachLabelFromIssueParams{- IssueID: issue.ID,- LabelID: labelUUID,- WorkspaceID: issue.WorkspaceID,+ detached, err := wakeupWrite(h, r, func(q *db.Queries) (db.DetachLabelFromIssueRow, error) {+ return q.DetachLabelFromIssue(r.Context(), db.DetachLabelFromIssueParams{+ IssueID: issue.ID,+ LabelID: labelUUID,+ WorkspaceID: issue.WorkspaceID,+ })})if err != nil {slog.Warn("DetachLabelFromIssue failed", append(logger.RequestAttrs(r), "error", err)...)diff --git a/server/internal/handler/plugin_action.go b/server/internal/handler/plugin_action.goindex 1c1e095e03..f529fe7ef7 100644--- a/server/internal/handler/plugin_action.go+++ b/server/internal/handler/plugin_action.go@@ -615,7 +615,7 @@ func (h *Handler) CreatePluginComment(w http.ResponseWriter, r *http.Request) {"issue_status": issue.Status,})if rootComment != nil {- h.TaskService.AutoUnresolveThreadOnReply(r.Context(), rootComment, uuidToString(caller.WorkspaceID), authorType, uuidToString(authorID))+ h.TaskService.AutoUnresolveThreadOnReply(r.Context(), rootComment, uuidToString(caller.WorkspaceID), authorType, uuidToString(authorID), pgtype.UUID{})}writeJSON(w, http.StatusCreated, publicPluginComment(comment))diff --git a/server/internal/handler/property.go b/server/internal/handler/property.goindex 69a24d756a..b18917ed6b 100644--- a/server/internal/handler/property.go+++ b/server/internal/handler/property.go@@ -898,6 +898,7 @@ type SetIssuePropertyRequest struct {}func (h *Handler) SetIssueProperty(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)issueID := chi.URLParam(r, "id")propertyID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "propertyId"), "property id")if !ok {@@ -992,6 +993,7 @@ func (h *Handler) SetIssueProperty(w http.ResponseWriter, r *http.Request) {}func (h *Handler) DeleteIssueProperty(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)issueID := chi.URLParam(r, "id")propertyID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "propertyId"), "property id")if !ok {@@ -1020,10 +1022,12 @@ func (h *Handler) DeleteIssueProperty(w http.ResponseWriter, r *http.Request) {return}- updated, err := h.Queries.DeleteIssuePropertyValue(r.Context(), db.DeleteIssuePropertyValueParams{- ID: issue.ID,- WorkspaceID: issue.WorkspaceID,- Key: uuidToString(propertyID),+ updated, err := wakeupWrite(h, r, func(q *db.Queries) (db.Issue, error) {+ return q.DeleteIssuePropertyValue(r.Context(), db.DeleteIssuePropertyValueParams{+ ID: issue.ID,+ WorkspaceID: issue.WorkspaceID,+ Key: uuidToString(propertyID),+ })})if err != nil {slog.Warn("DeleteIssuePropertyValue failed", append(logger.RequestAttrs(r), "error", err, "issue_id", issueID)...)@@ -1049,7 +1053,7 @@ func (h *Handler) DeleteIssueProperty(w http.ResponseWriter, r *http.Request) {// definition creates/unarchives against each other (the 20-active cap and// MAX(position)+1 are read-then-write). Locks are transaction-scoped.func (h *Handler) withPropertyLock(r *http.Request, lockKeys []string, fn func(q *db.Queries) error) error {- tx, err := h.TxStarter.Begin(r.Context())+ tx, err := h.beginWakeupWrite(r.Context())if err != nil {return err}diff --git a/server/internal/handler/reaction.go b/server/internal/handler/reaction.goindex f01dde7f58..4266aab651 100644--- a/server/internal/handler/reaction.go+++ b/server/internal/handler/reaction.go@@ -51,6 +51,7 @@ func addedReactionToResponse(r db.AddReactionRow) ReactionResponse {}func (h *Handler) AddReaction(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)commentId := chi.URLParam(r, "commentId")userID, ok := requireUserID(w, r)@@ -140,6 +141,7 @@ func (h *Handler) AddReaction(w http.ResponseWriter, r *http.Request) {}func (h *Handler) RemoveReaction(w http.ResponseWriter, r *http.Request) {+ r = h.withWakeupActor(r)commentId := chi.URLParam(r, "commentId")userID, ok := requireUserID(w, r)diff --git a/server/internal/handler/wakeup_actor.go b/server/internal/handler/wakeup_actor.gonew file mode 100644index 0000000000..50bcc7285a--- /dev/null+++ b/server/internal/handler/wakeup_actor.go@@ -0,0 +1,63 @@+package handler++import (+ "context"+ "net/http"++ "github.com/jackc/pgx/v5"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type wakeupActorKey struct{}+type wakeupActor struct{ kind, id, task string }++// Carry only server-resolved request identity into transaction-local settings.+// In particular, mutation of another agent's comment must not reuse its author+// or original run as the source of the new event.+func (h *Handler) withWakeupActor(r *http.Request) *http.Request {+ if _, ok := r.Context().Value(wakeupActorKey{}).(wakeupActor); ok {+ return r+ }+ kind, id := h.resolveActor(r, requestUserID(r), h.resolveWorkspaceID(r))+ source := h.wakeupSourceTaskID(r)+ var task string+ if source.Valid {+ task = uuidToString(source)+ }+ return r.WithContext(context.WithValue(r.Context(), wakeupActorKey{}, wakeupActor{kind, id, task}))+}++func (h *Handler) beginWakeupWrite(ctx context.Context) (pgx.Tx, error) {+ tx, err := h.TxStarter.Begin(ctx)+ if err != nil {+ return nil, err+ }+ if actor, ok := ctx.Value(wakeupActorKey{}).(wakeupActor); ok {+ _, err = tx.Exec(ctx, `SELECT set_config('multica.actor_type',$1,true),set_config('multica.actor_id',$2,true),set_config('multica.source_task_id',$3,true)`, actor.kind, actor.id, actor.task)+ if err != nil {+ _ = tx.Rollback(ctx)+ return nil, err+ }+ }+ return tx, nil+}++// Single-statement mutation paths use the same source attribution as existing+// multi-statement transactions. Settings cannot leak into the pooled connection.+func wakeupWrite[T any](h *Handler, r *http.Request, write func(*db.Queries) (T, error)) (T, error) {+ var zero T+ r = h.withWakeupActor(r)+ tx, err := h.beginWakeupWrite(r.Context())+ if err != nil {+ return zero, err+ }+ defer tx.Rollback(r.Context())+ result, err := write(h.Queries.WithTx(tx))+ if err != nil {+ return zero, err+ }+ if err = tx.Commit(r.Context()); err != nil {+ return zero, err+ }+ return result, nil+}diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex bac1ad642a..f3f7022285 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -72,6 +72,8 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"inbox_item": workspaceDelete,"instance_telemetry_state": workspaceDeleteKeep,"issue": workspaceDelete,+ "issue_wakeup": workspaceDelete,+ "issue_wakeup_receipt": workspaceDelete,"issue_view": workspaceDelete,"issue_view_preference": workspaceDelete,"issue_dependency": workspaceDelete,diff --git a/server/internal/handler/workspace_wakeup_test.go b/server/internal/handler/workspace_wakeup_test.gonew file mode 100644index 0000000000..df60eb42bb--- /dev/null+++ b/server/internal/handler/workspace_wakeup_test.go@@ -0,0 +1,174 @@+package handler++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestWorkspaceWakeupsInventory(t *testing.T) {+ issue := dbfx.Issue(t, "wakeup inventory")+ agent := dbfx.Agent(t, "inventory target", testRuntimeID)+ dbfx.Cleanup(t, "DELETE FROM issue_wakeup WHERE issue_id=$1", issue)+ dbfx.Cleanup(t, "DELETE FROM issue_wakeup_receipt WHERE wakeup_id IN (SELECT id FROM issue_wakeup WHERE issue_id=$1)", issue)+ svc := service.IssueWakeupService{Tasks: testHandler.TaskService}+ var wakes []db.IssueWakeup+ for i := 0; i < 5; i++ {+ w, err := svc.Create(context.Background(), parseUUID(issue), parseUUID(testUserID), pgtype.UUID{}, service.WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"task.completed"}, Instruction: "PRIVATE PROMPT"})+ if err != nil {+ t.Fatal(err)+ }+ wakes = append(wakes, w)+ }+ // The latest task pointer is terminal, but an older retry is still active.+ run := dbfx.Task(t, agent, testutil.Cols{"issue_id": issue, "runtime_id": testRuntimeID, "status": "running", "started_at": testutil.Raw("now()"), "context": fmt.Sprintf(`{"wakeup_id":%q}`, uuidToString(wakes[0].ID))})+ last := dbfx.Task(t, agent, testutil.Cols{"issue_id": issue, "runtime_id": testRuntimeID, "status": "completed", "context": fmt.Sprintf(`{"wakeup_id":%q}`, uuidToString(wakes[0].ID))})+ dbfx.Exec(t, "UPDATE issue_wakeup SET enabled=false,last_task_id=$2 WHERE id=$1", wakes[0].ID, last)+ if _, err := svc.Disable(context.Background(), parseUUID(issue), wakes[1].ID, parseUUID(testUserID)); err != nil {+ t.Fatal(err)+ }+ dbfx.Exec(t, "UPDATE issue_wakeup SET enabled=false WHERE id=$1", wakes[2].ID)+ sourceAgent := dbfx.Agent(t, "private source", testRuntimeID)+ sourceRun := dbfx.Task(t, sourceAgent, testutil.Cols{"issue_id": issue, "runtime_id": testRuntimeID, "status": "completed"})+ dbfx.Exec(t, "UPDATE issue_wakeup SET filter_agent_id=$2,filter_task_id=$3 WHERE id=$1", wakes[4].ID, sourceAgent, sourceRun)+ type row struct {+ ID string `json:"id"`+ CanManage bool `json:"can_manage"`+ ActiveRuns int `json:"active_runs"`+ FilterAgentID *string `json:"filter_agent_id"`+ FilterAgentName *string `json:"filter_agent_name"`+ FilterTaskID *string `json:"filter_task_id"`+ Task *struct {+ ID string `json:"id"`+ } `json:"task"`+ }+ type page struct {+ Items []row `json:"items"`+ Total int `json:"total"`+ Counts map[string]int `json:"counts"`+ Agents []any `json:"agents"`+ }+ read := func(req *http.Request, want int) page {+ t.Helper()+ rec := httptest.NewRecorder()+ testHandler.ListWorkspaceWakeups(rec, req)+ if rec.Code != want {+ t.Fatalf("status %d: %s", rec.Code, rec.Body.String())+ }+ var out page+ if want == 200 {+ if strings.Contains(rec.Body.String(), "PRIVATE PROMPT") || strings.Contains(rec.Body.String(), "instruction") {+ t.Fatal("prompt in inventory")+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {+ t.Fatal(err)+ }+ }+ return out+ }+ get := func(query string) page { return read(newRequest("GET", "/api/issue-wakeups?"+query, nil), 200) }+ p := get("")+ if p.Total != 3 || len(p.Items) != 3 || p.Counts["all"] != 5 || p.Counts["disabled"] != 1 || p.Counts["ended"] != 1 {+ t.Fatalf("bad inventory %+v", p)+ }+ found := false+ for _, r := range p.Items {+ if !r.CanManage {+ t.Fatal("owner cannot manage")+ }+ if r.ID == uuidToString(wakes[0].ID) {+ found = true+ if r.Task == nil || r.Task.ID != run || r.ActiveRuns != 1 {+ t.Fatalf("lost retry %+v", r)+ }+ }+ }+ if !found {+ t.Fatal("consumed active run disappeared")+ }+ a, b := get("scope=all&limit=2"), get("scope=all&limit=2&offset=2")+ if a.Total != 5 || b.Total != 5 || len(a.Items) != 2 || len(b.Items) != 2 {+ t.Fatal("bad pagination")+ }+ for _, x := range a.Items {+ for _, y := range b.Items {+ if x.ID == y.ID {+ t.Fatal("duplicate page row")+ }+ }+ }+ p = get("scope=all&offset=999")+ if p.Total != 5 || len(p.Items) != 0 {+ t.Fatal("empty page lost count")+ }+ if p = get("search=INVENTORY&kind=event"); p.Total != 3 {+ t.Fatal("search failed")+ }+ if p = get("kind=recurring"); p.Total != 0 || p.Counts["all"] != 5 {+ t.Fatal("filter changed inventory counts")+ }+ for _, q := range []string{"scope=oops", "kind=oops", "limit=0", "limit=101", "offset=-1", "offset=2147483648", "agent_id=bad"} {+ read(newRequest("GET", "/?"+q, nil), 400)+ }+ outsider := dbfx.User(t, "inventory outsider", "[email protected]")+ req := newRequest("GET", "/?scope=all", nil)+ req.Header.Set("X-User-ID", outsider)+ read(req, 404)+ dbfx.Member(t, testWorkspaceID, outsider, "member")+ p = read(req, 200)+ if p.Total != 5 || len(p.Agents) != 1 || p.Counts["all"] != 5 {+ t.Fatal("shared issue rules disappeared from inventory")+ }+ for _, r := range p.Items {+ if r.CanManage || r.FilterAgentID != nil || r.FilterAgentName != nil || r.FilterTaskID != nil {+ t.Fatal("shared inventory granted management or private source access")+ }+ }+ // The public target is visible, but the rule remains managed by its creator.+ dbfx.Exec(t, "UPDATE agent SET visibility='workspace',permission_mode='public_to' WHERE id=$1", agent)+ dbfx.Insert(t, "agent_invocation_target", testutil.Cols{"agent_id": agent, "target_type": "workspace", "target_id": testWorkspaceID})+ p = read(req, 200)+ if p.Total != 5 {+ t.Fatalf("public inventory missing %+v", p)+ }+ for _, r := range p.Items {+ if r.CanManage {+ t.Fatal("member can manage another creator's rule")+ }+ if r.FilterAgentID != nil || r.FilterAgentName != nil || r.FilterTaskID != nil {+ t.Fatal("private source exposed")+ }+ }+ dbfx.Exec(t, "UPDATE agent_task_queue SET originator_user_id=$2,accountable_user_id=$2 WHERE id=$1", run, outsider)+ trusted := newRequest("GET", "/?scope=all", nil)+ trusted.Header.Set("X-Agent-ID", agent)+ trusted.Header.Set("X-Task-ID", run)+ trusted.Header.Set("X-Actor-Source", "task_token")+ for _, r := range read(trusted, 200).Items {+ if r.CanManage {+ t.Fatal("management flag borrowed runtime owner rights")+ }+ }+ other := dbfx.Workspace(t, "other inventory", "other-inventory")+ dbfx.Member(t, other, testUserID, "owner")+ req = newRequest("GET", "/?scope=all", nil)+ req.Header.Set("X-Workspace-ID", other)+ if p = read(req, 200); p.Total != 0 || len(p.Agents) != 0 {+ t.Fatal("cross workspace inventory")+ }+ // Terminal issues stay visible as ended, except already-running work.+ dbfx.Exec(t, "UPDATE issue SET status='done' WHERE id=$1", issue)+ p = get("")+ if p.Total != 1 || p.Items[0].Task == nil || p.Items[0].Task.ID != run {+ t.Fatalf("closed running state %+v", p)+ }+}diff --git a/server/internal/scheduler/jobs_issue_wakeup.go b/server/internal/scheduler/jobs_issue_wakeup.gonew file mode 100644index 0000000000..1783ff654b--- /dev/null+++ b/server/internal/scheduler/jobs_issue_wakeup.go@@ -0,0 +1,21 @@+package scheduler++import (+ "context"+ "time"+)++type IssueWakeupDispatcher interface{ Tick(context.Context) error }++// Receipts and due times persist independently of the scheduler's plan bucket.+// A missed bucket therefore cannot drop a one-shot wakeup.+func IssueWakeupJob(dispatcher IssueWakeupDispatcher) JobSpec {+ return JobSpec{+ Name: "issue_wakeup_dispatch", Cadence: 30 * time.Second, CatchUpMode: CatchUpLatestOnly, CatchUpWindow: time.Hour,+ RunTimeout: 45 * time.Second, StaleTimeout: time.Minute, HeartbeatInterval: 10 * time.Second,+ AllowStaleReentry: true, MaxAttempts: 1, Scopes: StaticScopes(ScopeGlobal),+ Handler: func(ctx context.Context, _ HandlerInput) (HandlerResult, error) {+ return HandlerResult{}, dispatcher.Tick(ctx)+ },+ }+}diff --git a/server/internal/service/agent_invocation.go b/server/internal/service/agent_invocation.gonew file mode 100644index 0000000000..ae936bf540--- /dev/null+++ b/server/internal/service/agent_invocation.go@@ -0,0 +1,46 @@+package service++import (+ "context"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// CanMemberInvokeAgent applies the existing invocation policy for durable triggers.+func CanMemberInvokeAgent(ctx context.Context, queries *db.Queries, agent db.Agent, memberUserID pgtype.UUID, workspaceID pgtype.UUID) bool {+ userID := util.UUIDToString(memberUserID)+ if userID == "" {+ return false+ }+ if util.UUIDToString(agent.OwnerID) == userID {+ return true+ }+ if agent.PermissionMode != "public_to" {+ return false+ }+ targets, err := queries.ListAgentInvocationTargets(ctx, agent.ID)+ if err != nil {+ return false+ }+ isWorkspaceMember := false+ if _, err := queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{+ UserID: memberUserID,+ WorkspaceID: workspaceID,+ }); err == nil {+ isWorkspaceMember = true+ }+ for _, t := range targets {+ switch t.TargetType {+ case "workspace":+ if isWorkspaceMember {+ return true+ }+ case "member":+ if util.UUIDToString(t.TargetID) == userID {+ return true+ }+ }+ }+ return false+}diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.goindex 28e4b1a5e3..7a72fe62f4 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -1926,38 +1926,5 @@ func (s *AutopilotService) autopilotAdmitInvoke(ctx context.Context, ap db.Autop// autopilot "run now" where the clicker, not the creator, is the admission// principal. Fail-closed on any lookup error; no admin bypass.func (s *AutopilotService) canMemberInvokeAgent(ctx context.Context, agent db.Agent, memberUserID pgtype.UUID, workspaceID pgtype.UUID) bool {- userID := util.UUIDToString(memberUserID)- if userID == "" {- return false- }- if util.UUIDToString(agent.OwnerID) == userID {- return true- }- if agent.PermissionMode != "public_to" {- return false- }- targets, err := s.Queries.ListAgentInvocationTargets(ctx, agent.ID)- if err != nil {- return false- }- isWorkspaceMember := false- if _, err := s.Queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{- UserID: memberUserID,- WorkspaceID: workspaceID,- }); err == nil {- isWorkspaceMember = true- }- for _, t := range targets {- switch t.TargetType {- case "workspace":- if isWorkspaceMember {- return true- }- case "member":- if util.UUIDToString(t.TargetID) == userID {- return true- }- }- }- return false+ return CanMemberInvokeAgent(ctx, s.Queries, agent, memberUserID, workspaceID)}diff --git a/server/internal/service/builtin_skills/multica-platform/SKILL.md b/server/internal/service/builtin_skills/multica-platform/SKILL.mdindex 33c3185fad..da204c398f 100644--- a/server/internal/service/builtin_skills/multica-platform/SKILL.md+++ b/server/internal/service/builtin_skills/multica-platform/SKILL.md@@ -19,7 +19,7 @@ Read the invariants below, then open the reference(s) your task actually needs| Open | When the task is about ||---|---|-| `references/issues.md` | Issues: PR linking vs close intent, reading a linked PR's state, custom properties, status side effects, sub-issues and stages, who else is running |+| `references/issues.md` | Issues: PR linking vs close intent, reading a linked PR's state, custom properties, status side effects, sub-issues and stages, who else is running, event/time wakeups || `references/mentions.md` | Writing a `mention://` link: which types enqueue a run, which are inert, why one silently did nothing || `references/agents.md` | Creating, copying or debugging an agent definition: fields, secrets, MCP config, skill binding || `references/squads.md` | Squads: leader routing, roster, recording leader activity, why a squad did or did not run |diff --git a/server/internal/service/builtin_skills/multica-platform/references/issues.md b/server/internal/service/builtin_skills/multica-platform/references/issues.mdindex 058fec7bfd..678d6fa6a6 100644--- a/server/internal/service/builtin_skills/multica-platform/references/issues.md+++ b/server/internal/service/builtin_skills/multica-platform/references/issues.md@@ -419,3 +419,31 @@ multica issue create --title "Step 1" --parent <issue-id> --assignee <agent> --smultica issue create --title "Step 2" --parent <issue-id> --assignee <agent> --stage 2 --status backlogmultica issue create --title "Step 3" --parent <issue-id> --assignee <agent> --stage 3 --status backlog```++## Issue wakeups++Use `multica issue wakeup` to arrange a future ordinary run, then finish the+current run. A wakeup persists on the issue; it is not a sleeping process.++- `wakeup events` lists supported business facts. These work with plugins disabled.+- `wakeup create <issue> --agent-id <target> --kind event --event task.completed,task.failed,task.cancelled --task-id <run> --instruction-file ./instruction.md` wakes once. Omit `--agent-id` only when acting as the authenticated agent. A specific run must belong to this issue; if already terminal, registration captures its matching state immediately.+- For a continuing subscription use `--mode continuous`. For task events, use `--filter-agent-id` to match that agent's future runs; this does not replay historical runs. For comment/issue/reaction/attachment changes, use `--filter-actor-type member|agent --filter-actor-id <user-or-agent-id>` to match the actual author/editor. Mutation-only `--filter-agent-id` remains a legacy alias for actor=agent; do not combine it with actor flags.+- `wakeup create <issue> --kind at --after 10m --instruction-file ./instruction.md` schedules one run. Alternatively use `--at <RFC3339>`.+- `wakeup create <issue> --kind every --every 1h --instruction-file ./instruction.md` schedules a repeating check. Or use `--kind cron --cron '0 * * * *' --timezone Asia/Shanghai`.+- `wakeup list <issue>` / `wakeup get <issue> <id>` show the saved configuration, next time and latest run. Only promise that a reminder is arranged after creation succeeds.+- `wakeup update <issue> <id>` uses the same flags as create and replaces the whole configuration, explicitly re-enabling it. Supply all intended fields. Old unclaimed work is withdrawn.+- `wakeup disable <issue> <id>` stops future triggers and withdraws unclaimed work. Users can also turn it off in the issue sidebar. Closing/cancelling/completing the issue disables its wakeups; reopening does not restore them.+- `--parent <comment-id>` keeps result delivery in the original thread.++Read current state with issue get, comment list, and run inspection before+judging business completion. For CI, use the existing GitHub tools from a time+wakeup; CI events are not supported here yet. A failed run does not imply its+business goal is complete. Automatic retry chains are not followed by event+filters; subscribe to a new run if needed. Once the goal is met, disable any+continuous configuration. Every wakeup runs under ordinary execution and comment+delivery rules, even when a periodic check finds no change.++Self-trigger protection excludes the registering run and runs started by the+same rule when their source identity is available. It does not prevent cycles+between different rules. Avoid mutually triggering continuous comment subscriptions;+when waiting for a person's reply, filter that member explicitly.diff --git a/server/internal/service/issue_wakeup.go b/server/internal/service/issue_wakeup.gonew file mode 100644index 0000000000..908f51edfd--- /dev/null+++ b/server/internal/service/issue_wakeup.go@@ -0,0 +1,814 @@+package service++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "slices"+ "strings"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/issuestatus"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/dbid"+ "github.com/multica-ai/multica/server/pkg/eventcontract"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++var ErrWakeupInput = errors.New("invalid wakeup")+var ErrWakeupConflict = errors.New("wakeup changed; refresh and retry")+var ErrWakeupForbidden = errors.New("wakeup permission denied")++// WakeupEventTypes is independent of plugin availability. These facts have+// transactional capture into matching receipts, including non-HTTP writers.+var WakeupEventTypes = eventcontract.WakeupTypes++type WakeupInput struct {+ AgentID string `json:"agent_id"`+ Instruction string `json:"instruction"`+ Kind string `json:"kind"`+ Mode string `json:"mode"`+ EventTypes []string `json:"event_types"`+ FilterAgentID string `json:"filter_agent_id"`+ FilterActorType string `json:"filter_actor_type"`+ FilterActorID string `json:"filter_actor_id"`+ FilterTaskID string `json:"filter_task_id"`+ ParentCommentID string `json:"parent_comment_id"`+ AfterSeconds int64 `json:"after_seconds"`+ At *time.Time `json:"at"`+ IntervalSeconds int64 `json:"interval_seconds"`+ CronExpression string `json:"cron_expression"`+ Timezone string `json:"timezone"`+}++type IssueWakeupService struct{ Tasks *TaskService }++func (s *IssueWakeupService) Validate(in *WakeupInput, now time.Time) (pgtype.Timestamptz, error) {+ bad := func(msg string) (pgtype.Timestamptz, error) {+ return pgtype.Timestamptz{}, fmt.Errorf("%w: %s", ErrWakeupInput, msg)+ }+ in.Instruction = strings.TrimSpace(in.Instruction)+ if len(in.Instruction) == 0 || len(in.Instruction) > 12000 {+ return bad("instruction must contain 1–12000 bytes")+ }+ if in.Timezone == "" {+ in.Timezone = "UTC"+ }+ if _, err := time.LoadLocation(in.Timezone); err != nil {+ return bad("invalid timezone")+ }+ if in.Mode == "" {+ if in.Kind == "every" || in.Kind == "cron" {+ in.Mode = "continuous"+ } else {+ in.Mode = "once"+ }+ }+ if in.Mode != "once" && in.Mode != "continuous" {+ return bad("mode must be once or continuous")+ }+ if in.FilterActorType != "" || in.FilterActorID != "" {+ if in.Kind != "event" || (in.FilterActorType != "member" && in.FilterActorType != "agent") || in.FilterActorID == "" {+ return bad("actor filter requires an event, member or agent type, and actor ID")+ }+ if in.FilterAgentID != "" || in.FilterTaskID != "" {+ return bad("choose an actor filter or agent/run filters")+ }+ for _, event := range in.EventTypes {+ if strings.HasPrefix(event, "task.") {+ return bad("actor filters apply to issue, comment, reaction and attachment changes; use agent/run filters for task events")+ }+ }+ }+ switch in.Kind {+ case "event":+ if len(in.EventTypes) == 0 || len(in.EventTypes) > len(WakeupEventTypes) {+ return bad("select at least one supported event")+ }+ for _, e := range in.EventTypes {+ if slices.Contains(eventcontract.LifecycleTypes, e) {+ return bad(e + " cannot wake its own issue; subscriptions require an existing, open issue")+ }+ if !slices.Contains(WakeupEventTypes, e) {+ return bad("unsupported event: " + e)+ }+ }+ if in.FilterTaskID != "" {+ for _, e := range in.EventTypes {+ if !strings.HasPrefix(e, "task.") {+ return bad("task filter requires task events")+ }+ }+ }+ if in.AfterSeconds != 0 || in.At != nil || in.IntervalSeconds != 0 || in.CronExpression != "" {+ return bad("event wakeups cannot contain a schedule")+ }+ // Legacy mutation-only agent filters are an alias of actor=agent. Keep+ // mixed task/mutation subscriptions unchanged for existing API clients.+ if in.FilterAgentID != "" && in.FilterTaskID == "" {+ mutationOnly := true+ for _, event := range in.EventTypes {+ if strings.HasPrefix(event, "task.") {+ mutationOnly = false+ }+ }+ if mutationOnly {+ in.FilterActorType, in.FilterActorID = "agent", in.FilterAgentID+ in.FilterAgentID = ""+ }+ }+ return pgtype.Timestamptz{}, nil+ case "at":+ if in.Mode != "once" {+ return bad("single time requires once mode")+ }+ if (in.At == nil) == (in.AfterSeconds == 0) || in.AfterSeconds < 0 || in.AfterSeconds > 31536000 {+ return bad("provide at or after_seconds (1–31536000)")+ }+ if in.IntervalSeconds != 0 || in.CronExpression != "" {+ return bad("incompatible schedule fields")+ }+ if in.At != nil {+ return pgtype.Timestamptz{Time: in.At.UTC(), Valid: true}, nil+ }+ return pgtype.Timestamptz{Time: now.Add(time.Duration(in.AfterSeconds) * time.Second), Valid: true}, nil+ case "every":+ if in.Mode != "continuous" || in.IntervalSeconds < 60 || in.IntervalSeconds > 31536000 || in.At != nil || in.AfterSeconds != 0 || in.CronExpression != "" {+ return bad("every requires continuous mode and interval_seconds between 60 and 31536000")+ }+ return pgtype.Timestamptz{Time: now.Add(time.Duration(in.IntervalSeconds) * time.Second), Valid: true}, nil+ case "cron":+ if in.Mode != "continuous" || in.At != nil || in.AfterSeconds != 0 || in.IntervalSeconds != 0 {+ return bad("cron requires continuous mode without other schedule fields")+ }+ t, err := NextOccurrenceAfterUTC(in.CronExpression, in.Timezone, now)+ if err != nil || t.IsZero() {+ return bad("cron must have a future occurrence")+ }+ return pgtype.Timestamptz{Time: t, Valid: true}, nil+ default:+ return bad("kind must be event, at, every or cron")+ }+}++func wakeupUUID(s string) (pgtype.UUID, error) {+ if s == "" {+ return pgtype.UUID{}, nil+ }+ id, err := util.ParseUUID(s)+ if err != nil {+ return id, fmt.Errorf("%w: invalid UUID", ErrWakeupInput)+ }+ return id, nil+}++func wakeupIssueActive(ctx context.Context, q *db.Queries, i db.Issue) (bool, error) {+ category, err := issuestatus.CategoryWithError(ctx, q, i.WorkspaceID, i.Status)+ if err != nil {+ return false, err+ }+ return category != "done" && category != "closed", nil+}++func (s *IssueWakeupService) Create(ctx context.Context, issueID, member, source pgtype.UUID, in WakeupInput) (db.IssueWakeup, error) {+ return s.Save(ctx, issueID, member, source, pgtype.UUID{}, in)+}++type WakeupEnableInput struct {+ Revision int64 `json:"revision"`+ At *time.Time `json:"at,omitempty"`+ Rearm bool `json:"rearm,omitempty"`+}++type WakeupInstructionInput struct {+ Instruction string `json:"instruction"`+ ExpectedInstruction string `json:"expected_instruction"`+ Revision int64 `json:"revision"`+}++// EditInstruction preserves the subscription revision and queued work. Compare+// both the revision and the prior text so concurrent edits cannot overwrite one+// another, without invalidating captured events or rearming a consumed rule.+func (s *IssueWakeupService) EditInstruction(ctx context.Context, issueID, id, member pgtype.UUID, in WakeupInstructionInput) error {+ in.Instruction = strings.TrimSpace(in.Instruction)+ if len(in.Instruction) == 0 || len(in.Instruction) > 12000 || in.Revision < 1 {+ return fmt.Errorf("%w: instruction must be 1–12000 bytes and revision is required", ErrWakeupInput)+ }+ tx, err := s.Tasks.TxStarter.Begin(ctx)+ if err != nil {+ return err+ }+ defer tx.Rollback(ctx)+ q := s.Tasks.Queries.WithTx(tx)+ var workspace pgtype.UUID+ if err = tx.QueryRow(ctx, "SELECT w.id FROM workspace w JOIN issue i ON i.workspace_id=w.id WHERE i.id=$1 FOR KEY SHARE OF w", issueID).Scan(&workspace); err != nil {+ return err+ }+ issue, err := q.LockWakeupIssue(ctx, issueID)+ if err != nil {+ return err+ }+ membership, err := q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{UserID: member, WorkspaceID: issue.WorkspaceID})+ if err != nil {+ return ErrWakeupForbidden+ }+ w, err := q.LockIssueWakeup(ctx, id)+ if err != nil {+ return err+ }+ if w.IssueID != issue.ID || w.WorkspaceID != issue.WorkspaceID {+ return pgx.ErrNoRows+ }+ if w.CreatedBy != member && membership.Role != "owner" && membership.Role != "admin" {+ return ErrWakeupForbidden+ }+ agent, err := q.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: w.AgentID, WorkspaceID: issue.WorkspaceID})+ if err != nil {+ return ErrWakeupForbidden+ }+ if err = s.authorize(ctx, q, issue.WorkspaceID, member, agent); err != nil {+ return err+ }+ if w.Revision != in.Revision || w.Instruction != in.ExpectedInstruction {+ return ErrWakeupConflict+ }+ _, err = tx.Exec(ctx, "UPDATE issue_wakeup SET instruction=$2,updated_at=now() WHERE id=$1 AND workspace_id=$3", id, in.Instruction, workspace)+ if err != nil {+ return err+ }+ return tx.Commit(ctx)+}++// Enable reads the configuration under Save's locks; clients never round-trip+// instructions or filters. The revision fences stale toggles and duplicate rearm.+func (s *IssueWakeupService) Enable(ctx context.Context, issueID, member, source, id pgtype.UUID, in WakeupEnableInput) (db.IssueWakeup, error) {+ return s.save(ctx, issueID, member, source, id, WakeupInput{}, &in)+}++// Save replaces a subscription explicitly; revisions fence obsolete queued work.+func (s *IssueWakeupService) Save(ctx context.Context, issueID, member, source, existingID pgtype.UUID, in WakeupInput) (db.IssueWakeup, error) {+ return s.save(ctx, issueID, member, source, existingID, in, nil)+}++func (s *IssueWakeupService) save(ctx context.Context, issueID, member, source, existingID pgtype.UUID, in WakeupInput, enable *WakeupEnableInput) (db.IssueWakeup, error) {+ var out db.IssueWakeup+ tx, err := s.Tasks.TxStarter.Begin(ctx)+ if err != nil {+ return out, err+ }+ defer tx.Rollback(ctx)+ q := s.Tasks.Queries.WithTx(tx)+ var workspace pgtype.UUID+ if err = tx.QueryRow(ctx, "SELECT w.id FROM workspace w JOIN issue i ON i.workspace_id=w.id WHERE i.id=$1 FOR KEY SHARE OF w", issueID).Scan(&workspace); err != nil {+ return out, err+ }+ issue, err := q.LockWakeupIssue(ctx, issueID)+ if err != nil {+ return out, err+ }+ active, err := wakeupIssueActive(ctx, q, issue)+ if err != nil {+ return out, err+ }+ if !active {+ return out, fmt.Errorf("%w: issue is closed", ErrWakeupInput)+ }+ var now time.Time+ if err = tx.QueryRow(ctx, "SELECT now()").Scan(&now); err != nil {+ return out, err+ }++ if enable != nil {+ old, e := q.LockIssueWakeup(ctx, existingID)+ if e != nil {+ return out, e+ }+ if old.IssueID != issueID || old.WorkspaceID != issue.WorkspaceID {+ return out, pgx.ErrNoRows+ }+ if enable.Revision < 1 {+ return out, fmt.Errorf("%w: revision is required", ErrWakeupInput)+ }+ if old.Revision != enable.Revision {+ return out, ErrWakeupConflict+ }+ optionalID := func(id pgtype.UUID) string {+ if id.Valid {+ return util.UUIDToString(id)+ }+ return ""+ }+ in = WakeupInput{AgentID: optionalID(old.AgentID), Instruction: old.Instruction, Kind: old.Kind, Mode: old.Mode, EventTypes: old.EventTypes, FilterAgentID: optionalID(old.FilterAgentID), FilterTaskID: optionalID(old.FilterTaskID), FilterActorType: old.FilterActorType.String, FilterActorID: optionalID(old.FilterActorID), ParentCommentID: optionalID(old.ParentCommentID), IntervalSeconds: old.IntervalSeconds.Int64, CronExpression: old.CronExpression.String, Timezone: old.Timezone}+ if enable.At != nil && old.Kind != "at" {+ return out, fmt.Errorf("%w: only single-time wakeups accept a new time", ErrWakeupInput)+ }+ if !old.Enabled && old.Mode == "once" && (!old.DisabledAt.Valid || old.LastTaskID.Valid) {+ if !enable.Rearm {+ return out, fmt.Errorf("%w: consumed one-shot requires explicit rearm", ErrWakeupInput)+ }+ var activeRun bool+ if e = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM agent_task_queue WHERE issue_id=$1 AND context->>'wakeup_id'=$2 AND status IN ('queued','deferred','dispatched','running','waiting_local_directory'))", issueID, optionalID(old.ID)).Scan(&activeRun); e != nil {+ return out, e+ }+ if activeRun {+ return out, fmt.Errorf("%w: previous run is still active", ErrWakeupConflict)+ }+ }+ if old.Kind == "at" {+ if old.NextFireAt.Valid {+ at := old.NextFireAt.Time+ in.At = &at+ }+ if enable.At != nil {+ in.At = enable.At+ }+ if !old.Enabled && (in.At == nil || !in.At.After(now)) {+ return out, fmt.Errorf("%w: choose a future time", ErrWakeupInput)+ }+ }+ }+ next, err := s.Validate(&in, now)+ if err != nil {+ return out, err+ }+ agentID, err := wakeupUUID(in.AgentID)+ if err != nil || !agentID.Valid {+ return out, fmt.Errorf("%w: agent_id is required", ErrWakeupInput)+ }+ agent, err := q.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: agentID, WorkspaceID: issue.WorkspaceID})+ if err != nil {+ return out, ErrWakeupForbidden+ }+ if err = s.authorize(ctx, q, issue.WorkspaceID, member, agent); err != nil {+ return out, err+ }+ filterAgent, err := wakeupUUID(in.FilterAgentID)+ if err != nil {+ return out, err+ }+ filterTask, err := wakeupUUID(in.FilterTaskID)+ if err != nil {+ return out, err+ }+ filterActor, err := wakeupUUID(in.FilterActorID)+ if err != nil {+ return out, err+ }+ if filterActor.Valid {+ if in.FilterActorType == "member" {+ _, err = q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{UserID: filterActor, WorkspaceID: issue.WorkspaceID})+ } else {+ _, err = q.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: filterActor, WorkspaceID: issue.WorkspaceID})+ }+ if errors.Is(err, pgx.ErrNoRows) {+ return out, ErrWakeupForbidden+ }+ if err != nil {+ return out, err+ }+ }+ parent, err := wakeupUUID(in.ParentCommentID)+ if err != nil {+ return out, err+ }+ if filterAgent.Valid {+ if _, err = q.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: filterAgent, WorkspaceID: issue.WorkspaceID}); err != nil {+ return out, ErrWakeupForbidden+ }+ }+ if in.Kind != "event" && (len(in.EventTypes) > 0 || filterAgent.Valid || filterTask.Valid) {+ return out, fmt.Errorf("%w: time wakeup cannot contain event filters", ErrWakeupInput)+ }+ if parent.Valid {+ var exists bool+ err = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM comment WHERE id=$1 AND issue_id=$2 AND deleted_at IS NULL)", parent, issueID).Scan(&exists)+ if err != nil {+ return out, err+ }+ if !exists {+ return out, fmt.Errorf("%w: comment not found", ErrWakeupInput)+ }+ }+ if existingID.Valid {+ old, e := q.LockIssueWakeup(ctx, existingID)+ if e != nil {+ return out, e+ }+ if old.IssueID != issueID || old.WorkspaceID != issue.WorkspaceID {+ return out, pgx.ErrNoRows+ }+ membership, e := q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{UserID: member, WorkspaceID: issue.WorkspaceID})+ if e != nil {+ return out, ErrWakeupForbidden+ }+ if old.CreatedBy != member && membership.Role != "owner" && membership.Role != "admin" {+ return out, ErrWakeupForbidden+ }+ if enable != nil && old.Enabled {+ if enable.Rearm || enable.At != nil {+ return out, ErrWakeupConflict+ }+ return old, tx.Commit(ctx)+ }+ if err = q.DiscardWakeupReceipts(ctx, old.ID); err != nil {+ return out, err+ }+ if _, err = q.CancelUnstartedWakeupTasks(ctx, util.UUIDToString(old.ID)); err != nil {+ return out, err+ }+ }+ var target db.AgentTaskQueue+ if filterTask.Valid {+ target, err = q.LockWakeupSourceTask(ctx, db.LockWakeupSourceTaskParams{ID: filterTask, IssueID: issueID})+ if errors.Is(err, pgx.ErrNoRows) {+ return out, fmt.Errorf("%w: run does not belong to this issue", ErrWakeupInput)+ }+ if err != nil {+ return out, err+ }+ if filterAgent.Valid && filterAgent != target.AgentID {+ return out, fmt.Errorf("%w: run and agent filters disagree", ErrWakeupInput)+ }+ }+ params := db.CreateIssueWakeupParams{ID: dbid.NewV7(), WorkspaceID: issue.WorkspaceID, IssueID: issue.ID, AgentID: agent.ID, CreatedBy: member, SourceTaskID: source, ParentCommentID: parent, Instruction: in.Instruction, Kind: in.Kind, Mode: in.Mode, EventTypes: append([]string{}, in.EventTypes...), FilterAgentID: filterAgent, FilterTaskID: filterTask, FilterActorType: pgtype.Text{String: in.FilterActorType, Valid: in.FilterActorType != ""}, FilterActorID: filterActor, IntervalSeconds: pgtype.Int8{Int64: in.IntervalSeconds, Valid: in.IntervalSeconds > 0}, CronExpression: pgtype.Text{String: in.CronExpression, Valid: in.CronExpression != ""}, Timezone: in.Timezone, NextFireAt: next}+ if existingID.Valid {+ _, err = tx.Exec(ctx, `UPDATE issue_wakeup SET agent_id=$2,created_by=$3,source_task_id=$4,parent_comment_id=$5,instruction=$6,kind=$7,mode=$8,event_types=$9,filter_agent_id=$10,filter_task_id=$11,interval_seconds=$12,cron_expression=$13,timezone=$14,next_fire_at=$15,filter_actor_type=$16,filter_actor_id=$17,enabled=true,disabled_at=NULL,revision=revision+1,last_task_id=NULL,last_error=NULL,updated_at=now() WHERE id=$1`, existingID, params.AgentID, member, source, parent, in.Instruction, in.Kind, in.Mode, params.EventTypes, filterAgent, filterTask, params.IntervalSeconds, params.CronExpression, in.Timezone, next, params.FilterActorType, filterActor)+ if err == nil {+ out, err = q.LockIssueWakeup(ctx, existingID)+ }+ } else {+ out, err = q.CreateIssueWakeup(ctx, params)+ }+ if err != nil {+ return out, err+ }+ // Subscribe and inspect the concrete source under the same row lock. This+ // closes the already-terminal race even if the caller exits immediately.+ if filterTask.Valid && slices.Contains([]string{"completed", "failed", "cancelled"}, target.Status) && slices.Contains(in.EventTypes, eventcontract.TaskEvent(target.Status)) {+ payload, _ := json.Marshal(map[string]any{+ "event_id": util.UUIDToString(target.ID) + ":" + target.Status, "event_type": eventcontract.TaskEvent(target.Status), "version": 1,+ "occurred_at": target.CompletedAt, "observed_at": now, "registration_snapshot": true,+ "workspace_id": util.UUIDToString(issue.WorkspaceID), "issue_id": util.UUIDToString(issue.ID),+ "task_id": util.UUIDToString(target.ID), "source_task_id": util.UUIDToString(target.ID), "status": target.Status,+ "agent_id": util.UUIDToString(target.AgentID), "actor_type": "agent", "actor_id": util.UUIDToString(target.AgentID),+ "retry_of_task_id": target.RetryOfTaskID, "rerun_of_task_id": target.RerunOfTaskID,+ })+ _, err = q.RecordWakeupReceipt(ctx, db.RecordWakeupReceiptParams{ID: dbid.NewV7(), WakeupID: out.ID, Revision: out.Revision, EventKey: util.UUIDToString(target.ID) + ":" + target.Status, EventType: "task." + target.Status, Payload: payload})+ if err != nil {+ return out, err+ }+ if out.Mode == "once" {+ out.Enabled = false+ err = q.AdvanceIssueWakeup(ctx, db.AdvanceIssueWakeupParams{ID: out.ID, Enabled: false})+ if err != nil {+ return out, err+ }+ }+ }+ if err = tx.Commit(ctx); err != nil {+ return out, err+ }+ return out, nil+}++func (s *IssueWakeupService) authorize(ctx context.Context, q *db.Queries, ws, member pgtype.UUID, a db.Agent) error {+ if !member.Valid || a.ArchivedAt.Valid || !a.RuntimeID.Valid {+ return ErrWakeupForbidden+ }+ if _, err := q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{UserID: member, WorkspaceID: ws}); err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return ErrWakeupForbidden+ }+ return err+ }+ if !CanMemberInvokeAgent(ctx, q, a, member, ws) {+ return ErrWakeupForbidden+ }+ return nil+}++// Tick uses the existing scheduler lease. Each config has a row lock as well,+// so a manual retry or a second server cannot dispatch the same receipt twice.+func (s *IssueWakeupService) Tick(ctx context.Context) error {+ // Receipts are operational evidence, not the run history. Match the existing+ // event telemetry's seven-day retention; never expire unprocessed inputs.+ cleanupCtx, cleanupCancel := context.WithTimeout(ctx, 2*time.Second)+ _, cleanupErr := s.Tasks.Queries.DeleteExpiredWakeupReceipts(cleanupCtx, pgtype.Timestamptz{Time: time.Now().Add(-7 * 24 * time.Hour), Valid: true})+ cleanupCancel()+ rows, err := s.Tasks.Queries.ListReadyWakeups(ctx)+ if err != nil {+ return err+ }+ var errs []error+ if cleanupErr != nil {+ errs = append(errs, fmt.Errorf("expire wakeup receipts: %w", cleanupErr))+ }+ for _, w := range rows {+ if ctx.Err() != nil {+ return errors.Join(append(errs, ctx.Err())...)+ }+ // Outcome writes must not turn a busy rule row into another batch-wide+ // wait. Use the batch context, not dispatch's expired per-rule context.+ if err = s.dispatch(ctx, w); err != nil {+ errs = append(errs, fmt.Errorf("wakeup %s: %w", util.UUIDToString(w.ID), err))+ outcomeCtx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)+ _ = s.Tasks.Queries.NoteWakeupFailure(outcomeCtx, db.NoteWakeupFailureParams{ID: w.ID, LastError: pgtype.Text{String: truncateForSummary(err.Error(), 500), Valid: true}})+ cancel()+ }+ outcomeCtx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)+ if touchErr := s.Tasks.Queries.TouchWakeupDispatch(outcomeCtx, w.ID); touchErr != nil {+ errs = append(errs, touchErr)+ }+ cancel()+ }+ return errors.Join(errs...)+}++func (s *IssueWakeupService) dispatch(ctx context.Context, prev db.IssueWakeup) error {+ // A rule gets at most two seconds including credentials and SQL. Lock waits+ // below are shorter: even 100 contended rules consume only ~5s of the 45s+ // batch budget, leaving time to dispatch unrelated issues.+ ctx, cancel := context.WithTimeout(ctx, 2*time.Second)+ defer cancel()+ // Resolve optional connected-app credentials before taking database locks.+ candidate, readErr := s.Tasks.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: prev.AgentID, WorkspaceID: prev.WorkspaceID})+ if readErr != nil && !errors.Is(readErr, pgx.ErrNoRows) {+ return readErr+ }+ var overlay runtimeMCPOverlayData+ if candidate.ID.Valid && s.authorize(ctx, s.Tasks.Queries, prev.WorkspaceID, prev.CreatedBy, candidate) == nil {+ overlay = s.Tasks.buildRuntimeMCPOverlay(ctx, prev.CreatedBy, candidate)+ }+ tx, err := s.Tasks.TxStarter.Begin(ctx)+ if err != nil {+ return err+ }+ defer tx.Rollback(ctx)+ if _, err = tx.Exec(ctx, "SET LOCAL lock_timeout = '50ms'"); err != nil {+ return err+ }+ q := s.Tasks.Queries.WithTx(tx)+ var fenced bool+ if candidate.ID.Valid {+ if err = tx.QueryRow(ctx, "SELECT lock_task_owner_rows($1,$2,$3)", candidate.ID, prev.IssueID, candidate.RuntimeID).Scan(&fenced); err != nil {+ return err+ }+ if !fenced {+ return pgx.ErrNoRows+ }+ } else {+ if _, err = q.LockWorkspaceForChatSessionCreate(ctx, prev.WorkspaceID); err != nil {+ return err+ }+ }+ issue, err := q.LockWakeupIssue(ctx, prev.IssueID)+ if errors.Is(err, pgx.ErrNoRows) {+ return qCleanupMissingWakeup(ctx, tx, prev.ID)+ }+ if err != nil {+ return err+ }+ w, err := q.LockIssueWakeup(ctx, prev.ID)+ if err != nil {+ return err+ }+ if w.Revision != prev.Revision {+ return tx.Commit(ctx)+ }+ active, err := wakeupIssueActive(ctx, q, issue)+ if err != nil {+ return err+ }+ agent, err := q.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: w.AgentID, WorkspaceID: w.WorkspaceID})+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {+ return err+ }+ if agent.ID.Valid && agent.RuntimeID != candidate.RuntimeID {+ return tx.Commit(ctx)+ }+ authErr := s.authorize(ctx, q, w.WorkspaceID, w.CreatedBy, agent)+ if w.DisabledAt.Valid || !active || authErr != nil {+ if authErr != nil && !errors.Is(authErr, ErrWakeupForbidden) {+ return authErr+ }+ _, err = tx.Exec(ctx, "UPDATE issue_wakeup SET enabled=false,disabled_at=COALESCE(disabled_at,now()),last_error=$2 WHERE id=$1", w.ID, "Wakeup disabled: issue closed or permission unavailable")+ if err != nil {+ return err+ }+ if err = q.DiscardWakeupReceipts(ctx, w.ID); err != nil {+ return err+ }+ if _, err = q.CancelUnstartedWakeupTasks(ctx, util.UUIDToString(w.ID)); err != nil {+ return err+ }+ return tx.Commit(ctx)+ }+ if _, err = tx.Exec(ctx, "UPDATE issue_wakeup_receipt SET processed_at=now() WHERE wakeup_id=$1 AND revision<>$2 AND processed_at IS NULL", w.ID, w.Revision); err != nil {+ return err+ }+ var now time.Time+ if err = tx.QueryRow(ctx, "SELECT now()").Scan(&now); err != nil {+ return err+ }+ next := w.NextFireAt+ enabled := w.Enabled+ if w.Mode == "once" && w.LastTaskID.Valid {+ if err := q.DiscardWakeupReceipts(ctx, w.ID); err != nil {+ return err+ }+ return tx.Commit(ctx)+ }+ if w.Enabled && w.Kind != "event" && next.Valid && !next.Time.After(now) {+ planned := next.Time+ switch w.Kind {+ case "at":+ enabled = false+ next = pgtype.Timestamptz{}+ case "every":+ step := time.Duration(w.IntervalSeconds.Int64) * time.Second+ planned = planned.Add(now.Sub(planned) / step * step)+ next.Time = planned.Add(step)+ case "cron":+ next.Time, err = NextOccurrenceAfterUTC(w.CronExpression.String, w.Timezone, now)+ if err != nil {+ return err+ }+ if next.Time.IsZero() {+ enabled = false+ next.Valid = false+ }+ }+ payload, _ := json.Marshal(map[string]any{"planned_at": planned.UTC().Format(time.RFC3339), "kind": w.Kind})+ var latest db.IssueWakeupReceipt+ latest, err = q.RecordWakeupReceipt(ctx, db.RecordWakeupReceiptParams{ID: dbid.NewV7(), WakeupID: w.ID, Revision: w.Revision, EventKey: planned.UTC().Format(time.RFC3339Nano), EventType: "time.due", Payload: payload})+ if err == nil {+ _, err = tx.Exec(ctx, "DELETE FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND event_type='time.due' AND processed_at IS NULL AND id<>$2", w.ID, latest.ID)+ }+ if err != nil {+ return err+ }+ }+ task, err := q.FindPendingWakeupTask(ctx, util.UUIDToString(w.ID))+ if err == nil && task.Status == "dispatched" {+ // A claimed prompt is immutable. Recovery belongs to the ordinary+ // claim/prepare lease, not a second wakeup-specific task timeout.+ var waiting pgtype.Text+ if task.DispatchedAt.Valid && now.Sub(task.DispatchedAt.Time) >= claimResponseRecoveryWindow &&+ (!task.PrepareLeaseExpiresAt.Valid || !task.PrepareLeaseExpiresAt.Time.After(now)) {+ waiting = pgtype.Text{String: "Waiting for claimed run " + util.UUIDToString(task.ID) + " to start or recover; new trigger inputs are retained.", Valid: true}+ }+ // Persist timer progress even while waiting; do not regenerate each+ // elapsed tick. Keep once enabled until its pending input is assigned.+ if err := q.AdvanceIssueWakeup(ctx, db.AdvanceIssueWakeupParams{ID: w.ID, Enabled: w.Enabled, NextFireAt: next, LastError: waiting}); err != nil {+ return err+ }+ return tx.Commit(ctx)+ }+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {+ return err+ }+ taskExists := err == nil+ receipts, err := q.ListPendingWakeupReceipts(ctx, db.ListPendingWakeupReceiptsParams{WakeupID: w.ID, Revision: w.Revision})+ if err != nil {+ return err+ }+ if len(receipts) == 0 {+ return tx.Commit(ctx)+ }+ ids := make([]pgtype.UUID, 0, len(receipts))+ for _, r := range receipts {+ ids = append(ids, r.ID)+ }+ if w.Mode == "once" {+ enabled = false+ }+ note, evidence := mergeWakeupEvidence(w, task, receipts)+ if taskExists {+ task, err = q.ReplaceWakeupEvidence(ctx, db.ReplaceWakeupEvidenceParams{ID: task.ID, HandoffNote: pgtype.Text{String: note, Valid: true}, WakeupEvidence: evidence})+ } else {+ if err = guardIssueNotInTriage(ctx, q, issue.ID, OriginNamed); err != nil {+ return err+ }+ contextJSON, _ := json.Marshal(map[string]any{"wakeup_id": util.UUIDToString(w.ID), "wakeup_revision": w.Revision, "wakeup_evidence": evidence})+ task, err = q.CreateWakeupTask(ctx, db.CreateWakeupTaskParams{ID: dbid.NewV7(), AgentID: w.AgentID, RuntimeID: agent.RuntimeID, IssueID: w.IssueID, Priority: priorityToInt(issue.Priority), TriggerCommentID: w.ParentCommentID, TriggerSummary: pgtype.Text{String: "Wakeup: " + truncateForSummary(w.Instruction, 160), Valid: true}, HandoffNote: pgtype.Text{String: note, Valid: true}, OriginatorUserID: w.CreatedBy, AccountableUserID: w.CreatedBy, OriginatorSource: pgtype.Text{String: "trigger_owner", Valid: true}, TriggerEvidenceKind: pgtype.Text{String: "issue_wakeup", Valid: true}, TriggerEvidenceRefID: w.ID, DelegatedFromTaskID: w.SourceTaskID, WakeupContext: contextJSON, RuntimeMcpOverlay: overlay.Overlay, RuntimeConnectedApps: overlay.ConnectedApps})+ }+ if err != nil {+ return err+ }+ if err = q.ConsumeWakeupReceipts(ctx, db.ConsumeWakeupReceiptsParams{Ids: ids, TaskID: task.ID}); err != nil {+ return err+ }+ if err = q.AdvanceIssueWakeup(ctx, db.AdvanceIssueWakeupParams{ID: w.ID, Enabled: enabled, NextFireAt: next, LastTaskID: task.ID}); err != nil {+ return err+ }+ if err = tx.Commit(ctx); err != nil {+ return err+ }+ s.Tasks.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)+ s.Tasks.NotifyTaskEnqueued(ctx, task)+ return nil+}++func qCleanupMissingWakeup(ctx context.Context, tx pgx.Tx, id pgtype.UUID) error {+ if _, err := tx.Exec(ctx, "DELETE FROM issue_wakeup_receipt WHERE wakeup_id=$1", id); err != nil {+ return err+ }+ if _, err := tx.Exec(ctx, "DELETE FROM issue_wakeup WHERE id=$1", id); err != nil {+ return err+ }+ return tx.Commit(ctx)+}++// Disable withdraws only work not yet claimed. A running task keeps the+// ordinary Stop control; closing a subscription never kills unrelated work.+func (s *IssueWakeupService) Disable(ctx context.Context, issueID, id, member pgtype.UUID) (db.IssueWakeup, error) {+ var out db.IssueWakeup+ tx, err := s.Tasks.TxStarter.Begin(ctx)+ if err != nil {+ return out, err+ }+ defer tx.Rollback(ctx)+ q := s.Tasks.Queries.WithTx(tx)+ var workspace pgtype.UUID+ if err = tx.QueryRow(ctx, "SELECT w.id FROM workspace w JOIN issue i ON i.workspace_id=w.id WHERE i.id=$1 FOR KEY SHARE OF w", issueID).Scan(&workspace); err != nil {+ return out, err+ }+ issue, err := q.LockWakeupIssue(ctx, issueID)+ if err != nil {+ return out, err+ }+ membership, err := q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{UserID: member, WorkspaceID: issue.WorkspaceID})+ if err != nil {+ return out, ErrWakeupForbidden+ }+ out, err = q.LockIssueWakeup(ctx, id)+ if err != nil {+ return out, err+ }+ if out.IssueID != issue.ID || out.WorkspaceID != issue.WorkspaceID {+ return db.IssueWakeup{}, pgx.ErrNoRows+ }+ if out.CreatedBy != member && membership.Role != "owner" && membership.Role != "admin" {+ return db.IssueWakeup{}, ErrWakeupForbidden+ }+ _, err = tx.Exec(ctx, "UPDATE issue_wakeup SET enabled=false,disabled_at=COALESCE(disabled_at,now()),updated_at=now() WHERE id=$1", id)+ if err != nil {+ return out, err+ }+ if err = q.DiscardWakeupReceipts(ctx, id); err != nil {+ return out, err+ }+ tasks, err := q.CancelUnstartedWakeupTasks(ctx, util.UUIDToString(id))+ if err != nil {+ return out, err+ }+ out, err = q.LockIssueWakeup(ctx, id)+ if err != nil {+ return out, err+ }+ if err = tx.Commit(ctx); err != nil {+ return out, err+ }+ for _, task := range tasks {+ s.Tasks.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, task)+ }+ return out, nil+}++// CheckClaim revalidates stored human authority after an offline wait. The+// enqueue-time MCP overlay does not grant permission to execute forever.+func (s *IssueWakeupService) CheckClaim(ctx context.Context, task db.AgentTaskQueue) error {+ var source struct {+ ID string `json:"wakeup_id"`+ Revision int64 `json:"wakeup_revision"`+ }+ if err := json.Unmarshal(task.Context, &source); err != nil || source.ID == "" {+ return nil+ }+ id, err := wakeupUUID(source.ID)+ if err != nil {+ return ErrWakeupForbidden+ }+ w, err := s.Tasks.Queries.LocklessWakeup(ctx, id)+ if errors.Is(err, pgx.ErrNoRows) {+ return ErrWakeupForbidden+ }+ if err != nil {+ return err+ }+ if w.DisabledAt.Valid || w.Revision != source.Revision || w.IssueID != task.IssueID || w.AgentID != task.AgentID || w.CreatedBy != task.OriginatorUserID {+ return ErrWakeupForbidden+ }+ agent, err := s.Tasks.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: w.AgentID, WorkspaceID: w.WorkspaceID})+ if errors.Is(err, pgx.ErrNoRows) {+ return ErrWakeupForbidden+ }+ if err != nil {+ return err+ }+ return s.authorize(ctx, s.Tasks.Queries, w.WorkspaceID, w.CreatedBy, agent)+}diff --git a/server/internal/service/issue_wakeup_actor_test.go b/server/internal/service/issue_wakeup_actor_test.gonew file mode 100644index 0000000000..57939cd4f6--- /dev/null+++ b/server/internal/service/issue_wakeup_actor_test.go@@ -0,0 +1,176 @@+package service++import (+ "context"+ "errors"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestIssueWakeupMemberFilterPreservesOnceUntilMatchingComment(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ other := f.User(t, "monitored member", "[email protected]")+ f.Member(t, f.WorkspaceID, other, "member")+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"comment.created"}, FilterActorType: "member", FilterActorID: other, Instruction: "continue after member reply"})+ f.Comment(t, util.UUIDToString(issue), "another member")+ f.Exec(t, `INSERT INTO comment(issue_id,workspace_id,author_type,author_id,content,type) VALUES($1,$2,'agent',$3,'agent reply','comment')`, issue, f.WorkspaceID, agent)+ wakeDispatch(t, s, w)+ current, err := f.q.GetIssueWakeup(context.Background(), db.GetIssueWakeupParams{ID: w.ID, WorkspaceID: parseTestUUID(t, f.WorkspaceID)})+ if err != nil || !current.Enabled || current.LastTaskID.Valid {+ t.Fatalf("nonmatching input consumed once rule: %+v %v", current, err)+ }+ if got := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1", w.ID); got != 0 {+ t.Fatalf("nonmatching receipt: %d", got)+ }+ f.Exec(t, `INSERT INTO comment(issue_id,workspace_id,author_type,author_id,content,type) VALUES($1,$2,'member',$3,'requested reply','comment')`, issue, f.WorkspaceID, other)+ wakeDispatch(t, s, w)+ if got := f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'=$1", util.UUIDToString(w.ID)); got != 1 {+ t.Fatalf("matching comment did not enqueue: %d", got)+ }+ current, err = f.q.GetIssueWakeup(context.Background(), db.GetIssueWakeupParams{ID: w.ID, WorkspaceID: parseTestUUID(t, f.WorkspaceID)})+ if err != nil || current.Enabled {+ t.Fatal("one-shot did not finish")+ }+}++func TestIssueWakeupActorMatchesEditorNotOriginalAuthor(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ other := f.User(t, "editor", "[email protected]")+ f.Member(t, f.WorkspaceID, other, "member")+ comment := f.Comment(t, util.UUIDToString(issue), "original")+ makeRule := func(kind, id string) db.IssueWakeup {+ return wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.updated"}, FilterActorType: kind, FilterActorID: id, Instruction: "check edit"})+ }+ authorRule, editorRule, agentRule := makeRule("member", f.UserID), makeRule("member", other), makeRule("agent", agent)+ edit := func(kind, id, body string, commit bool) {+ t.Helper()+ ctx := context.Background()+ tx, err := f.Pool.Begin(ctx)+ if err != nil {+ t.Fatal(err)+ }+ defer tx.Rollback(ctx)+ if _, err = tx.Exec(ctx, "SELECT set_config('multica.actor_type',$1,true),set_config('multica.actor_id',$2,true)", kind, id); err != nil {+ t.Fatal(err)+ }+ if _, err = tx.Exec(ctx, "UPDATE comment SET content=$2 WHERE id=$1", comment, body); err != nil {+ t.Fatal(err)+ }+ if commit {+ if err = tx.Commit(ctx); err != nil {+ t.Fatal(err)+ }+ }+ }+ count := func(w db.IssueWakeup) int {+ return f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1", w.ID)+ }+ edit("member", other, "human edit", true)+ if count(authorRule) != 0 || count(editorRule) != 1 || count(agentRule) != 0 {+ t.Fatal("editor confused with original author")+ }+ edit("agent", agent, "agent edit", true)+ if count(authorRule) != 0 || count(editorRule) != 1 || count(agentRule) != 1 {+ t.Fatal("agent mutation did not match actor")+ }+ edit("member", f.UserID, "rolled back", false)+ if count(authorRule) != 0 {+ t.Fatal("rolled back edit captured")+ }+}++func TestIssueWakeupActorValidationAndWorkspaceScope(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ base := WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"comment.created"}, FilterActorType: "member", FilterActorID: f.UserID, Instruction: "check"}+ for _, change := range []func(*WakeupInput){+ func(in *WakeupInput) { in.FilterActorType = "system" }, func(in *WakeupInput) { in.FilterActorType = "" }, func(in *WakeupInput) { in.FilterActorID = "" },+ func(in *WakeupInput) { in.FilterAgentID = agent }, func(in *WakeupInput) { in.EventTypes = []string{"task.completed"} },+ func(in *WakeupInput) { in.Kind = "at"; in.EventTypes = nil; in.AfterSeconds = 60 },+ } {+ in := base+ change(&in)+ if _, err := s.Validate(&in, time.Now()); !errors.Is(err, ErrWakeupInput) {+ t.Fatalf("accepted invalid actor filter: %+v %v", in, err)+ }+ }+ foreign, _, _, foreignAgent := wakeFixture(t)+ for _, tc := range []struct {+ kind, id string+ want error+ }{{"member", foreign.UserID, ErrWakeupForbidden}, {"agent", foreignAgent, ErrWakeupForbidden}, {"member", "bad-id", ErrWakeupInput}} {+ in := base+ in.FilterActorType = tc.kind+ in.FilterActorID = tc.id+ if _, err := s.Create(context.Background(), issue, parseTestUUID(t, f.UserID), pgtype.UUID{}, in); !errors.Is(err, tc.want) {+ t.Fatalf("scope error %v, want %v", err, tc.want)+ }+ }+}++func TestIssueWakeupActorFilterSurvivesEnableAndExplicitReplacement(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ ctx := context.Background()+ owner := parseTestUUID(t, f.UserID)+ in := WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created"}, FilterActorType: "member", FilterActorID: f.UserID, Instruction: "check"}+ w := wakeCreate(t, f, s, issue, in)+ disabled, err := s.Disable(ctx, issue, w.ID, owner)+ if err != nil {+ t.Fatal(err)+ }+ enabled, err := s.Enable(ctx, issue, owner, pgtype.UUID{}, w.ID, WakeupEnableInput{Revision: disabled.Revision})+ if err != nil {+ t.Fatal(err)+ }+ if enabled.FilterActorType.String != "member" || enabled.FilterActorID != owner {+ t.Fatal("enable lost filter")+ }+ f.Comment(t, util.UUIDToString(issue), "matching old rule")+ in.FilterActorType = "agent"+ in.FilterActorID = agent+ replaced, err := s.Save(ctx, issue, owner, pgtype.UUID{}, w.ID, in)+ if err != nil {+ t.Fatal(err)+ }+ if replaced.FilterActorType.String != "agent" || replaced.Revision != enabled.Revision+1 {+ t.Fatal("replacement lost actor filter")+ }+ f.Comment(t, util.UUIDToString(issue), "no longer matching")+ if got := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND processed_at IS NULL", w.ID); got != 0 {+ t.Fatal("old rule input survived revision")+ }+ in.FilterActorType = ""+ in.FilterActorID = ""+ cleared, err := s.Save(ctx, issue, owner, pgtype.UUID{}, w.ID, in)+ if err != nil {+ t.Fatal(err)+ }+ if cleared.FilterActorType.Valid || cleared.FilterActorID.Valid {+ t.Fatal("explicit replacement could not clear filter")+ }+}++func TestIssueWakeupLegacyMutationAgentFilterNormalizes(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"comment.created"}, FilterAgentID: agent, Instruction: "wait"})+ if w.FilterAgentID.Valid || w.FilterActorType.String != "agent" || w.FilterActorID != parseTestUUID(t, agent) {+ t.Fatalf("legacy alias not normalized: %+v", w)+ }+ f.Comment(t, util.UUIDToString(issue), "human")+ if f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1", w.ID) != 0 {+ t.Fatal("human matched legacy agent alias")+ }+ f.Exec(t, `INSERT INTO comment(issue_id,workspace_id,author_type,author_id,content,type) VALUES($1,$2,'agent',$3,'agent reply','comment')`, issue, f.WorkspaceID, agent)+ wakeDispatch(t, s, w)+ if f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'=$1", util.UUIDToString(w.ID)) != 1 {+ t.Fatal("legacy alias did not wake on agent comment")+ }+ // Existing clients can still combine task and mutation types in one rule.+ in := WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"task.completed", "comment.created"}, FilterAgentID: agent, Instruction: "wait"}+ if _, err := s.Validate(&in, time.Now()); err != nil || in.FilterAgentID != agent || in.FilterActorType != "" {+ t.Fatalf("mixed legacy subscription changed: %+v %v", in, err)+ }+}diff --git a/server/internal/service/issue_wakeup_capacity_test.go b/server/internal/service/issue_wakeup_capacity_test.gonew file mode 100644index 0000000000..f753dea674--- /dev/null+++ b/server/internal/service/issue_wakeup_capacity_test.go@@ -0,0 +1,274 @@+package service++import (+ "context"+ "encoding/json"+ "errors"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgconn"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestIssueWakeupBusyRuleDoesNotBlockOtherWorkspace(t *testing.T) {+ for _, lock := range []string{"issue", "rule", "task", "workspace"} {+ t.Run(lock, func(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ other, _, otherIssue, otherAgent := wakeFixture(t)+ first := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created"}, Instruction: "first"})+ second := wakeCreate(t, other, s, otherIssue, WakeupInput{AgentID: otherAgent, Kind: "event", EventTypes: []string{"comment.created"}, Instruction: "second"})+ f.Comment(t, util.UUIDToString(issue), "first")+ wakeDispatch(t, s, first)+ f.Comment(t, util.UUIDToString(issue), "more")+ other.Comment(t, util.UUIDToString(otherIssue), "other workspace")+ f.Exec(t, "UPDATE issue_wakeup SET updated_at=now()-interval '1 day' WHERE id=$1", first.ID)+ holder, err := f.Pool.Begin(context.Background())+ if err != nil {+ t.Fatal(err)+ }+ defer holder.Rollback(context.Background())+ var sql string+ var key any+ switch lock {+ case "issue":+ sql, key = "SELECT id FROM issue WHERE id=$1 FOR NO KEY UPDATE", issue+ case "rule":+ sql, key = "SELECT id FROM issue_wakeup WHERE id=$1 FOR UPDATE", first.ID+ case "task":+ task, err := f.q.FindPendingWakeupTask(context.Background(), util.UUIDToString(first.ID))+ if err != nil {+ t.Fatal(err)+ }+ sql, key = "SELECT id FROM agent_task_queue WHERE id=$1 FOR UPDATE", task.ID+ case "workspace":+ sql, key = "SELECT id FROM workspace WHERE id=$1 FOR UPDATE", f.WorkspaceID+ }+ if _, err = holder.Exec(context.Background(), sql, key); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)+ defer cancel()+ if err = s.Tick(ctx); err == nil {+ t.Fatal("expected busy-rule diagnostic")+ }+ if ctx.Err() != nil {+ t.Fatal("busy rule consumed batch deadline")+ }+ if got := other.Count(t, "SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'=$1", util.UUIDToString(second.ID)); got != 1 {+ t.Fatalf("unrelated rule not dispatched: %d", got)+ }+ if got := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND processed_at IS NULL", first.ID); got != 1 {+ t.Fatalf("busy rule lost pending evidence: %d", got)+ }+ })+ }+}++func TestIssueWakeupPendingEventsAreBoundedAndLegacyInputsDrain(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created"}, Instruction: "read all new comments"})+ // Old servers' receipts have no coalesce key and remain readable.+ f.Exec(t, `INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload) VALUES(gen_random_uuid(),$1,1,'legacy','comment.created','{"comment_id":"legacy-reference"}')`, w.ID)+ var wg sync.WaitGroup+ errs := make(chan error, 80)+ for n := 0; n < 80; n++ {+ wg.Add(1)+ go func() {+ defer wg.Done()+ _, err := f.Pool.Exec(context.Background(), `INSERT INTO comment(issue_id,workspace_id,author_type,author_id,content,type) VALUES($1,$2,'member',$3,'burst','comment')`, issue, f.WorkspaceID, f.UserID)+ errs <- err+ }()+ }+ wg.Wait()+ close(errs)+ for err := range errs {+ if err != nil {+ t.Fatal(err)+ }+ }+ last := f.Comment(t, util.UUIDToString(issue), "latest")+ if got := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND processed_at IS NULL", w.ID); got != 2 {+ t.Fatalf("unbounded pending receipts: %d", got)+ }+ var payload []byte+ if err := f.Pool.QueryRow(context.Background(), "SELECT payload FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND coalesce_key IS NOT NULL", w.ID).Scan(&payload); err != nil {+ t.Fatal(err)+ }+ var fact struct {+ Count int `json:"coalesced_count"`+ Comment string `json:"comment_id"`+ First string `json:"first_occurred_at"`+ }+ if err := json.Unmarshal(payload, &fact); err != nil {+ t.Fatal(err)+ }+ if fact.Count != 81 || fact.Comment != last || fact.First == "" {+ t.Fatalf("lost burst summary: %s", payload)+ }+ wakeDispatch(t, s, w)+ task, err := f.q.FindPendingWakeupTask(context.Background(), util.UUIDToString(w.ID))+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(task.HandoffNote.String, last) || !strings.Contains(task.HandoffNote.String, "legacy-reference") || !strings.Contains(task.HandoffNote.String, wakeupOmittedEvidence) {+ t.Fatal("missing evidence or state-read instruction")+ }+ f.Comment(t, util.UUIDToString(issue), "after consumption")+ if got := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND processed_at IS NULL", w.ID); got != 1 {+ t.Fatalf("new input after consumption lost: %d", got)+ }+}++func TestIssueWakeupCaptureRacingConsumptionKeepsNewInput(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created"}, Instruction: "check"})+ f.Comment(t, util.UUIDToString(issue), "first")+ ctx := context.Background()+ tx, err := f.Pool.Begin(ctx)+ if err != nil {+ t.Fatal(err)+ }+ defer tx.Rollback(ctx)+ q := f.q.WithTx(tx)+ receipts, err := q.ListPendingWakeupReceipts(ctx, db.ListPendingWakeupReceiptsParams{WakeupID: w.ID, Revision: w.Revision})+ if err != nil {+ t.Fatal(err)+ }+ writerCtx, cancel := context.WithTimeout(ctx, 3*time.Second)+ defer cancel()+ done := make(chan error, 1)+ go func() {+ _, err := f.Pool.Exec(writerCtx, `INSERT INTO comment(issue_id,workspace_id,author_type,author_id,content,type) VALUES($1,$2,'member',$3,'racing','comment')`, issue, f.WorkspaceID, f.UserID)+ done <- err+ }()+ // A bounded wait proves capture cannot update evidence after dispatch read it.+ select {+ case err := <-done:+ t.Fatalf("writer bypassed receipt lock: %v", err)+ case <-time.After(50 * time.Millisecond):+ }+ if err = q.ConsumeWakeupReceipts(ctx, db.ConsumeWakeupReceiptsParams{Ids: []pgtype.UUID{receipts[0].ID}}); err != nil {+ t.Fatal(err)+ }+ if err = tx.Commit(ctx); err != nil {+ t.Fatal(err)+ }+ if err = <-done; err != nil {+ t.Fatal(err)+ }+ if got := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND processed_at IS NULL", w.ID); got != 1 {+ t.Fatalf("racing input lost: %d", got)+ }+}++func TestIssueWakeupReceiptExpiryIsBoundedAndKeepsPending(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"comment.created"}, Instruction: "check"})+ f.Exec(t, `INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload,created_at,processed_at)+ SELECT gen_random_uuid(),$1,1,n::text,'comment.created','{}',now()-interval '10 days',now()-interval '8 days' FROM generate_series(1,1050) n`, w.ID)+ f.Exec(t, `INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload,created_at,processed_at)+ VALUES(gen_random_uuid(),$1,1,'pending','comment.created','{}',now()-interval '10 days',NULL),+ (gen_random_uuid(),$1,1,'recent','comment.created','{}',now()-interval '10 days',now())`, w.ID)+ removed, err := f.q.DeleteExpiredWakeupReceipts(context.Background(), pgtype.Timestamptz{Time: time.Now().Add(-7 * 24 * time.Hour), Valid: true})+ if err != nil {+ t.Fatal(err)+ }+ if removed != 1000 {+ t.Fatalf("cleanup not bounded: %d", removed)+ }+ if got := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND event_key IN ('pending','recent')", w.ID); got != 2 {+ t.Fatal("expired pending input or recent dedup key")+ }+}++func TestIssueWakeupActivationCapacityAndReenable(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ in := WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"comment.created"}, Instruction: "check"}+ var first db.IssueWakeup+ for n := 0; n < 32; n++ {+ w := wakeCreate(t, f, s, issue, in)+ if n == 0 {+ first = w+ }+ }+ _, err := s.Create(context.Background(), issue, parseTestUUID(t, f.UserID), pgtype.UUID{}, in)+ var pgErr *pgconn.PgError+ if !errors.As(err, &pgErr) || pgErr.ConstraintName != "issue_wakeup_active_limit" {+ t.Fatalf("capacity not enforced: %v", err)+ }+ disabled, err := s.Disable(context.Background(), issue, first.ID, parseTestUUID(t, f.UserID))+ if err != nil {+ t.Fatal(err)+ }+ wakeCreate(t, f, s, issue, in)+ _, err = s.Enable(context.Background(), issue, parseTestUUID(t, f.UserID), pgtype.UUID{}, first.ID, WakeupEnableInput{Revision: disabled.Revision})+ if !errors.As(err, &pgErr) || pgErr.ConstraintName != "issue_wakeup_active_limit" {+ t.Fatalf("re-enable bypassed capacity: %v", err)+ }+}++func TestIssueWakeupWorkspaceCapacitySerializesDifferentIssues(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ f.Cleanup(t, "DELETE FROM issue_wakeup WHERE workspace_id=$1", f.WorkspaceID)+ issues := []pgtype.UUID{issue}+ for n := 0; n < 33; n++ {+ issues = append(issues, parseTestUUID(t, f.Issue(t, "capacity issue")))+ }+ f.Exec(t, `INSERT INTO issue_wakeup(id,workspace_id,issue_id,agent_id,created_by,instruction,kind,mode)+ SELECT gen_random_uuid(),$1,($2::uuid[])[1+(n%34)],$3,$4,'check','event','continuous' FROM generate_series(1,999) n`, f.WorkspaceID, issues, agent, f.UserID)+ errs := make(chan error, 2)+ for _, id := range issues[:2] {+ go func(id pgtype.UUID) {+ _, err := s.Create(context.Background(), id, parseTestUUID(t, f.UserID), pgtype.UUID{}, WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"comment.created"}, Instruction: "check"})+ errs <- err+ }(id)+ }+ var ok, full int+ for n := 0; n < 2; n++ {+ err := <-errs+ var pgErr *pgconn.PgError+ if err == nil {+ ok+++ } else if errors.As(err, &pgErr) && pgErr.ConstraintName == "issue_wakeup_active_limit" {+ full+++ } else {+ t.Fatal(err)+ }+ }+ if ok != 1 || full != 1 {+ t.Fatalf("workspace capacity race: success=%d full=%d", ok, full)+ }+}++// Older consumers do not lock the receipt before building a prompt. A merged+// input must survive their later UPDATE by the original receipt ID.+func TestIssueWakeupLegacyConsumerCannotConsumeUnseenMerge(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created"}, Instruction: "check"})+ f.Comment(t, util.UUIDToString(issue), "first")+ ctx := context.Background()+ var observed pgtype.UUID+ if err := f.Pool.QueryRow(ctx, "SELECT id FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND processed_at IS NULL", w.ID).Scan(&observed); err != nil {+ t.Fatal(err)+ }+ latest := f.Comment(t, util.UUIDToString(issue), "arrived after old consumer read")+ if err := f.q.ConsumeWakeupReceipts(ctx, db.ConsumeWakeupReceiptsParams{Ids: []pgtype.UUID{observed}}); err != nil {+ t.Fatal(err)+ }+ if got := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND processed_at IS NULL AND payload->>'comment_id'=$2", w.ID, latest); got != 1 {+ t.Fatalf("old consumer lost new evidence: %d", got)+ }+ wakeDispatch(t, s, w)+ task, err := f.q.FindPendingWakeupTask(ctx, util.UUIDToString(w.ID))+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(task.HandoffNote.String, latest) {+ t.Fatal("new dispatcher lost merged reference")+ }+}diff --git a/server/internal/service/issue_wakeup_collaboration_test.go b/server/internal/service/issue_wakeup_collaboration_test.gonew file mode 100644index 0000000000..e3b32a7e3f--- /dev/null+++ b/server/internal/service/issue_wakeup_collaboration_test.go@@ -0,0 +1,203 @@+package service++import (+ "context"+ "encoding/json"+ "errors"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util"+ "github.com/multica-ai/multica/server/pkg/eventcontract"+)++// Exercise real writes rather than calling the capture function: every advertised+// event must be reachable from the persisted collaboration state.+func TestIssueWakeupCollaborationCapture(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: eventcontract.WakeupTypes, Instruction: "Read current state"})+ count := func(event string) int {+ return f.Count(t, "SELECT COALESCE(sum(COALESCE((payload->>'coalesced_count')::int,1)),0) FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND event_type=$2", w.ID, event)+ }+ assert := func(event string, n int) {+ t.Helper()+ if got := count(event); got != n {+ t.Fatalf("%s: got %d captured facts, want %d", event, got, n)+ }+ }+ run := f.Task(t, agent, testutil.Cols{"issue_id": issue, "runtime_id": testutil.Raw("(SELECT runtime_id FROM agent WHERE id='" + agent + "')")})+ assert("task.queued", 1)+ for _, status := range []string{"dispatched", "running", "deferred", "queued", "deferred", "waiting_local_directory", "completed", "failed", "cancelled"} {+ f.Exec(t, "UPDATE agent_task_queue SET status=$2 WHERE id=$1", run, status)+ }+ assert("task.queued", 2)+ assert("task.deferred", 2)+ f.Exec(t, "UPDATE agent_task_queue SET status=status WHERE id=$1", run)+ assert("task.cancelled", 1)+ parent := f.Issue(t, "parent")+ project := f.Project(t, "project")+ f.Exec(t, "UPDATE issue SET title='changed',status='in_progress',assignee_type='agent',assignee_id=$2,parent_issue_id=$3,project_id=$4,properties='{\"priority-note\":\"private-value\"}',metadata='{\"build\":\"private-value\"}' WHERE id=$1", issue, agent, parent, project)+ assert("issue.updated", 1)+ f.Exec(t, "UPDATE issue SET title=title,revision=revision+1,updated_at=now() WHERE id=$1", issue)+ assert("issue.updated", 1)+ label := f.Insert(t, "issue_label", testutil.Cols{"workspace_id": f.WorkspaceID, "name": "review", "color": "red"})+ f.InsertNoID(t, "issue_to_label", testutil.Cols{"issue_id": issue, "label_id": label}, "issue_id=$1 AND label_id=$2", issue, label)+ f.Exec(t, "DELETE FROM issue_to_label WHERE issue_id=$1 AND label_id=$2", issue, label)+ assert("issue.labels_changed", 2)+ comment := f.Comment(t, util.UUIDToString(issue), "private-comment")+ f.Exec(t, "UPDATE comment SET content='private-edited-comment' WHERE id=$1", comment)+ f.Exec(t, "UPDATE comment SET resolved_at=now(),resolved_by_type='member',resolved_by_id=$2 WHERE id=$1", comment, f.UserID)+ f.Exec(t, "UPDATE comment SET resolved_at=NULL,resolved_by_type=NULL,resolved_by_id=NULL WHERE id=$1", comment)+ for _, target := range []struct{ table, key, id string }{{"comment_reaction", "comment_id", comment}, {"issue_reaction", "issue_id", util.UUIDToString(issue)}} {+ reaction := f.Insert(t, target.table, testutil.Cols{target.key: target.id, "workspace_id": f.WorkspaceID, "actor_type": "member", "actor_id": f.UserID, "emoji": "👍"})+ f.Exec(t, "DELETE FROM "+target.table+" WHERE id=$1", reaction)+ }+ assert("reaction.added", 2)+ assert("reaction.removed", 2)+ attachment := f.Insert(t, "attachment", testutil.Cols{"workspace_id": f.WorkspaceID, "uploader_type": "member", "uploader_id": f.UserID, "filename": "secret.txt", "url": "https://private.invalid/secret", "content_type": "text/plain", "size_bytes": 1})+ assert("attachment.attached", 0) // upload without an owner is not attachment+ f.Exec(t, "UPDATE attachment SET issue_id=$2 WHERE id=$1", attachment, issue)+ f.Exec(t, "UPDATE attachment SET issue_id=NULL,comment_id=$2 WHERE id=$1", attachment, comment)+ f.Exec(t, "DELETE FROM attachment WHERE id=$1", attachment)+ assert("attachment.attached", 2)+ assert("attachment.detached", 2)+ f.Exec(t, "UPDATE comment SET deleted_at=now() WHERE id=$1", comment)+ f.Exec(t, "DELETE FROM comment WHERE id=$1", comment)+ assert("comment.deleted", 1) // tombstone cleanup is not another deletion+ for _, event := range eventcontract.WakeupTypes {+ if count(event) == 0 {+ t.Errorf("advertised event %s has no captured fact", event)+ }+ }+ rows, err := f.Pool.Query(context.Background(), "SELECT payload FROM issue_wakeup_receipt WHERE wakeup_id=$1", w.ID)+ if err != nil {+ t.Fatal(err)+ }+ defer rows.Close()+ for rows.Next() {+ var raw []byte+ if err := rows.Scan(&raw); err != nil {+ t.Fatal(err)+ }+ var payload map[string]any+ if err := json.Unmarshal(raw, &payload); err != nil {+ t.Fatal(err)+ }+ for _, field := range []string{"event_id", "event_type", "version", "occurred_at", "workspace_id", "issue_id", "actor_type"} {+ if payload[field] == nil {+ t.Errorf("missing %s: %s", field, raw)+ }+ }+ if strings.Contains(string(raw), "private-") || strings.Contains(string(raw), "secret") {+ t.Fatalf("private content in payload: %s", raw)+ }+ }+ if err := rows.Err(); err != nil {+ t.Fatal(err)+ }+ wakeDispatch(t, s, w)+ if n := f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'=$1", util.UUIDToString(w.ID)); n != 1 {+ t.Fatalf("expected coalesced run, got %d", n)+ }+}++func TestIssueWakeupNonterminalSubscriptionIsProspective(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ run := f.Task(t, agent, testutil.Cols{"issue_id": issue, "runtime_id": testutil.Raw("(SELECT runtime_id FROM agent WHERE id='" + agent + "')")})+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"task.queued"}, FilterTaskID: run, Instruction: "inspect new queue input"})+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1", w.ID); n != 0 {+ t.Fatal("registration replayed nonterminal current state")+ }+ f.Exec(t, "UPDATE agent_task_queue SET status='deferred' WHERE id=$1", run)+ f.Exec(t, "UPDATE agent_task_queue SET status='queued' WHERE id=$1", run)+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1", w.ID); n != 1 {+ t.Fatalf("missed future queue transition: %d", n)+ }+ for _, event := range []string{"issue.created", "issue.deleted"} {+ _, err := s.Create(context.Background(), issue, parseTestUUID(t, f.UserID), parseTestUUID(t, run), WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{event}, Instruction: "invalid self subscription"})+ if !errors.Is(err, ErrWakeupInput) || !strings.Contains(err.Error(), "cannot wake its own issue") {+ t.Fatalf("lifecycle scope rejection: %v", err)+ }+ }+}++func TestIssueWakeupReplyUnresolveKeepsSource(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ parent := f.Comment(t, util.UUIDToString(issue), "resolved thread", testutil.Cols{"resolved_at": testutil.Raw("now()"), "resolved_by_type": "member", "resolved_by_id": f.UserID})+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.unresolved"}, Instruction: "inspect reply"})+ run := f.Task(t, agent, testutil.Cols{"issue_id": issue, "runtime_id": testutil.Raw("(SELECT runtime_id FROM agent WHERE id='" + agent + "')")})+ f.Cleanup(t, "DELETE FROM comment WHERE source_task_id=$1", run)+ f.Exec(t, "UPDATE agent_task_queue SET context=jsonb_build_object('wakeup_id',$2::text) WHERE id=$1", run, util.UUIDToString(w.ID))+ s.Tasks.createAgentComment(context.Background(), issue, parseTestUUID(t, agent), "own reply", "comment", parseTestUUID(t, parent), parseTestUUID(t, run))+ if n := f.Count(t, "SELECT count(*) FROM comment WHERE id=$1 AND resolved_at IS NULL", parent); n != 1 {+ t.Fatal("reply did not reopen thread")+ }+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1", w.ID); n != 0 {+ t.Fatal("automatic unresolve caused self-loop")+ }+ f.Exec(t, "UPDATE agent_task_queue SET context='{}' WHERE id=$1", run)+ f.Exec(t, "UPDATE comment SET resolved_at=now(),resolved_by_type='member',resolved_by_id=$2 WHERE id=$1", parent, f.UserID)+ s.Tasks.createAgentComment(context.Background(), issue, parseTestUUID(t, agent), "external reply", "comment", parseTestUUID(t, parent), parseTestUUID(t, run))+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND payload->>'source_task_id'=$2", w.ID, run); n != 1 {+ t.Fatalf("external reply not attributed: %d", n)+ }+}++func TestIssueWakeupCollaborationTransactionAndActor(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ comment := f.Comment(t, util.UUIDToString(issue), "original", testutil.Cols{"author_type": "agent", "author_id": agent})+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.updated", "issue.metadata_changed"}, FilterAgentID: agent, Instruction: "inspect"})+ run := f.Task(t, agent, testutil.Cols{"issue_id": issue, "runtime_id": testutil.Raw("(SELECT runtime_id FROM agent WHERE id='" + agent + "')")})+ ctx := context.Background()+ write := func(commit, own bool) {+ t.Helper()+ tx, err := f.Pool.Begin(ctx)+ if err != nil {+ t.Fatal(err)+ }+ defer tx.Rollback(ctx)+ if _, err = tx.Exec(ctx, "SELECT set_config('multica.source_task_id',$1,true),set_config('multica.actor_type','agent',true),set_config('multica.actor_id',$2,true)", run, agent); err != nil {+ t.Fatal(err)+ }+ if own {+ if _, err = tx.Exec(ctx, "UPDATE agent_task_queue SET context=jsonb_build_object('wakeup_id',$2::text) WHERE id=$1", run, util.UUIDToString(w.ID)); err != nil {+ t.Fatal(err)+ }+ }+ if _, err = tx.Exec(ctx, "UPDATE comment SET content=content||'!' WHERE id=$1", comment); err != nil {+ t.Fatal(err)+ }+ if _, err = tx.Exec(ctx, "UPDATE issue SET metadata=jsonb_build_object('changed',gen_random_uuid()) WHERE id=$1", issue); err != nil {+ t.Fatal(err)+ }+ if commit {+ if err := tx.Commit(ctx); err != nil {+ t.Fatal(err)+ }+ }+ }+ count := func() int { return f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1", w.ID) }+ write(false, false)+ if count() != 0 {+ t.Fatal("rollback left receipts")+ }+ // The original author is not the actor of a later edit.+ f.Exec(t, "UPDATE comment SET content='system edit' WHERE id=$1", comment)+ if count() != 0 {+ t.Fatal("edit inherited original agent author")+ }+ write(true, false)+ if count() != 2 {+ t.Fatalf("trusted agent edits missing: %d", count())+ }+ write(true, true)+ if count() != 2 {+ t.Fatal("own wakeup edits caused a self-loop")+ }+ // Transaction-local identity must not leak to the next borrower.+ f.Exec(t, "UPDATE comment SET content='later system edit' WHERE id=$1", comment)+ if count() != 2 {+ t.Fatal("source identity leaked")+ }+}diff --git a/server/internal/service/issue_wakeup_enable_test.go b/server/internal/service/issue_wakeup_enable_test.gonew file mode 100644index 0000000000..95c3347412--- /dev/null+++ b/server/internal/service/issue_wakeup_enable_test.go@@ -0,0 +1,126 @@+package service++import (+ "context"+ "errors"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestIssueWakeupEnablePreservesConfigAndFencesReplay(t *testing.T) {+ for _, kind := range []string{"event", "at", "every", "cron"} {+ t.Run(kind, func(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ ctx := context.Background()+ owner := parseTestUUID(t, f.UserID)+ parent := f.Comment(t, util.UUIDToString(issue), "delivery thread")+ in := WakeupInput{AgentID: agent, Kind: kind, Instruction: "keep my instruction", ParentCommentID: parent, Timezone: "Asia/Shanghai"}+ switch kind {+ case "event":+ in.EventTypes = []string{"task.completed"}+ in.FilterAgentID = agent+ case "at":+ in.AfterSeconds = 3600+ case "every":+ in.IntervalSeconds = 3600+ case "cron":+ in.CronExpression = "0 * * * *"+ }+ w := wakeCreate(t, f, s, issue, in)+ if _, err := s.Disable(ctx, issue, w.ID, owner); err != nil {+ t.Fatal(err)+ }+ // Missed recurring periods must not generate catch-up runs on enable.+ if kind == "every" || kind == "cron" {+ f.Exec(t, "UPDATE issue_wakeup SET next_fire_at=now()-interval '3 hours' WHERE id=$1", w.ID)+ }+ restored, err := s.Enable(ctx, issue, owner, pgtype.UUID{}, w.ID, WakeupEnableInput{Revision: w.Revision})+ if err != nil {+ t.Fatal(err)+ }+ if !restored.Enabled || restored.DisabledAt.Valid || restored.Revision != w.Revision+1 || restored.Instruction != w.Instruction || restored.ParentCommentID != w.ParentCommentID || restored.FilterAgentID != w.FilterAgentID || restored.Timezone != w.Timezone {+ t.Fatalf("changed configuration: %+v", restored)+ }+ if kind != "event" && !restored.NextFireAt.Time.After(time.Now()) {+ t.Fatal("restored timer catches up in the past")+ }+ if _, err = s.Enable(ctx, issue, owner, pgtype.UUID{}, w.ID, WakeupEnableInput{Revision: w.Revision}); !errors.Is(err, ErrWakeupConflict) {+ t.Fatalf("stale enable accepted: %v", err)+ }+ // Already-on toggle with current revision is an idempotent read.+ same, err := s.Enable(ctx, issue, owner, pgtype.UUID{}, w.ID, WakeupEnableInput{Revision: restored.Revision})+ if err != nil || same.Revision != restored.Revision || same.NextFireAt != restored.NextFireAt {+ t.Fatalf("duplicate toggled schedule: %v", err)+ }+ })+ }+}++func TestIssueWakeupEnableOneShotRequiresExplicitFutureRearm(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ ctx := context.Background()+ owner := parseTestUUID(t, f.UserID)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "at", AfterSeconds: 600, Instruction: "check"})+ if _, err := s.Disable(ctx, issue, w.ID, owner); err != nil {+ t.Fatal(err)+ }+ f.Exec(t, "UPDATE issue_wakeup SET next_fire_at=now()-interval '1 minute' WHERE id=$1", w.ID)+ if _, err := s.Enable(ctx, issue, owner, pgtype.UUID{}, w.ID, WakeupEnableInput{Revision: w.Revision}); !errors.Is(err, ErrWakeupInput) {+ t.Fatalf("expired toggle accepted: %v", err)+ }+ future := time.Now().Add(time.Hour)+ restored, err := s.Enable(ctx, issue, owner, pgtype.UUID{}, w.ID, WakeupEnableInput{Revision: w.Revision, At: &future, Rearm: true})+ if err != nil {+ t.Fatal(err)+ }+ f.Exec(t, "UPDATE issue_wakeup SET next_fire_at=now()-interval '1 second' WHERE id=$1", w.ID)+ wakeDispatch(t, s, restored)+ if _, err = s.Enable(ctx, issue, owner, pgtype.UUID{}, w.ID, WakeupEnableInput{Revision: restored.Revision, At: &future}); !errors.Is(err, ErrWakeupInput) {+ t.Fatalf("consumed toggle accepted: %v", err)+ }+ if _, err = s.Enable(ctx, issue, owner, pgtype.UUID{}, w.ID, WakeupEnableInput{Revision: restored.Revision, At: &future, Rearm: true}); !errors.Is(err, ErrWakeupConflict) {+ t.Fatalf("active run rearmed: %v", err)+ }+ if _, err = s.Disable(ctx, issue, w.ID, owner); err != nil {+ t.Fatal(err)+ }+ if _, err = s.Enable(ctx, issue, owner, pgtype.UUID{}, w.ID, WakeupEnableInput{Revision: restored.Revision, At: &future, Rearm: true}); err != nil {+ t.Fatal(err)+ }+}++func TestIssueWakeupEnableChecksScopeAuthorityAndClosedState(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ ctx := context.Background()+ owner := parseTestUUID(t, f.UserID)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"task.completed"}, Instruction: "check"})+ if _, err := s.Disable(ctx, issue, w.ID, owner); err != nil {+ t.Fatal(err)+ }+ input := WakeupEnableInput{Revision: w.Revision}+ outsider := parseTestUUID(t, f.member(t, "enable-outsider"))+ if _, err := s.Enable(ctx, issue, outsider, pgtype.UUID{}, w.ID, input); !errors.Is(err, ErrWakeupForbidden) {+ t.Fatalf("borrowed permission: %v", err)+ }+ other := parseTestUUID(t, f.Issue(t, "other"))+ if _, err := s.Enable(ctx, other, owner, pgtype.UUID{}, w.ID, input); !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("wrong scope: %v", err)+ }+ f.Exec(t, "UPDATE issue SET status='done' WHERE id=$1", issue)+ if _, err := s.Enable(ctx, issue, owner, pgtype.UUID{}, w.ID, input); !errors.Is(err, ErrWakeupInput) {+ t.Fatalf("closed enable: %v", err)+ }+ f.Exec(t, "UPDATE issue SET status='todo' WHERE id=$1", issue)+ current, err := f.q.GetIssueWakeup(ctx, db.GetIssueWakeupParams{ID: w.ID, WorkspaceID: w.WorkspaceID})+ if err != nil || current.Enabled {+ t.Fatal("reopen automatically enabled")+ }+ if _, err = s.Enable(ctx, issue, owner, pgtype.UUID{}, w.ID, input); err != nil {+ t.Fatal(err)+ }+}diff --git a/server/internal/service/issue_wakeup_evidence.go b/server/internal/service/issue_wakeup_evidence.gonew file mode 100644index 0000000000..b52455e7b7--- /dev/null+++ b/server/internal/service/issue_wakeup_evidence.go@@ -0,0 +1,135 @@+package service++import (+ "bytes"+ "encoding/json"+ "fmt"+ "strings"++ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Retain the existing 40KB prompt budget, including the <=12KB instruction.+// Consumed notifications stay linked to the task during the retention window.+const wakeupNoteLimit = 40000+const wakeupLegacyHeading = "Previous wakeup context (historical; follow the current instruction above):\n"+const wakeupOmittedEvidence = "Some trigger details were omitted to keep this prompt bounded. Read current issue comments, runs and state before deciding what to do.\n"++// Keep facts as data in task.context; handoff_note is only a rendering.+// Legacy notes remain opaque during mixed-version operation, never parsed.+type wakeupEvidence struct {+ Version int `json:"version"`+ Instruction string `json:"instruction,omitempty"`+ Facts []wakeupFact `json:"facts,omitempty"`+ Legacy string `json:"legacy,omitempty"`+ Omitted bool `json:"omitted,omitempty"`+}+type wakeupFact struct {+ EventType string `json:"event_type"`+ Payload json.RawMessage `json:"payload"`+}++func mergeWakeupEvidence(w db.IssueWakeup, previous db.AgentTaskQueue, receipts []db.IssueWakeupReceipt) (string, json.RawMessage) {+ var stored struct {+ Evidence wakeupEvidence `json:"wakeup_evidence"`+ }+ _ = json.Unmarshal(previous.Context, &stored)+ evidence := stored.Evidence+ // jsonb can reorder object keys/spacing; normalize before rendering.+ for i := range evidence.Facts {+ evidence.Facts[i].Payload = canonicalWakeupPayload(evidence.Facts[i].Payload)+ }+ previousConfig := w+ if evidence.Instruction != "" {+ previousConfig.Instruction = evidence.Instruction+ }+ if evidence.Version != 1 || renderWakeupEvidence(previousConfig, evidence) != previous.HandoffNote.String {+ // An old dispatcher may have updated only handoff_note. Preserve its text+ // as one bounded legacy item instead of trusting a stale structured summary.+ evidence = wakeupEvidence{Version: 1, Legacy: previous.HandoffNote.String}+ }+ if w.Kind != "event" {+ evidence = wakeupEvidence{Version: 1}+ }++ header := "Wakeup " + util.UUIDToString(w.ID) + " triggered. Instruction:\n" + w.Instruction + "\nTrigger facts (read current state before deciding what to do):\n"+ budget := wakeupNoteLimit - len(header) - len(wakeupOmittedEvidence) - len(wakeupLegacyHeading)+ budget = max(budget, 0)+ total := len(evidence.Legacy)+ for _, fact := range evidence.Facts {+ total += len(fact.EventType) + len(fact.Payload) + 2+ }+ trim := func() {+ if total > budget && evidence.Legacy != "" {+ total -= len(evidence.Legacy)+ evidence.Legacy = ""+ evidence.Omitted = true+ }+ for total > budget && len(evidence.Facts) > 0 {+ fact := evidence.Facts[0]+ total -= len(fact.EventType) + len(fact.Payload) + 2+ evidence.Facts = evidence.Facts[1:]+ evidence.Omitted = true+ }+ }+ trim()+ for _, r := range receipts {+ var summary struct {+ Count int64 `json:"coalesced_count"`+ }+ _ = json.Unmarshal(r.Payload, &summary)+ if summary.Count > 1 {+ evidence.Omitted = true+ }+ payload := canonicalWakeupPayload(r.Payload)+ if len(r.EventType)+len(payload)+2 > budget {+ // Keep references as data even when a changed-field list is oversized.+ var fields map[string]json.RawMessage+ _ = json.Unmarshal(payload, &fields)+ refs := map[string]json.RawMessage{}+ for _, key := range []string{"event_id", "occurred_at", "first_occurred_at", "coalesced_count", "task_id", "source_task_id", "comment_id", "thread_id", "attachment_id", "agent_id", "actor_type", "actor_id"} {+ if value := fields[key]; len(value) > 0 && len(value) <= 256 {+ refs[key] = value+ }+ }+ refs["receipt_id"], _ = json.Marshal(util.UUIDToString(r.ID))+ payload, _ = json.Marshal(refs)+ evidence.Omitted = true+ }+ evidence.Facts = append(evidence.Facts, wakeupFact{EventType: r.EventType, Payload: payload})+ total += len(r.EventType) + len(payload) + 2+ trim()+ }+ evidence.Instruction = w.Instruction+ raw, _ := json.Marshal(evidence)+ return renderWakeupEvidence(w, evidence), raw+}++func renderWakeupEvidence(w db.IssueWakeup, evidence wakeupEvidence) string {+ header := "Wakeup " + util.UUIDToString(w.ID) + " triggered. Instruction:\n" + w.Instruction + "\nTrigger facts (read current state before deciding what to do):\n"+ if evidence.Omitted {+ header += wakeupOmittedEvidence+ }+ var b strings.Builder+ b.WriteString(header)+ if evidence.Legacy != "" {+ b.WriteString(wakeupLegacyHeading)+ b.WriteString(evidence.Legacy)+ }+ for _, fact := range evidence.Facts {+ fmt.Fprintf(&b, "%s %s\n", fact.EventType, fact.Payload)+ }+ return b.String()+}++func canonicalWakeupPayload(raw json.RawMessage) json.RawMessage {+ var value any+ decoder := json.NewDecoder(bytes.NewReader(raw))+ decoder.UseNumber()+ if decoder.Decode(&value) != nil {+ return json.RawMessage(`{}`)+ }+ result, _ := json.Marshal(value)+ return result+}diff --git a/server/internal/service/issue_wakeup_evidence_test.go b/server/internal/service/issue_wakeup_evidence_test.gonew file mode 100644index 0000000000..7892de8a9a--- /dev/null+++ b/server/internal/service/issue_wakeup_evidence_test.go@@ -0,0 +1,93 @@+package service++import (+ "encoding/json"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestWakeupEvidenceStructuredMergeAndLegacyWriter(t *testing.T) {+ w := db.IssueWakeup{Kind: "event", Instruction: "Inspect current state"}+ fact := func(id string) []db.IssueWakeupReceipt {+ return []db.IssueWakeupReceipt{{EventType: "comment.created", Payload: json.RawMessage(`{"comment_id":"` + id + `","coalesced_count":1}`)}}+ }+ note, raw := mergeWakeupEvidence(w, db.AgentTaskQueue{}, fact("first"))+ contextJSON, _ := json.Marshal(map[string]json.RawMessage{"wakeup_evidence": raw})+ previous := db.AgentTaskQueue{Context: contextJSON, HandoffNote: pgtype.Text{String: note, Valid: true}}+ note, raw = mergeWakeupEvidence(w, previous, fact("second"))+ var summary wakeupEvidence+ if err := json.Unmarshal(raw, &summary); err != nil {+ t.Fatal(err)+ }+ if len(summary.Facts) != 2 || summary.Legacy != "" || strings.Count(note, "Instruction:") != 1 {+ t.Fatalf("facts were merged as rendered text: %s", raw)+ }+ // An older server only knows handoff_note. Preserve its new input on upgrade.+ previous.HandoffNote.String += "legacy-only-reference\n"+ note, raw = mergeWakeupEvidence(w, previous, fact("third"))+ if !strings.Contains(note, "legacy-only-reference") || !strings.Contains(note, "third") {+ t.Fatal("old writer's input was lost")+ }+ if err := json.Unmarshal(raw, &summary); err != nil || summary.Legacy != previous.HandoffNote.String {+ t.Fatalf("legacy text was parsed: %s", raw)+ }+}++func TestWakeupEvidenceJSONBFormattingAndTimerReplacement(t *testing.T) {+ w := db.IssueWakeup{Kind: "event", Instruction: "inspect"}+ receipt := db.IssueWakeupReceipt{EventType: "comment.created", Payload: json.RawMessage(`{"revision":9007199254740993,"comment_id":"first"}`)}+ note, _ := mergeWakeupEvidence(w, db.AgentTaskQueue{}, []db.IssueWakeupReceipt{receipt})+ previous := db.AgentTaskQueue{Context: json.RawMessage(`{"wakeup_evidence":{"version":1,"facts":[{"event_type":"comment.created","payload":{"revision":9007199254740993, "comment_id":"first"}}]}}`), HandoffNote: pgtype.Text{String: note, Valid: true}}+ _, raw := mergeWakeupEvidence(w, previous, nil)+ var summary wakeupEvidence+ _ = json.Unmarshal(raw, &summary)+ if summary.Legacy != "" || !strings.Contains(string(raw), "9007199254740993") {+ t.Fatalf("JSONB formatting lost structured data or number precision: %s", raw)+ }+ w.Kind = "every"+ note, _ = mergeWakeupEvidence(w, previous, []db.IssueWakeupReceipt{{EventType: "time.due", Payload: json.RawMessage(`{"planned_at":"next"}`)}})+ if strings.Contains(note, "first") || !strings.Contains(note, "next") {+ t.Fatal("timer should keep only latest tick")+ }+}++func TestIssueWakeupStructuredEvidenceSurvivesDatabaseRoundTrip(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created"}, Instruction: "read state"})+ first := f.Comment(t, util.UUIDToString(issue), "first")+ wakeDispatch(t, s, w)+ second := f.Comment(t, util.UUIDToString(issue), "second")+ wakeDispatch(t, s, w)+ task, err := f.q.FindPendingWakeupTask(t.Context(), util.UUIDToString(w.ID))+ if err != nil {+ t.Fatal(err)+ }+ var stored struct {+ Evidence wakeupEvidence `json:"wakeup_evidence"`+ }+ if err = json.Unmarshal(task.Context, &stored); err != nil {+ t.Fatal(err)+ }+ if len(stored.Evidence.Facts) != 2 || stored.Evidence.Legacy != "" || !strings.Contains(task.HandoffNote.String, first) || !strings.Contains(task.HandoffNote.String, second) {+ t.Fatalf("summary did not survive database round trip: %s", task.Context)+ }+}++func TestWakeupEvidenceInstructionEditDoesNotReintroduceOldPrompt(t *testing.T) {+ w := db.IssueWakeup{Kind: "event", Instruction: "old instructions"}+ first, raw := mergeWakeupEvidence(w, db.AgentTaskQueue{}, []db.IssueWakeupReceipt{{EventType: "comment.created", Payload: json.RawMessage(`{"comment_id":"first"}`)}})+ ctx, _ := json.Marshal(map[string]json.RawMessage{"wakeup_evidence": raw})+ w.Instruction = "new instructions"+ note, raw := mergeWakeupEvidence(w, db.AgentTaskQueue{Context: ctx, HandoffNote: pgtype.Text{String: first, Valid: true}}, []db.IssueWakeupReceipt{{EventType: "comment.created", Payload: json.RawMessage(`{"comment_id":"second"}`)}})+ var evidence wakeupEvidence+ if err := json.Unmarshal(raw, &evidence); err != nil {+ t.Fatal(err)+ }+ if evidence.Legacy != "" || len(evidence.Facts) != 2 || evidence.Instruction != w.Instruction || strings.Contains(note, "old instructions") || !strings.Contains(note, "new instructions") {+ t.Fatalf("prompt edit confused structured evidence: %s", note)+ }+}diff --git a/server/internal/service/issue_wakeup_instruction_test.go b/server/internal/service/issue_wakeup_instruction_test.gonew file mode 100644index 0000000000..e4aa9e35ce--- /dev/null+++ b/server/internal/service/issue_wakeup_instruction_test.go@@ -0,0 +1,142 @@+package service++import (+ "context"+ "errors"+ "reflect"+ "strings"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/multica-ai/multica/server/internal/util"+)++func TestIssueWakeupInstructionPreservesStateAndPendingEvents(t *testing.T) {+ for _, kind := range []string{"event", "at", "every", "cron"} {+ t.Run(kind, func(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ ctx := context.Background()+ owner := parseTestUUID(t, f.UserID)+ input := WakeupInput{AgentID: agent, Kind: kind, Instruction: "original", Timezone: "UTC"}+ switch kind {+ case "event":+ input.EventTypes = []string{"comment.created"}+ case "at":+ input.AfterSeconds = 600+ case "every":+ input.IntervalSeconds = 600+ case "cron":+ input.CronExpression = "0 * * * *"+ }+ w := wakeCreate(t, f, s, issue, input)+ if kind == "event" {+ f.Comment(t, util.UUIDToString(issue), "captured before edit")+ }+ before, err := s.Tasks.Queries.LocklessWakeup(ctx, w.ID)+ if err != nil {+ t.Fatal(err)+ }+ in := WakeupInstructionInput{Instruction: "new instructions", ExpectedInstruction: w.Instruction, Revision: w.Revision}+ if err = s.EditInstruction(ctx, issue, w.ID, owner, in); err != nil {+ t.Fatal(err)+ }+ after, err := s.Tasks.Queries.LocklessWakeup(ctx, w.ID)+ if err != nil {+ t.Fatal(err)+ }+ normalized := after+ normalized.Instruction = before.Instruction+ normalized.UpdatedAt = before.UpdatedAt+ if !reflect.DeepEqual(before, normalized) {+ t.Fatalf("editing altered subscription: before=%+v after=%+v", before, after)+ }+ if err = s.EditInstruction(ctx, issue, w.ID, owner, in); !errors.Is(err, ErrWakeupConflict) {+ t.Fatalf("stale edit: %v", err)+ }+ if kind == "event" {+ wakeDispatch(t, s, after)+ var note string+ if err = f.Pool.QueryRow(ctx, "SELECT handoff_note FROM agent_task_queue WHERE issue_id=$1 AND context->>'wakeup_id'=$2", issue, util.UUIDToString(w.ID)).Scan(¬e); err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(note, "new instructions") {+ t.Fatal("pending event lost or dispatched old instructions")+ }+ }+ if _, err = s.Disable(ctx, issue, w.ID, owner); err != nil {+ t.Fatal(err)+ }+ in.ExpectedInstruction = in.Instruction+ in.Instruction = "saved while off"+ if err = s.EditInstruction(ctx, issue, w.ID, owner, in); err != nil {+ t.Fatal(err)+ }+ off, err := s.Tasks.Queries.LocklessWakeup(ctx, w.ID)+ if err != nil {+ t.Fatal(err)+ }+ if off.Enabled || !off.DisabledAt.Valid || off.NextFireAt != after.NextFireAt {+ t.Fatal("edit rearmed disabled rule")+ }+ })+ }+}++func TestIssueWakeupInstructionPreservesQueuedRunAndChecksScope(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ ctx := context.Background()+ owner := parseTestUUID(t, f.UserID)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "at", AfterSeconds: 600, Instruction: "queued instruction"})+ f.Exec(t, "UPDATE issue_wakeup SET next_fire_at=now()-interval '1 second' WHERE id=$1", w.ID)+ wakeDispatch(t, s, w)+ in := WakeupInstructionInput{Instruction: "future instruction", ExpectedInstruction: w.Instruction, Revision: w.Revision}+ if err := s.EditInstruction(ctx, issue, w.ID, owner, in); err != nil {+ t.Fatal(err)+ }+ var note string+ if err := f.Pool.QueryRow(ctx, "SELECT handoff_note FROM agent_task_queue WHERE issue_id=$1 AND context->>'wakeup_id'=$2", issue, util.UUIDToString(w.ID)).Scan(¬e); err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(note, "queued instruction") || strings.Contains(note, "future instruction") {+ t.Fatal("edit rewrote queued run")+ }+ current, err := s.Tasks.Queries.LocklessWakeup(ctx, w.ID)+ if err != nil {+ t.Fatal(err)+ }+ if current.Enabled || current.Revision != w.Revision {+ t.Fatal("edit rearmed consumed rule")+ }+ in.ExpectedInstruction = in.Instruction+ other := f.Issue(t, "other issue")+ if err = s.EditInstruction(ctx, parseTestUUID(t, other), w.ID, owner, in); !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("cross issue: %v", err)+ }+ outsider := f.User(t, "outsider", "[email protected]")+ if err = s.EditInstruction(ctx, issue, w.ID, parseTestUUID(t, outsider), in); !errors.Is(err, ErrWakeupForbidden) {+ t.Fatalf("outsider: %v", err)+ }+ f.Member(t, f.WorkspaceID, outsider, "member")+ if err = s.EditInstruction(ctx, issue, w.ID, parseTestUUID(t, outsider), in); !errors.Is(err, ErrWakeupForbidden) {+ t.Fatalf("other member: %v", err)+ }+ for _, value := range []string{" ", strings.Repeat("中", 4001)} {+ in.Instruction = value+ if err = s.EditInstruction(ctx, issue, w.ID, owner, in); !errors.Is(err, ErrWakeupInput) {+ t.Fatalf("invalid text accepted: %v", err)+ }+ }+ // A revision change fences edits even when the old prompt remains the same.+ in.Instruction = "valid"+ in.Revision+++ if err = s.EditInstruction(ctx, issue, w.ID, owner, in); !errors.Is(err, ErrWakeupConflict) {+ t.Fatalf("stale revision: %v", err)+ }+ // Editing requires current invoke rights; it cannot borrow the rule owner's rights.+ f.Exec(t, "UPDATE agent SET archived_at=$2 WHERE id=$1", agent, time.Now())+ in.Revision = w.Revision+ if err = s.EditInstruction(ctx, issue, w.ID, owner, in); !errors.Is(err, ErrWakeupForbidden) {+ t.Fatalf("archived target: %v", err)+ }+}diff --git a/server/internal/service/issue_wakeup_lock_order_test.go b/server/internal/service/issue_wakeup_lock_order_test.gonew file mode 100644index 0000000000..8d09fbab49--- /dev/null+++ b/server/internal/service/issue_wakeup_lock_order_test.go@@ -0,0 +1,59 @@+package service++import (+ "context"+ "github.com/jackc/pgx/v5"+ "github.com/multica-ai/multica/server/internal/util"+ "strings"+ "testing"+ "time"+)++type wakeupTaskLockProbe struct {+ TxStarter+ beforeTaskLock func()+}++func (s wakeupTaskLockProbe) Begin(ctx context.Context) (pgx.Tx, error) {+ tx, err := s.TxStarter.Begin(ctx)+ if err != nil {+ return nil, err+ }+ return wakeupProbeTx{Tx: tx, beforeTaskLock: s.beforeTaskLock}, nil+}++type wakeupProbeTx struct {+ pgx.Tx+ beforeTaskLock func()+}++func (tx wakeupProbeTx) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {+ if strings.Contains(sql, "-- name: FindPendingWakeupTask") {+ tx.beforeTaskLock()+ }+ return tx.Tx.QueryRow(ctx, sql, args...)+}++func TestIssueWakeupTaskLockWaitDoesNotHoldReceipt(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created"}, Instruction: "check"})+ f.Comment(t, util.UUIDToString(issue), "first")+ wakeDispatch(t, s, w)+ f.Comment(t, util.UUIDToString(issue), "pending")+ checked := false+ s.Tasks.TxStarter = wakeupTaskLockProbe{TxStarter: f.Pool, beforeTaskLock: func() {+ checked = true+ // Execute while dispatch has reached the task-lock boundary. Before the+ // reorder this blocks on a receipt already locked by dispatch.+ ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)+ defer cancel()+ _, err := f.Pool.Exec(ctx, `INSERT INTO comment(issue_id,workspace_id,author_type,author_id,content,type) VALUES($1,$2,'member',$3,'concurrent','comment')`, issue, f.WorkspaceID, f.UserID)+ if err != nil {+ t.Errorf("comment capture blocked behind task-lock wait: %v", err)+ }+ }}+ wakeDispatch(t, s, w)+ if !checked {+ t.Fatal("task-lock boundary not exercised")+ }+}diff --git a/server/internal/service/issue_wakeup_review_test.go b/server/internal/service/issue_wakeup_review_test.gonew file mode 100644index 0000000000..3216720765--- /dev/null+++ b/server/internal/service/issue_wakeup_review_test.go@@ -0,0 +1,113 @@+package service++import (+ "context"+ "encoding/json"+ "strings"+ "testing"+ "unicode/utf8"++ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestIssueWakeupLargeSingleFactPreservesReferences(t *testing.T) {+ payload, _ := json.Marshal(map[string]any{"comment_id": "source-comment", "changed_fields": strings.Repeat("字段", 20000)})+ w := db.IssueWakeup{Instruction: strings.Repeat("指", 4000)}+ note, _ := mergeWakeupEvidence(w, db.AgentTaskQueue{}, []db.IssueWakeupReceipt{{EventType: "comment.updated", Payload: payload}})+ if len(note) > wakeupNoteLimit || !utf8.ValidString(note) || !strings.Contains(note, w.Instruction) || !strings.Contains(note, "source-comment") || !strings.Contains(note, wakeupOmittedEvidence) {+ t.Fatalf("oversized fact not safely condensed: %d bytes", len(note))+ }+}++func TestIssueWakeupRegistrationRunDoesNotTriggerItself(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ source := f.Task(t, agent, testutil.Cols{"issue_id": issue, "status": "running", "runtime_id": testutil.Raw("(SELECT runtime_id FROM agent WHERE id='" + agent + "')")})+ w, err := s.Create(context.Background(), issue, parseTestUUID(t, f.UserID), parseTestUUID(t, source), WakeupInput{+ AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created", "task.completed"}, Instruction: "Wait for new input",+ })+ if err != nil {+ t.Fatal(err)+ }+ f.Comment(t, util.UUIDToString(issue), "Registered", testutil.Cols{"author_type": "agent", "author_id": agent, "source_task_id": source})+ f.Exec(t, "UPDATE agent_task_queue SET status='completed',completed_at=now() WHERE id=$1", source)+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1", w.ID); n != 0 {+ t.Fatalf("registration run produced %d receipts for itself", n)+ }+ f.Comment(t, util.UUIDToString(issue), "External input")+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1", w.ID); n != 1 {+ t.Fatalf("external input lost: %d", n)+ }+ wakeDispatch(t, s, w)+}++func TestIssueWakeupOversizedPendingEvidenceStillConsumesInputs(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created"}, Instruction: "Keep this instruction"})+ f.Comment(t, util.UUIDToString(issue), "first")+ wakeDispatch(t, s, w)+ task, err := f.q.FindPendingWakeupTask(context.Background(), util.UUIDToString(w.ID))+ if err != nil {+ t.Fatal(err)+ }+ f.Exec(t, "UPDATE agent_task_queue SET handoff_note=$2 WHERE id=$1", task.ID, strings.Repeat("旧", 20000))+ latest := f.Comment(t, util.UUIDToString(issue), "latest")+ wakeDispatch(t, s, w)+ got, err := f.q.GetAgentTask(context.Background(), task.ID)+ if err != nil {+ t.Fatal(err)+ }+ if !utf8.ValidString(got.HandoffNote.String) || len(got.HandoffNote.String) > 40000 || !strings.Contains(got.HandoffNote.String, latest) || !strings.Contains(got.HandoffNote.String, w.Instruction) {+ t.Fatalf("evidence not bounded with instruction/latest reference: %d bytes", len(got.HandoffNote.String))+ }+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND processed_at IS NULL", w.ID); n != 0 {+ t.Fatalf("%d inputs stalled", n)+ }+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND task_id=$2", w.ID, task.ID); n != 2 {+ t.Fatalf("lost durable evidence: %d", n)+ }+ if n := f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'=$1", util.UUIDToString(w.ID)); n != 1 {+ t.Fatalf("duplicate task: %d", n)+ }+}++func TestIssueWakeupDispatchedWaitIsObservableAndResumes(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created"}, Instruction: "Wait for input"})+ f.Comment(t, util.UUIDToString(issue), "first")+ wakeDispatch(t, s, w)+ task, err := f.q.FindPendingWakeupTask(context.Background(), util.UUIDToString(w.ID))+ if err != nil {+ t.Fatal(err)+ }+ f.Exec(t, "UPDATE agent_task_queue SET status='dispatched',dispatched_at=now()-interval '10 minutes',prepare_lease_expires_at=now()-interval '1 minute' WHERE id=$1", task.ID)+ f.Comment(t, util.UUIDToString(issue), "next")+ wakeDispatch(t, s, w)+ got, err := f.q.GetIssueWakeup(context.Background(), db.GetIssueWakeupParams{ID: w.ID, WorkspaceID: w.WorkspaceID})+ if err != nil {+ t.Fatal(err)+ }+ if !got.LastError.Valid {+ t.Fatal("stale dispatched wait is invisible")+ }+ unchanged, _ := f.q.GetAgentTask(context.Background(), task.ID)+ if unchanged.HandoffNote != task.HandoffNote {+ t.Fatal("changed claimed prompt")+ }+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND processed_at IS NULL", w.ID); n != 1 {+ t.Fatalf("pending input lost: %d", n)+ }+ f.Exec(t, "UPDATE agent_task_queue SET status='running',started_at=now() WHERE id=$1", task.ID)+ wakeDispatch(t, s, w)+ got, err = f.q.GetIssueWakeup(context.Background(), db.GetIssueWakeupParams{ID: w.ID, WorkspaceID: w.WorkspaceID})+ if err != nil {+ t.Fatal(err)+ }+ if got.LastError.Valid || got.LastTaskID == task.ID {+ t.Fatal("did not resume/clear error after start")+ }+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND processed_at IS NULL", w.ID); n != 0 {+ t.Fatalf("pending input stalled: %d", n)+ }+}diff --git a/server/internal/service/issue_wakeup_test.go b/server/internal/service/issue_wakeup_test.gonew file mode 100644index 0000000000..0fd038c003--- /dev/null+++ b/server/internal/service/issue_wakeup_test.go@@ -0,0 +1,284 @@+package service++import (+ "context"+ "errors"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func wakeFixture(t *testing.T) (principalFixture, *IssueWakeupService, pgtype.UUID, string) {+ t.Helper()+ f, owner := newPrincipalFixture(t)+ if err := f.q.SeedIssueStatusEntries(context.Background(), parseTestUUID(t, f.WorkspaceID)); err != nil {+ t.Fatal(err)+ }+ issue := f.Issue(t, "Wakeup test")+ agent := f.privateAgentOwnedBy(t, owner, "wake")+ // Service-created data is cleaned before fixture owners, including receipts.+ f.Cleanup(t, "DELETE FROM issue_wakeup WHERE issue_id=$1", issue)+ f.Cleanup(t, "DELETE FROM issue_wakeup_receipt WHERE wakeup_id IN (SELECT id FROM issue_wakeup WHERE issue_id=$1)", issue)+ f.Cleanup(t, "DELETE FROM agent_task_queue WHERE issue_id=$1", issue)+ return f, &IssueWakeupService{Tasks: f.svc.TaskSvc}, parseTestUUID(t, issue), agent+}+func parseTestUUID(t *testing.T, s string) pgtype.UUID {+ t.Helper()+ id, e := util.ParseUUID(s)+ if e != nil {+ t.Fatal(e)+ }+ return id+}+func wakeCreate(t *testing.T, f principalFixture, s *IssueWakeupService, issue pgtype.UUID, in WakeupInput) db.IssueWakeup {+ t.Helper()+ w, e := s.Create(context.Background(), issue, parseTestUUID(t, f.UserID), pgtype.UUID{}, in)+ if e != nil {+ t.Fatal(e)+ }+ return w+}+func wakeDispatch(t *testing.T, s *IssueWakeupService, w db.IssueWakeup) {+ t.Helper()+ if e := s.dispatch(context.Background(), w); e != nil {+ t.Fatal(e)+ }+}++func TestIssueWakeupEventAtomicOnceAndIndependentInputs(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ ctx := context.Background()+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"comment.created"}, Instruction: "Review latest changes"})+ // A source rollback cannot leave a notification behind.+ tx, e := f.Pool.Begin(ctx)+ if e != nil {+ t.Fatal(e)+ }+ _, e = tx.Exec(ctx, "INSERT INTO comment(issue_id,workspace_id,author_type,author_id,content,type) VALUES($1,$2,'member',$3,'rollback','comment')", issue, f.WorkspaceID, f.UserID)+ if e != nil {+ t.Fatal(e)+ }+ _ = tx.Rollback(ctx)+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1", w.ID); n != 0 {+ t.Fatalf("rollback left %d receipts", n)+ }+ comment := f.Comment(t, util.UUIDToString(issue), "source")+ // Existing assign task must coexist and must not absorb the wakeup.+ ordinary := f.Task(t, agent, testutil.Cols{"issue_id": issue, "runtime_id": testutil.Raw("(SELECT runtime_id FROM agent WHERE id='" + agent + "')")})+ wakeDispatch(t, s, w)+ wakeDispatch(t, s, w)+ got, e := f.q.GetIssueWakeup(ctx, db.GetIssueWakeupParams{ID: w.ID, WorkspaceID: w.WorkspaceID})+ if e != nil {+ t.Fatal(e)+ }+ if got.Enabled || !got.LastTaskID.Valid {+ t.Fatalf("not consumed: %+v", got)+ }+ task, e := f.q.GetAgentTask(ctx, got.LastTaskID)+ if e != nil {+ t.Fatal(e)+ }+ if !strings.Contains(task.HandoffNote.String, comment) || task.OriginatorUserID != parseTestUUID(t, f.UserID) {+ t.Fatal("missing input or principal")+ }+ if n := f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'=$1", util.UUIDToString(w.ID)); n != 1 {+ t.Fatalf("duplicate runs %d", n)+ }+ _, e = s.Disable(ctx, issue, w.ID, parseTestUUID(t, f.UserID))+ if e != nil {+ t.Fatal(e)+ }+ var status string+ f.QueryRow(t, "SELECT status FROM agent_task_queue WHERE id=$1", ordinary).Scan(&status)+ if status != "queued" {+ t.Fatal("disable changed assign task")+ }+ f.QueryRow(t, "SELECT status FROM agent_task_queue WHERE id=$1", task.ID).Scan(&status)+ if status != "cancelled" {+ t.Fatal("wakeup not withdrawn")+ }+}++func TestIssueWakeupTerminalStateAndScope(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ source := f.Task(t, agent, testutil.Cols{"issue_id": issue, "status": "completed", "runtime_id": testutil.Raw("(SELECT runtime_id FROM agent WHERE id='" + agent + "')")})+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"task.completed"}, FilterTaskID: source, Instruction: "inspect output"})+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1", w.ID); n != 1 {+ t.Fatal("missed already-terminal run")+ }+ wakeDispatch(t, s, w)+ otherIssue := f.Issue(t, "Other issue")+ _, err := s.Create(context.Background(), parseTestUUID(t, otherIssue), parseTestUUID(t, f.UserID), pgtype.UUID{}, WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"task.completed"}, FilterTaskID: source, Instruction: "invalid scope"})+ if !errors.Is(err, ErrWakeupInput) {+ t.Fatalf("scope accepted: %v", err)+ }+}++func TestIssueWakeupContinuousSelfLoopAndClose(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ ctx := context.Background()+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created", "task.completed"}, Instruction: "check"})+ f.Comment(t, util.UUIDToString(issue), "one")+ wakeDispatch(t, s, w)+ got, _ := f.q.GetIssueWakeup(ctx, db.GetIssueWakeupParams{ID: w.ID, WorkspaceID: w.WorkspaceID})+ first := got.LastTaskID+ f.Exec(t, "UPDATE agent_task_queue SET status='running',started_at=now() WHERE id=$1", first)+ f.Comment(t, util.UUIDToString(issue), "self", testutil.Cols{"author_type": "agent", "author_id": agent, "source_task_id": first})+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND processed_at IS NULL", w.ID); n != 0 {+ t.Fatal("self comment reawakened")+ }+ f.Comment(t, util.UUIDToString(issue), "two")+ wakeDispatch(t, s, w)+ f.Comment(t, util.UUIDToString(issue), "three")+ wakeDispatch(t, s, w)+ if n := f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'=$1 AND status='queued'", util.UUIDToString(w.ID)); n != 1 {+ t.Fatalf("pending backlog: %d", n)+ }+ f.Insert(t, "issue_status", testutil.Cols{"workspace_id": f.WorkspaceID, "key": "finished", "name": "Finished", "category": "done", "color": "#000000"})+ f.Exec(t, "UPDATE issue SET status='finished' WHERE id=$1", issue)+ got, _ = f.q.GetIssueWakeup(ctx, db.GetIssueWakeupParams{ID: w.ID, WorkspaceID: w.WorkspaceID})+ if got.Enabled || !got.DisabledAt.Valid {+ t.Fatal("custom end state did not disable")+ }+ task, _ := f.q.GetAgentTask(ctx, first)+ if task.Status != "running" {+ t.Fatal("close stopped active run")+ }+ f.Exec(t, "UPDATE issue SET status='todo' WHERE id=$1", issue)+ got, _ = f.q.GetIssueWakeup(ctx, db.GetIssueWakeupParams{ID: w.ID, WorkspaceID: w.WorkspaceID})+ if got.Enabled {+ t.Fatal("reopen enabled old subscription")+ }+}++func TestIssueWakeupTimeRecoveryUpdateAndRevocation(t *testing.T) {+ for _, kind := range []string{"at", "every", "cron"} {+ t.Run(kind, func(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ ctx := context.Background()+ in := WakeupInput{AgentID: agent, Kind: kind, Instruction: "check CI"}+ switch kind {+ case "at":+ in.AfterSeconds = 600+ case "every":+ in.IntervalSeconds = 3600+ case "cron":+ in.CronExpression = "0 * * * *"+ in.Timezone = "Asia/Shanghai"+ }+ w := wakeCreate(t, f, s, issue, in)+ f.Exec(t, "UPDATE issue_wakeup SET next_fire_at=now()-interval '3 hours' WHERE id=$1", w.ID)+ f.Exec(t, "UPDATE agent_runtime SET status='offline' WHERE id=(SELECT runtime_id FROM agent WHERE id=$1)", agent)+ wakeDispatch(t, s, w)+ wakeDispatch(t, s, w)+ if n := f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'=$1", util.UUIDToString(w.ID)); n != 1 {+ t.Fatalf("offline catchup creates %d runs", n)+ }+ // Replacing the configuration withdraws the old queued input.+ updated, e := s.Save(ctx, issue, parseTestUUID(t, f.UserID), pgtype.UUID{}, w.ID, in)+ if e != nil {+ t.Fatal(e)+ }+ if updated.Revision != 2 {+ t.Fatal("revision missing")+ }+ if n := f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'=$1 AND status='queued'", util.UUIDToString(w.ID)); n != 0 {+ t.Fatal("stale revision still queued")+ }+ f.Exec(t, "UPDATE issue_wakeup SET next_fire_at=now()-interval '1 second' WHERE id=$1", w.ID)+ f.Exec(t, "DELETE FROM member WHERE user_id=$1 AND workspace_id=$2", f.UserID, f.WorkspaceID)+ wakeDispatch(t, s, updated)+ got, _ := f.q.GetIssueWakeup(ctx, db.GetIssueWakeupParams{ID: w.ID, WorkspaceID: w.WorkspaceID})+ if got.Enabled || !got.LastError.Valid {+ t.Fatal("permission revoked but still enabled")+ }+ })+ }+}++func TestIssueWakeupValidate(t *testing.T) {+ s := IssueWakeupService{}+ for _, in := range []WakeupInput{{Kind: "event", Instruction: "x", EventTypes: []string{"review_ready"}}, {Kind: "every", Instruction: "x", IntervalSeconds: 1}, {Kind: "cron", Instruction: "x", CronExpression: "bad"}, {Kind: "at", Instruction: "x", AfterSeconds: -1}} {+ if _, err := s.Validate(&in, time.Now()); !errors.Is(err, ErrWakeupInput) {+ t.Errorf("accepted %+v", in)+ }+ }+}++func TestIssueWakeupStatusSourceAndClaimAuthority(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ ctx := context.Background()+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"issue.status_changed"}, Instruction: "check state"})+ f.Exec(t, "UPDATE issue SET status='in_progress',revision=revision+1 WHERE id=$1", issue)+ wakeDispatch(t, s, w)+ got, _ := f.q.GetIssueWakeup(ctx, db.GetIssueWakeupParams{ID: w.ID, WorkspaceID: w.WorkspaceID})+ _, err := f.q.UpdateIssue(ctx, db.UpdateIssueParams{ID: issue, Status: pgtype.Text{String: "in_review", Valid: true}, SourceTaskID: got.LastTaskID})+ if err != nil {+ t.Fatal(err)+ }+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND processed_at IS NULL", w.ID); n != 0 {+ t.Fatal("self status update created a loop")+ }+ task, _ := f.q.GetAgentTask(ctx, got.LastTaskID)+ if err = s.CheckClaim(ctx, task); err != nil {+ t.Fatal(err)+ }+ f.Exec(t, "DELETE FROM member WHERE user_id=$1 AND workspace_id=$2", f.UserID, f.WorkspaceID)+ if !errors.Is(s.CheckClaim(ctx, task), ErrWakeupForbidden) {+ t.Fatal("revoked member still claimable")+ }+}++func TestIssueWakeupRetryKeepsPromptAndSchedulingScope(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ ctx := context.Background()+ parent := f.Comment(t, util.UUIDToString(issue), "original request")+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "at", AfterSeconds: 1, ParentCommentID: parent, Instruction: "specific wakeup instruction"})+ f.Exec(t, "UPDATE issue_wakeup SET next_fire_at=now()-interval '1 second' WHERE id=$1", w.ID)+ wakeDispatch(t, s, w)+ got, _ := f.q.GetIssueWakeup(ctx, db.GetIssueWakeupParams{ID: w.ID, WorkspaceID: w.WorkspaceID})+ task, _ := f.q.GetAgentTask(ctx, got.LastTaskID)+ if task.CommentThreadID != w.ID || util.UUIDToString(task.TriggerCommentID) != parent {+ t.Fatal("delivery thread and scheduling scope confused")+ }+ f.Exec(t, "UPDATE agent_task_queue SET status='failed',completed_at=now() WHERE id=$1", task.ID)+ child, err := f.q.CreateRetryTask(ctx, db.CreateRetryTaskParams{ID: task.ID})+ if err != nil {+ t.Fatal(err)+ }+ if child.HandoffNote != task.HandoffNote || child.CommentThreadID != w.ID {+ t.Fatal("retry lost wakeup prompt or scope")+ }+ f.Cleanup(t, "DELETE FROM agent_task_queue WHERE id=$1", child.ID)+}++func TestIssueWakeupConcurrentDispatchIsIdempotent(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "at", AfterSeconds: 1, Instruction: "once"})+ f.Exec(t, "UPDATE issue_wakeup SET next_fire_at=now()-interval '1 second' WHERE id=$1", w.ID)+ var wg sync.WaitGroup+ errs := make(chan error, 6)+ for range 6 {+ wg.Go(func() {+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ errs <- s.dispatch(ctx, w)+ })+ }+ wg.Wait()+ close(errs)+ for err := range errs {+ if err != nil {+ t.Error(err)+ }+ }+ if n := f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'=$1", util.UUIDToString(w.ID)); n != 1 {+ t.Fatalf("created %d runs", n)+ }+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 011f561797..370f79af45 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -6041,9 +6041,10 @@ func (s *TaskService) HandleFailedTasks(ctx context.Context, tasks []db.AgentTas)} else if !hasActive {updatedIssue, updateErr := s.Queries.UpdateIssueStatus(ctx, db.UpdateIssueStatusParams{- ID: t.IssueID,- Status: "todo",- WorkspaceID: issue.WorkspaceID,+ SourceTaskID: t.ID,+ ID: t.IssueID,+ Status: "todo",+ WorkspaceID: issue.WorkspaceID,})if updateErr != nil {slog.Warn("handle failed tasks: reset stuck issue failed",@@ -7479,7 +7480,7 @@ func (s *TaskService) createAgentComment(ctx context.Context, issueID, agentID p"issue_revision": created.IssueRevision,},})- s.AutoUnresolveThreadOnReply(ctx, rootComment, util.UUIDToString(issue.WorkspaceID), "agent", util.UUIDToString(agentID))+ s.AutoUnresolveThreadOnReply(ctx, rootComment, util.UUIDToString(issue.WorkspaceID), "agent", util.UUIDToString(agentID), sourceTaskID)}// AutoUnresolveThreadOnReply clears resolved_at on the thread root when a@@ -7488,15 +7489,32 @@ func (s *TaskService) createAgentComment(ctx context.Context, issueID, agentID p// TaskService.createAgentComment path so the resolved-then-replied state can// never desync (one of the bugs Emacs flagged on PR #2300). Errors are logged// — the reply itself already committed, the desync is recoverable on next read.-func (s *TaskService) AutoUnresolveThreadOnReply(ctx context.Context, parent *db.Comment, workspaceID, actorType, actorID string) {+func (s *TaskService) AutoUnresolveThreadOnReply(ctx context.Context, parent *db.Comment, workspaceID, actorType, actorID string, sourceTaskID pgtype.UUID) {if parent == nil || !parent.ResolvedAt.Valid {return}- updated, err := s.Queries.UnresolveComment(ctx, parent.ID)+ // This follow-up write is a consequence of the reply's run, not a new+ // system action. Preserve that lineage for event subscriptions as well.+ tx, err := s.TxStarter.Begin(ctx)+ if err != nil {+ slog.Warn("auto-unresolve transaction failed", "error", err)+ return+ }+ defer tx.Rollback(ctx)+ _, err = tx.Exec(ctx, `SELECT set_config('multica.actor_type',$1,true),set_config('multica.actor_id',$2,true),set_config('multica.source_task_id',$3,true)`, actorType, actorID, util.UUIDToString(sourceTaskID))+ if err != nil {+ slog.Warn("auto-unresolve source attribution failed", "error", err)+ return+ }+ updated, err := s.Queries.WithTx(tx).UnresolveComment(ctx, parent.ID)if err != nil {slog.Warn("auto-unresolve on reply failed", "error", err, "comment_id", util.UUIDToString(parent.ID))return}+ if err := tx.Commit(ctx); err != nil {+ slog.Warn("auto-unresolve commit failed", "error", err)+ return+ }s.Bus.Publish(events.Event{Type: protocol.EventCommentUnresolved,WorkspaceID: workspaceID,diff --git a/server/migrations/509_issue_wakeup.down.sql b/server/migrations/509_issue_wakeup.down.sqlnew file mode 100644index 0000000000..4e4f2430ad--- /dev/null+++ b/server/migrations/509_issue_wakeup.down.sql@@ -0,0 +1,2 @@+DROP TABLE IF EXISTS issue_wakeup_receipt;+DROP TABLE IF EXISTS issue_wakeup;diff --git a/server/migrations/509_issue_wakeup.up.sql b/server/migrations/509_issue_wakeup.up.sqlnew file mode 100644index 0000000000..9cf075b4c4--- /dev/null+++ b/server/migrations/509_issue_wakeup.up.sql@@ -0,0 +1,19 @@+CREATE TABLE issue_wakeup (+ id uuid NOT NULL, workspace_id uuid NOT NULL, issue_id uuid NOT NULL,+ agent_id uuid NOT NULL, created_by uuid NOT NULL, source_task_id uuid,+ parent_comment_id uuid, instruction text NOT NULL,+ kind text NOT NULL CHECK (kind IN ('event','at','every','cron')),+ mode text NOT NULL CHECK (mode IN ('once','continuous')),+ event_types text[] NOT NULL DEFAULT '{}', filter_agent_id uuid, filter_task_id uuid,+ interval_seconds bigint, cron_expression text, timezone text NOT NULL DEFAULT 'UTC',+ next_fire_at timestamptz, enabled boolean NOT NULL DEFAULT true,+ disabled_at timestamptz, revision bigint NOT NULL DEFAULT 1,+ last_task_id uuid, last_error text,+ created_at timestamptz NOT NULL DEFAULT clock_timestamp(), updated_at timestamptz NOT NULL DEFAULT clock_timestamp()+);+CREATE TABLE issue_wakeup_receipt (+ id uuid NOT NULL, wakeup_id uuid NOT NULL, revision bigint NOT NULL,+ event_key text NOT NULL, event_type text NOT NULL, payload jsonb NOT NULL,+ task_id uuid, processed_at timestamptz,+ created_at timestamptz NOT NULL DEFAULT clock_timestamp()+);diff --git a/server/migrations/510_wakeup_id.down.sql b/server/migrations/510_wakeup_id.down.sqlnew file mode 100644index 0000000000..e7accd92e3--- /dev/null+++ b/server/migrations/510_wakeup_id.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS issue_wakeup_id_idx;diff --git a/server/migrations/510_wakeup_id.up.sql b/server/migrations/510_wakeup_id.up.sqlnew file mode 100644index 0000000000..70c32985e7--- /dev/null+++ b/server/migrations/510_wakeup_id.up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX CONCURRENTLY issue_wakeup_id_idx ON issue_wakeup(id);diff --git a/server/migrations/511_wakeup_issue.down.sql b/server/migrations/511_wakeup_issue.down.sqlnew file mode 100644index 0000000000..83261d60bf--- /dev/null+++ b/server/migrations/511_wakeup_issue.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS issue_wakeup_issue_idx;diff --git a/server/migrations/511_wakeup_issue.up.sql b/server/migrations/511_wakeup_issue.up.sqlnew file mode 100644index 0000000000..cf0125e08e--- /dev/null+++ b/server/migrations/511_wakeup_issue.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY issue_wakeup_issue_idx ON issue_wakeup(issue_id,workspace_id);diff --git a/server/migrations/512_wakeup_due.down.sql b/server/migrations/512_wakeup_due.down.sqlnew file mode 100644index 0000000000..c1ee56a123--- /dev/null+++ b/server/migrations/512_wakeup_due.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS issue_wakeup_due_idx;diff --git a/server/migrations/512_wakeup_due.up.sql b/server/migrations/512_wakeup_due.up.sqlnew file mode 100644index 0000000000..8dd445e207--- /dev/null+++ b/server/migrations/512_wakeup_due.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY issue_wakeup_due_idx ON issue_wakeup(next_fire_at) WHERE enabled;diff --git a/server/migrations/513_wakeup_receipt_id.down.sql b/server/migrations/513_wakeup_receipt_id.down.sqlnew file mode 100644index 0000000000..d3f1d154a2--- /dev/null+++ b/server/migrations/513_wakeup_receipt_id.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS issue_wakeup_receipt_id_idx;diff --git a/server/migrations/513_wakeup_receipt_id.up.sql b/server/migrations/513_wakeup_receipt_id.up.sqlnew file mode 100644index 0000000000..7ca8f060b0--- /dev/null+++ b/server/migrations/513_wakeup_receipt_id.up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX CONCURRENTLY issue_wakeup_receipt_id_idx ON issue_wakeup_receipt(id);diff --git a/server/migrations/514_wakeup_receipt_key.down.sql b/server/migrations/514_wakeup_receipt_key.down.sqlnew file mode 100644index 0000000000..38323eba20--- /dev/null+++ b/server/migrations/514_wakeup_receipt_key.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS issue_wakeup_receipt_key_idx;diff --git a/server/migrations/514_wakeup_receipt_key.up.sql b/server/migrations/514_wakeup_receipt_key.up.sqlnew file mode 100644index 0000000000..35d2b8d493--- /dev/null+++ b/server/migrations/514_wakeup_receipt_key.up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX CONCURRENTLY issue_wakeup_receipt_key_idx ON issue_wakeup_receipt(wakeup_id,revision,event_key);diff --git a/server/migrations/515_wakeup_receipt_pending.down.sql b/server/migrations/515_wakeup_receipt_pending.down.sqlnew file mode 100644index 0000000000..f464ba6c66--- /dev/null+++ b/server/migrations/515_wakeup_receipt_pending.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS issue_wakeup_receipt_pending_idx;diff --git a/server/migrations/515_wakeup_receipt_pending.up.sql b/server/migrations/515_wakeup_receipt_pending.up.sqlnew file mode 100644index 0000000000..26b03c9e4e--- /dev/null+++ b/server/migrations/515_wakeup_receipt_pending.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY issue_wakeup_receipt_pending_idx ON issue_wakeup_receipt(wakeup_id,created_at) WHERE processed_at IS NULL;diff --git a/server/migrations/516_wakeup_pending_scope.down.sql b/server/migrations/516_wakeup_pending_scope.down.sqlnew file mode 100644index 0000000000..482769f540--- /dev/null+++ b/server/migrations/516_wakeup_pending_scope.down.sql@@ -0,0 +1,8 @@+-- Disable/drain wakeups before rolling back; ordinary task scopes are unchanged.+CREATE OR REPLACE FUNCTION set_agent_task_comment_thread() RETURNS trigger+LANGUAGE plpgsql AS $$+BEGIN+ NEW.comment_thread_id := comment_thread_root_id(NEW.trigger_comment_id);+ RETURN NEW;+END+$$;diff --git a/server/migrations/516_wakeup_pending_scope.up.sql b/server/migrations/516_wakeup_pending_scope.up.sqlnew file mode 100644index 0000000000..a5cf861410--- /dev/null+++ b/server/migrations/516_wakeup_pending_scope.up.sql@@ -0,0 +1,10 @@+-- Preserve the existing unique index and retry ON CONFLICT contract during a+-- rolling deployment. For wakeup runs the scheduling scope is the configuration+-- id; trigger_comment_id still holds the real result-delivery thread.+CREATE OR REPLACE FUNCTION set_agent_task_comment_thread() RETURNS trigger+LANGUAGE plpgsql AS $$+BEGIN+ NEW.comment_thread_id := COALESCE(NULLIF(NEW.context->>'wakeup_id','')::uuid,comment_thread_root_id(NEW.trigger_comment_id));+ RETURN NEW;+END+$$;diff --git a/server/migrations/518_wakeup_event_capture.down.sql b/server/migrations/518_wakeup_event_capture.down.sqlnew file mode 100644index 0000000000..e55f65e4bc--- /dev/null+++ b/server/migrations/518_wakeup_event_capture.down.sql@@ -0,0 +1,7 @@+DROP TRIGGER IF EXISTS stop_issue_wakeups ON issue;+DROP TRIGGER IF EXISTS capture_comment_wakeup ON comment;+DROP TRIGGER IF EXISTS capture_task_wakeup ON agent_task_queue;+DROP FUNCTION IF EXISTS stop_issue_wakeups();+DROP FUNCTION IF EXISTS capture_comment_wakeup();+DROP FUNCTION IF EXISTS capture_task_wakeup();+DROP FUNCTION IF EXISTS capture_issue_wakeup(uuid,text,text,uuid,uuid,jsonb);diff --git a/server/migrations/518_wakeup_event_capture.up.sql b/server/migrations/518_wakeup_event_capture.up.sqlnew file mode 100644index 0000000000..2732c77071--- /dev/null+++ b/server/migrations/518_wakeup_event_capture.up.sql@@ -0,0 +1,57 @@+-- Capture only matching wakeup inputs, in the source write's transaction.+-- This is not an event history: receipts are consumed by the normal task queue.+CREATE FUNCTION capture_issue_wakeup(p_issue uuid, p_type text, p_key text, p_agent uuid, p_task uuid, p_payload jsonb)+RETURNS void LANGUAGE plpgsql AS $$+DECLARE w issue_wakeup;+BEGIN+ FOR w IN SELECT * FROM issue_wakeup WHERE issue_id=p_issue AND enabled AND kind='event'+ AND p_type=ANY(event_types) AND (filter_agent_id IS NULL OR filter_agent_id=p_agent)+ AND (filter_task_id IS NULL OR filter_task_id=p_task)+ AND NOT EXISTS (SELECT 1 FROM agent_task_queue t WHERE t.id=p_task AND t.context->>'wakeup_id'=issue_wakeup.id::text)+ ORDER BY id+ LOOP+ INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload)+ VALUES(gen_random_uuid(),w.id,w.revision,p_key,p_type,p_payload) ON CONFLICT DO NOTHING;+ END LOOP;+END $$;+CREATE FUNCTION capture_task_wakeup() RETURNS trigger LANGUAGE plpgsql AS $$+BEGIN+ IF NEW.issue_id IS NOT NULL AND NEW.status IS DISTINCT FROM OLD.status AND NEW.status IN ('completed','failed','cancelled') THEN+ PERFORM capture_issue_wakeup(NEW.issue_id,'task.'||NEW.status,NEW.id::text||':'||NEW.status,NEW.agent_id,NEW.id,+ jsonb_build_object('task_id',NEW.id,'agent_id',NEW.agent_id,'status',NEW.status));+ END IF;+ RETURN NEW;+END $$;+CREATE TRIGGER capture_task_wakeup AFTER UPDATE OF status ON agent_task_queue FOR EACH ROW EXECUTE FUNCTION capture_task_wakeup();+CREATE FUNCTION capture_comment_wakeup() RETURNS trigger LANGUAGE plpgsql AS $$+BEGIN+ PERFORM capture_issue_wakeup(NEW.issue_id,'comment.created',NEW.id::text,+ CASE WHEN NEW.author_type='agent' THEN NEW.author_id ELSE NULL END,NEW.source_task_id,+ jsonb_build_object('comment_id',NEW.id,'author_type',NEW.author_type,'author_id',NEW.author_id,'source_task_id',NEW.source_task_id));+ RETURN NEW;+END $$;+CREATE TRIGGER capture_comment_wakeup AFTER INSERT ON comment FOR EACH ROW EXECUTE FUNCTION capture_comment_wakeup();+CREATE FUNCTION stop_issue_wakeups() RETURNS trigger LANGUAGE plpgsql AS $$+DECLARE closing boolean;+BEGIN+ closing := TG_OP='DELETE';+ IF NOT closing THEN+ closing := NEW.status IN ('done','cancelled') OR EXISTS+ (SELECT 1 FROM issue_status s WHERE s.workspace_id=NEW.workspace_id AND s.key=NEW.status AND s.category IN ('done','closed'));+ END IF;+ IF closing THEN+ UPDATE issue_wakeup SET enabled=false,disabled_at=clock_timestamp(),updated_at=clock_timestamp()+ WHERE issue_id=OLD.id AND disabled_at IS NULL;+ UPDATE agent_task_queue SET status='cancelled',completed_at=now(),error='Issue closed; wakeup disabled'+ WHERE issue_id=OLD.id AND context->>'wakeup_id' IS NOT NULL AND status IN ('queued','deferred') AND started_at IS NULL;+ ELSE+ IF NEW.status IS DISTINCT FROM OLD.status THEN+ PERFORM capture_issue_wakeup(NEW.id,'issue.status_changed',NEW.id::text||':'||NEW.revision::text,+ (SELECT agent_id FROM agent_task_queue WHERE id=NULLIF(current_setting('multica.source_task_id',true),'')::uuid),+ NULLIF(current_setting('multica.source_task_id',true),'')::uuid,+ jsonb_build_object('issue_id',NEW.id,'status',NEW.status));+ END IF;+ END IF;+ RETURN COALESCE(NEW,OLD);+END $$;+CREATE TRIGGER stop_issue_wakeups AFTER UPDATE OF status ON issue FOR EACH ROW EXECUTE FUNCTION stop_issue_wakeups();diff --git a/server/migrations/519_wakeup_event_issue.down.sql b/server/migrations/519_wakeup_event_issue.down.sqlnew file mode 100644index 0000000000..91b22aad52--- /dev/null+++ b/server/migrations/519_wakeup_event_issue.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_wakeup_event_issue;diff --git a/server/migrations/519_wakeup_event_issue.up.sql b/server/migrations/519_wakeup_event_issue.up.sqlnew file mode 100644index 0000000000..42d9f5f6de--- /dev/null+++ b/server/migrations/519_wakeup_event_issue.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY idx_wakeup_event_issue ON issue_wakeup(issue_id) WHERE enabled AND kind='event';diff --git a/server/migrations/520_collaboration_wakeup_events.down.sql b/server/migrations/520_collaboration_wakeup_events.down.sqlnew file mode 100644index 0000000000..e497ac3519--- /dev/null+++ b/server/migrations/520_collaboration_wakeup_events.down.sql@@ -0,0 +1,67 @@+DROP TRIGGER capture_issue_collaboration_wakeup ON issue;+DROP TRIGGER capture_issue_label_wakeup ON issue_to_label;+DROP TRIGGER capture_comment_reaction_wakeup ON comment_reaction;+DROP TRIGGER capture_issue_reaction_wakeup ON issue_reaction;+DROP TRIGGER capture_attachment_wakeup ON attachment;+DROP FUNCTION capture_issue_collaboration_wakeup();+DROP FUNCTION capture_issue_label_wakeup();+DROP FUNCTION capture_reaction_wakeup();+DROP FUNCTION capture_attachment_wakeup();+DROP TRIGGER capture_task_wakeup ON agent_task_queue;+DROP TRIGGER capture_comment_wakeup ON comment;+-- Capture only matching wakeup inputs, in the source write's transaction.+-- This is not an event history: receipts are consumed by the normal task queue.+CREATE OR REPLACE FUNCTION capture_issue_wakeup(p_issue uuid, p_type text, p_key text, p_agent uuid, p_task uuid, p_payload jsonb)+RETURNS void LANGUAGE plpgsql AS $$+DECLARE w issue_wakeup;+BEGIN+ FOR w IN SELECT * FROM issue_wakeup WHERE issue_id=p_issue AND enabled AND kind='event'+ AND p_type=ANY(event_types) AND (filter_agent_id IS NULL OR filter_agent_id=p_agent)+ AND (filter_task_id IS NULL OR filter_task_id=p_task)+ AND NOT EXISTS (SELECT 1 FROM agent_task_queue t WHERE t.id=p_task AND t.context->>'wakeup_id'=issue_wakeup.id::text)+ ORDER BY id+ LOOP+ INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload)+ VALUES(gen_random_uuid(),w.id,w.revision,p_key,p_type,p_payload) ON CONFLICT DO NOTHING;+ END LOOP;+END $$;+CREATE OR REPLACE FUNCTION capture_task_wakeup() RETURNS trigger LANGUAGE plpgsql AS $$+BEGIN+ IF NEW.issue_id IS NOT NULL AND NEW.status IS DISTINCT FROM OLD.status AND NEW.status IN ('completed','failed','cancelled') THEN+ PERFORM capture_issue_wakeup(NEW.issue_id,'task.'||NEW.status,NEW.id::text||':'||NEW.status,NEW.agent_id,NEW.id,+ jsonb_build_object('task_id',NEW.id,'agent_id',NEW.agent_id,'status',NEW.status));+ END IF;+ RETURN NEW;+END $$;+CREATE TRIGGER capture_task_wakeup AFTER UPDATE OF status ON agent_task_queue FOR EACH ROW EXECUTE FUNCTION capture_task_wakeup();+CREATE OR REPLACE FUNCTION capture_comment_wakeup() RETURNS trigger LANGUAGE plpgsql AS $$+BEGIN+ PERFORM capture_issue_wakeup(NEW.issue_id,'comment.created',NEW.id::text,+ CASE WHEN NEW.author_type='agent' THEN NEW.author_id ELSE NULL END,NEW.source_task_id,+ jsonb_build_object('comment_id',NEW.id,'author_type',NEW.author_type,'author_id',NEW.author_id,'source_task_id',NEW.source_task_id));+ RETURN NEW;+END $$;+CREATE TRIGGER capture_comment_wakeup AFTER INSERT ON comment FOR EACH ROW EXECUTE FUNCTION capture_comment_wakeup();+CREATE OR REPLACE FUNCTION stop_issue_wakeups() RETURNS trigger LANGUAGE plpgsql AS $$+DECLARE closing boolean;+BEGIN+ closing := TG_OP='DELETE';+ IF NOT closing THEN+ closing := NEW.status IN ('done','cancelled') OR EXISTS+ (SELECT 1 FROM issue_status s WHERE s.workspace_id=NEW.workspace_id AND s.key=NEW.status AND s.category IN ('done','closed'));+ END IF;+ IF closing THEN+ UPDATE issue_wakeup SET enabled=false,disabled_at=clock_timestamp(),updated_at=clock_timestamp()+ WHERE issue_id=OLD.id AND disabled_at IS NULL;+ UPDATE agent_task_queue SET status='cancelled',completed_at=now(),error='Issue closed; wakeup disabled'+ WHERE issue_id=OLD.id AND context->>'wakeup_id' IS NOT NULL AND status IN ('queued','deferred') AND started_at IS NULL;+ ELSE+ IF NEW.status IS DISTINCT FROM OLD.status THEN+ PERFORM capture_issue_wakeup(NEW.id,'issue.status_changed',NEW.id::text||':'||NEW.revision::text,+ (SELECT agent_id FROM agent_task_queue WHERE id=NULLIF(current_setting('multica.source_task_id',true),'')::uuid),+ NULLIF(current_setting('multica.source_task_id',true),'')::uuid,+ jsonb_build_object('issue_id',NEW.id,'status',NEW.status));+ END IF;+ END IF;+ RETURN COALESCE(NEW,OLD);+END $$;diff --git a/server/migrations/520_collaboration_wakeup_events.up.sql b/server/migrations/520_collaboration_wakeup_events.up.sqlnew file mode 100644index 0000000000..ccef5330d2--- /dev/null+++ b/server/migrations/520_collaboration_wakeup_events.up.sql@@ -0,0 +1,211 @@+-- Extend transactional capture without an event archive or a second run lifecycle.+-- Payloads contain references and changed field names, never comment bodies,+-- attachment URLs, or arbitrary metadata values.+CREATE OR REPLACE FUNCTION capture_issue_wakeup(p_issue uuid, p_type text, p_key text, p_agent uuid, p_task uuid, p_payload jsonb)+RETURNS void LANGUAGE plpgsql AS $$+DECLARE w issue_wakeup; owner_workspace uuid; evidence jsonb;+BEGIN+ IF NOT EXISTS (SELECT 1 FROM issue_wakeup WHERE issue_id=p_issue AND enabled AND kind='event' AND p_type=ANY(event_types)) THEN RETURN; END IF;+ IF p_agent IS NULL AND current_setting('multica.actor_type',true)='agent' THEN+ p_agent := NULLIF(current_setting('multica.actor_id',true),'')::uuid;+ END IF;+ SELECT i.workspace_id INTO owner_workspace FROM issue i+ WHERE i.id=p_issue AND i.status NOT IN ('done','cancelled') AND NOT EXISTS+ (SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'));+ IF owner_workspace IS NULL THEN RETURN; END IF;+ evidence := jsonb_build_object('event_id',p_key,'event_type',p_type,'version',1,+ 'occurred_at',clock_timestamp(),'workspace_id',owner_workspace,'issue_id',p_issue,+ 'source_task_id',p_task,'agent_id',p_agent,+ 'actor_type',COALESCE(NULLIF(current_setting('multica.actor_type',true),''),CASE WHEN p_agent IS NOT NULL THEN 'agent' ELSE 'system' END),+ 'actor_id',COALESCE(NULLIF(current_setting('multica.actor_id',true),''),p_agent::text)) || p_payload;+ FOR w IN SELECT * FROM issue_wakeup WHERE issue_id=p_issue AND workspace_id=owner_workspace AND enabled AND kind='event'+ AND p_type=ANY(event_types) AND (filter_agent_id IS NULL OR filter_agent_id=p_agent)+ AND (filter_task_id IS NULL OR filter_task_id=p_task)+ AND NOT EXISTS (SELECT 1 FROM agent_task_queue t WHERE t.id=p_task AND t.context->>'wakeup_id'=issue_wakeup.id::text)+ ORDER BY id+ LOOP+ INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload)+ VALUES(gen_random_uuid(),w.id,w.revision,p_key,p_type,evidence) ON CONFLICT DO NOTHING;+ END LOOP;+END $$;++CREATE OR REPLACE FUNCTION capture_task_wakeup() RETURNS trigger LANGUAGE plpgsql AS $$+DECLARE event_type text; event_key text; old_status text;+BEGIN+ IF NEW.issue_id IS NULL THEN RETURN NEW; END IF;+ IF TG_OP='UPDATE' THEN+ IF NEW.status IS NOT DISTINCT FROM OLD.status THEN RETURN NEW; END IF;+ old_status := OLD.status;+ END IF;+ event_type := CASE NEW.status WHEN 'running' THEN 'task.started' ELSE 'task.'||NEW.status END;+ IF NEW.status NOT IN ('queued','dispatched','running','deferred','waiting_local_directory','completed','failed','cancelled') THEN RETURN NEW; END IF;+ -- Terminal keys also match the locked registration check. Repeated queue /+ -- defer transitions are separate facts and must not share a lifetime key.+ event_key := CASE WHEN NEW.status IN ('completed','failed','cancelled') THEN NEW.id::text||':'||NEW.status ELSE gen_random_uuid()::text END;+ PERFORM capture_issue_wakeup(NEW.issue_id,event_type,event_key,NEW.agent_id,NEW.id,+ jsonb_build_object('task_id',NEW.id,'agent_id',NEW.agent_id,'status',NEW.status,'previous_status',old_status,+ 'retry_of_task_id',NEW.retry_of_task_id,'rerun_of_task_id',NEW.rerun_of_task_id));+ RETURN NEW;+END $$;+DROP TRIGGER capture_task_wakeup ON agent_task_queue;+CREATE TRIGGER capture_task_wakeup AFTER INSERT OR UPDATE OF status ON agent_task_queue FOR EACH ROW EXECUTE FUNCTION capture_task_wakeup();++CREATE OR REPLACE FUNCTION capture_comment_wakeup() RETURNS trigger LANGUAGE plpgsql AS $$+DECLARE c comment; event_type text; source_id uuid; source_agent uuid; payload jsonb; root_id uuid;+BEGIN+ c := CASE WHEN TG_OP='DELETE' THEN OLD ELSE NEW END;+ IF NOT EXISTS (SELECT 1 FROM issue_wakeup WHERE issue_id=c.issue_id AND enabled AND kind='event') THEN RETURN c; END IF;+ source_id := NULLIF(current_setting('multica.source_task_id',true),'')::uuid;+ IF TG_OP='INSERT' THEN+ event_type := 'comment.created';+ source_id := COALESCE(source_id,c.source_task_id);+ source_agent := CASE WHEN c.author_type='agent' THEN c.author_id END;+ ELSIF TG_OP='DELETE' THEN+ -- Pruning an existing tombstone is storage cleanup, not another deletion.+ IF OLD.deleted_at IS NOT NULL THEN RETURN OLD; END IF;+ event_type := 'comment.deleted';+ ELSIF OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL THEN+ event_type := 'comment.deleted';+ ELSIF NEW.deleted_at IS NOT NULL THEN RETURN NEW;+ ELSIF OLD.resolved_at IS NULL AND NEW.resolved_at IS NOT NULL THEN event_type := 'comment.resolved';+ ELSIF OLD.resolved_at IS NOT NULL AND NEW.resolved_at IS NULL THEN event_type := 'comment.unresolved';+ ELSIF NEW.content IS DISTINCT FROM OLD.content THEN event_type := 'comment.updated';+ ELSE RETURN NEW;+ END IF;+ IF source_id IS NOT NULL THEN SELECT agent_id INTO source_agent FROM agent_task_queue WHERE id=source_id; END IF;+ -- Keep author and actor distinct: an admin editing an agent's comment is+ -- not an event produced by that agent's original run.+ IF TG_OP<>'INSERT' AND source_id IS NULL THEN+ source_agent := CASE WHEN current_setting('multica.actor_type',true)='agent' THEN NULLIF(current_setting('multica.actor_id',true),'')::uuid END;+ END IF;+ root_id := c.id;+ IF c.parent_id IS NOT NULL THEN+ WITH RECURSIVE ancestors AS (+ SELECT id,parent_id,1 AS depth FROM comment WHERE id=c.parent_id AND issue_id=c.issue_id AND workspace_id=c.workspace_id+ UNION ALL SELECT p.id,p.parent_id,a.depth+1 FROM comment p JOIN ancestors a ON p.id=a.parent_id+ WHERE p.issue_id=c.issue_id AND p.workspace_id=c.workspace_id AND a.depth<256+ ) SELECT id INTO root_id FROM ancestors ORDER BY depth DESC LIMIT 1;+ END IF;+ payload := jsonb_build_object('comment_id',c.id,'parent_comment_id',c.parent_id,'thread_id',COALESCE(root_id,c.id),+ 'author_type',c.author_type,'author_id',c.author_id);+ IF TG_OP='INSERT' THEN payload := payload || jsonb_build_object('actor_type',c.author_type,'actor_id',c.author_id); END IF;+ PERFORM capture_issue_wakeup(c.issue_id,event_type,gen_random_uuid()::text,source_agent,source_id,payload);+ RETURN c;+END $$;+DROP TRIGGER capture_comment_wakeup ON comment;+CREATE TRIGGER capture_comment_wakeup AFTER INSERT OR UPDATE OR DELETE ON comment FOR EACH ROW EXECUTE FUNCTION capture_comment_wakeup();++-- Closing still wins over every subscription. Capture of non-terminal changes+-- lives in its own trigger so revision-only writes never produce a new input.+CREATE OR REPLACE FUNCTION stop_issue_wakeups() RETURNS trigger LANGUAGE plpgsql AS $$+BEGIN+ IF NEW.status IN ('done','cancelled') OR EXISTS+ (SELECT 1 FROM issue_status s WHERE s.workspace_id=NEW.workspace_id AND s.key=NEW.status AND s.category IN ('done','closed')) THEN+ UPDATE issue_wakeup SET enabled=false,disabled_at=clock_timestamp(),updated_at=clock_timestamp()+ WHERE issue_id=OLD.id AND disabled_at IS NULL;+ UPDATE agent_task_queue SET status='cancelled',completed_at=now(),error='Issue closed; wakeup disabled'+ WHERE issue_id=OLD.id AND context->>'wakeup_id' IS NOT NULL AND status IN ('queued','deferred') AND started_at IS NULL;+ END IF;+ RETURN NEW;+END $$;++CREATE FUNCTION capture_issue_collaboration_wakeup() RETURNS trigger LANGUAGE plpgsql AS $$+DECLARE source_id uuid; source_agent uuid; fields jsonb; field_name text; event_type text;+ before_row jsonb; after_row jsonb; event_key text;+BEGIN+ -- Avoid serializing potentially large issue documents on the ordinary path.+ IF NOT EXISTS (SELECT 1 FROM issue_wakeup WHERE issue_id=NEW.id AND enabled AND kind='event') THEN RETURN NEW; END IF;+ before_row := to_jsonb(OLD); after_row := to_jsonb(NEW); event_key := gen_random_uuid()::text;+ SELECT jsonb_agg(k ORDER BY k) INTO fields FROM unnest(ARRAY[+ 'title','description','status','priority','assignee_type','assignee_id','parent_issue_id','project_id',+ 'due_date','start_date','stage','properties','metadata','acceptance_criteria','context_refs','triage_state']) k+ WHERE before_row->k IS DISTINCT FROM after_row->k;+ IF fields IS NULL THEN RETURN NEW; END IF;+ source_id := NULLIF(current_setting('multica.source_task_id',true),'')::uuid;+ SELECT agent_id INTO source_agent FROM agent_task_queue WHERE id=source_id;+ IF source_agent IS NULL AND current_setting('multica.actor_type',true)='agent' THEN+ source_agent := NULLIF(current_setting('multica.actor_id',true),'')::uuid;+ END IF;+ PERFORM capture_issue_wakeup(NEW.id,'issue.updated',event_key||':updated',source_agent,source_id,jsonb_build_object('changed_fields',fields));+ FOR field_name,event_type IN SELECT * FROM (VALUES+ ('status','issue.status_changed'),('assignee_id','issue.assignee_changed'),+ ('parent_issue_id','issue.parent_changed'),('project_id','issue.project_changed'),+ ('properties','issue.properties_changed'),('metadata','issue.metadata_changed')) v(f,e)+ LOOP+ IF fields ? field_name OR (field_name='assignee_id' AND fields ? 'assignee_type') THEN+ PERFORM capture_issue_wakeup(NEW.id,event_type,event_key||':'||field_name,source_agent,source_id,+ CASE WHEN field_name IN ('metadata','properties') THEN+ jsonb_build_object('changed_fields',(SELECT jsonb_agg(k ORDER BY k) FROM+ (SELECT jsonb_object_keys(before_row->field_name) k UNION SELECT jsonb_object_keys(after_row->field_name)) keys+ WHERE (before_row->field_name)->k IS DISTINCT FROM (after_row->field_name)->k))+ WHEN field_name='status' THEN jsonb_build_object('previous_status',OLD.status,'status',NEW.status,+ 'previous_category',(SELECT category FROM issue_status WHERE workspace_id=OLD.workspace_id AND key=OLD.status),+ 'category',(SELECT category FROM issue_status WHERE workspace_id=NEW.workspace_id AND key=NEW.status))+ WHEN field_name='assignee_id' THEN jsonb_build_object('previous_assignee_id',OLD.assignee_id,'assignee_id',NEW.assignee_id,+ 'previous_assignee_type',OLD.assignee_type,'assignee_type',NEW.assignee_type)+ ELSE jsonb_build_object('previous_'||field_name,before_row->field_name,field_name,after_row->field_name) END);+ END IF;+ END LOOP;+ RETURN NEW;+END $$;+CREATE TRIGGER capture_issue_collaboration_wakeup AFTER UPDATE ON issue FOR EACH ROW EXECUTE FUNCTION capture_issue_collaboration_wakeup();++CREATE FUNCTION capture_issue_label_wakeup() RETURNS trigger LANGUAGE plpgsql AS $$+DECLARE row_data jsonb := CASE WHEN TG_OP='DELETE' THEN to_jsonb(OLD) ELSE to_jsonb(NEW) END; source_id uuid; source_agent uuid;+BEGIN+ source_id := NULLIF(current_setting('multica.source_task_id',true),'')::uuid;+ SELECT agent_id INTO source_agent FROM agent_task_queue WHERE id=source_id;+ PERFORM capture_issue_wakeup((row_data->>'issue_id')::uuid,'issue.labels_changed',gen_random_uuid()::text,source_agent,source_id,+ jsonb_build_object('label_id',row_data->'label_id','action',CASE WHEN TG_OP='INSERT' THEN 'added' ELSE 'removed' END));+ RETURN COALESCE(NEW,OLD);+END $$;+CREATE TRIGGER capture_issue_label_wakeup AFTER INSERT OR DELETE ON issue_to_label FOR EACH ROW EXECUTE FUNCTION capture_issue_label_wakeup();++CREATE FUNCTION capture_reaction_wakeup() RETURNS trigger LANGUAGE plpgsql AS $$+DECLARE row_data jsonb := CASE WHEN TG_OP='DELETE' THEN to_jsonb(OLD) ELSE to_jsonb(NEW) END;+ owner_issue uuid; source_id uuid; source_agent uuid; target_type text; target_id uuid; payload jsonb;+BEGIN+ IF TG_TABLE_NAME='comment_reaction' THEN+ target_type := 'comment'; target_id := (row_data->>'comment_id')::uuid;+ SELECT issue_id INTO owner_issue FROM comment WHERE id=target_id AND workspace_id=(row_data->>'workspace_id')::uuid;+ ELSE target_type := 'issue'; target_id := (row_data->>'issue_id')::uuid; owner_issue := target_id;+ END IF;+ source_id := NULLIF(current_setting('multica.source_task_id',true),'')::uuid;+ IF source_id IS NOT NULL THEN SELECT agent_id INTO source_agent FROM agent_task_queue WHERE id=source_id;+ ELSIF TG_OP='INSERT' AND row_data->>'actor_type'='agent' THEN source_agent := (row_data->>'actor_id')::uuid;+ END IF;+ payload := jsonb_build_object('reaction_id',row_data->'id','target_type',target_type,'target_id',target_id,'emoji',row_data->'emoji',+ 'reaction_actor_type',row_data->'actor_type','reaction_actor_id',row_data->'actor_id');+ IF TG_OP='INSERT' THEN payload := payload || jsonb_build_object('actor_type',row_data->'actor_type','actor_id',row_data->'actor_id'); END IF;+ PERFORM capture_issue_wakeup(owner_issue,CASE WHEN TG_OP='INSERT' THEN 'reaction.added' ELSE 'reaction.removed' END,+ gen_random_uuid()::text,source_agent,source_id,payload);+ RETURN COALESCE(NEW,OLD);+END $$;+CREATE TRIGGER capture_comment_reaction_wakeup AFTER INSERT OR DELETE ON comment_reaction FOR EACH ROW EXECUTE FUNCTION capture_reaction_wakeup();+CREATE TRIGGER capture_issue_reaction_wakeup AFTER INSERT OR DELETE ON issue_reaction FOR EACH ROW EXECUTE FUNCTION capture_reaction_wakeup();++CREATE FUNCTION capture_attachment_wakeup() RETURNS trigger LANGUAGE plpgsql AS $$+DECLARE before_row jsonb; after_row jsonb; row_data jsonb; before_target uuid; after_target uuid;+ target_type text; source_id uuid; source_agent uuid; owner_issue uuid; event_type text;+BEGIN+ IF TG_OP<>'INSERT' THEN before_row:=to_jsonb(OLD); before_target:=COALESCE(OLD.comment_id,OLD.issue_id); END IF;+ IF TG_OP<>'DELETE' THEN after_row:=to_jsonb(NEW); after_target:=COALESCE(NEW.comment_id,NEW.issue_id); END IF;+ IF before_target IS NOT DISTINCT FROM after_target THEN RETURN COALESCE(NEW,OLD); END IF;+ source_id := NULLIF(current_setting('multica.source_task_id',true),'')::uuid;+ SELECT agent_id INTO source_agent FROM agent_task_queue WHERE id=source_id;+ FOR row_data,event_type IN SELECT * FROM (VALUES (before_row,'attachment.detached'),(after_row,'attachment.attached')) v(r,e)+ LOOP+ -- Source-context snapshots and chat attachments are outside this issue contract.+ IF row_data IS NULL OR row_data->>'source_context_id' IS NOT NULL OR row_data->>'chat_session_id' IS NOT NULL THEN CONTINUE; END IF;+ owner_issue := (row_data->>'issue_id')::uuid;+ target_type := CASE WHEN row_data->>'comment_id' IS NOT NULL THEN 'comment' ELSE 'issue' END;+ IF target_type='comment' THEN+ SELECT issue_id INTO owner_issue FROM comment WHERE id=(row_data->>'comment_id')::uuid AND workspace_id=(row_data->>'workspace_id')::uuid;+ END IF;+ PERFORM capture_issue_wakeup(owner_issue,event_type,gen_random_uuid()::text,source_agent,source_id,+ jsonb_build_object('attachment_id',row_data->'id','target_type',target_type,+ 'target_id',COALESCE(row_data->>'comment_id',row_data->>'issue_id')));+ END LOOP;+ RETURN COALESCE(NEW,OLD);+END $$;+CREATE TRIGGER capture_attachment_wakeup AFTER INSERT OR UPDATE OF issue_id,comment_id OR DELETE ON attachment FOR EACH ROW EXECUTE FUNCTION capture_attachment_wakeup();diff --git a/server/migrations/521_wakeup_workspace_summary.down.sql b/server/migrations/521_wakeup_workspace_summary.down.sqlnew file mode 100644index 0000000000..6cd0f3f5dd--- /dev/null+++ b/server/migrations/521_wakeup_workspace_summary.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_wakeup_workspace_enabled;diff --git a/server/migrations/521_wakeup_workspace_summary.up.sql b/server/migrations/521_wakeup_workspace_summary.up.sqlnew file mode 100644index 0000000000..dc1de83c41--- /dev/null+++ b/server/migrations/521_wakeup_workspace_summary.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY idx_wakeup_workspace_enabled ON issue_wakeup(workspace_id,issue_id) WHERE enabled;diff --git a/server/migrations/522_wakeup_run_lookup.down.sql b/server/migrations/522_wakeup_run_lookup.down.sqlnew file mode 100644index 0000000000..36344bd87c--- /dev/null+++ b/server/migrations/522_wakeup_run_lookup.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS agent_task_wakeup_lookup_idx;diff --git a/server/migrations/522_wakeup_run_lookup.up.sql b/server/migrations/522_wakeup_run_lookup.up.sqlnew file mode 100644index 0000000000..2844717931--- /dev/null+++ b/server/migrations/522_wakeup_run_lookup.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS agent_task_wakeup_lookup_idx ON agent_task_queue ((context->>'wakeup_id'),created_at DESC) WHERE context->>'wakeup_id' IS NOT NULL;diff --git a/server/migrations/523_wakeup_registration_source.down.sql b/server/migrations/523_wakeup_registration_source.down.sqlnew file mode 100644index 0000000000..b5eaf190c6--- /dev/null+++ b/server/migrations/523_wakeup_registration_source.down.sql@@ -0,0 +1,30 @@+-- Extend transactional capture without an event archive or a second run lifecycle.+-- Payloads contain references and changed field names, never comment bodies,+-- attachment URLs, or arbitrary metadata values.+CREATE OR REPLACE FUNCTION capture_issue_wakeup(p_issue uuid, p_type text, p_key text, p_agent uuid, p_task uuid, p_payload jsonb)+RETURNS void LANGUAGE plpgsql AS $$+DECLARE w issue_wakeup; owner_workspace uuid; evidence jsonb;+BEGIN+ IF NOT EXISTS (SELECT 1 FROM issue_wakeup WHERE issue_id=p_issue AND enabled AND kind='event' AND p_type=ANY(event_types)) THEN RETURN; END IF;+ IF p_agent IS NULL AND current_setting('multica.actor_type',true)='agent' THEN+ p_agent := NULLIF(current_setting('multica.actor_id',true),'')::uuid;+ END IF;+ SELECT i.workspace_id INTO owner_workspace FROM issue i+ WHERE i.id=p_issue AND i.status NOT IN ('done','cancelled') AND NOT EXISTS+ (SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'));+ IF owner_workspace IS NULL THEN RETURN; END IF;+ evidence := jsonb_build_object('event_id',p_key,'event_type',p_type,'version',1,+ 'occurred_at',clock_timestamp(),'workspace_id',owner_workspace,'issue_id',p_issue,+ 'source_task_id',p_task,'agent_id',p_agent,+ 'actor_type',COALESCE(NULLIF(current_setting('multica.actor_type',true),''),CASE WHEN p_agent IS NOT NULL THEN 'agent' ELSE 'system' END),+ 'actor_id',COALESCE(NULLIF(current_setting('multica.actor_id',true),''),p_agent::text)) || p_payload;+ FOR w IN SELECT * FROM issue_wakeup WHERE issue_id=p_issue AND workspace_id=owner_workspace AND enabled AND kind='event'+ AND p_type=ANY(event_types) AND (filter_agent_id IS NULL OR filter_agent_id=p_agent)+ AND (filter_task_id IS NULL OR filter_task_id=p_task)+ AND NOT EXISTS (SELECT 1 FROM agent_task_queue t WHERE t.id=p_task AND t.context->>'wakeup_id'=issue_wakeup.id::text)+ ORDER BY id+ LOOP+ INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload)+ VALUES(gen_random_uuid(),w.id,w.revision,p_key,p_type,evidence) ON CONFLICT DO NOTHING;+ END LOOP;+END $$;diff --git a/server/migrations/523_wakeup_registration_source.up.sql b/server/migrations/523_wakeup_registration_source.up.sqlnew file mode 100644index 0000000000..b7c37ee34b--- /dev/null+++ b/server/migrations/523_wakeup_registration_source.up.sql@@ -0,0 +1,32 @@+-- Ignore events emitted by the run that registered this subscription.+-- Extend transactional capture without an event archive or a second run lifecycle.+-- Payloads contain references and changed field names, never comment bodies,+-- attachment URLs, or arbitrary metadata values.+CREATE OR REPLACE FUNCTION capture_issue_wakeup(p_issue uuid, p_type text, p_key text, p_agent uuid, p_task uuid, p_payload jsonb)+RETURNS void LANGUAGE plpgsql AS $$+DECLARE w issue_wakeup; owner_workspace uuid; evidence jsonb;+BEGIN+ IF NOT EXISTS (SELECT 1 FROM issue_wakeup WHERE issue_id=p_issue AND enabled AND kind='event' AND p_type=ANY(event_types)) THEN RETURN; END IF;+ IF p_agent IS NULL AND current_setting('multica.actor_type',true)='agent' THEN+ p_agent := NULLIF(current_setting('multica.actor_id',true),'')::uuid;+ END IF;+ SELECT i.workspace_id INTO owner_workspace FROM issue i+ WHERE i.id=p_issue AND i.status NOT IN ('done','cancelled') AND NOT EXISTS+ (SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'));+ IF owner_workspace IS NULL THEN RETURN; END IF;+ evidence := jsonb_build_object('event_id',p_key,'event_type',p_type,'version',1,+ 'occurred_at',clock_timestamp(),'workspace_id',owner_workspace,'issue_id',p_issue,+ 'source_task_id',p_task,'agent_id',p_agent,+ 'actor_type',COALESCE(NULLIF(current_setting('multica.actor_type',true),''),CASE WHEN p_agent IS NOT NULL THEN 'agent' ELSE 'system' END),+ 'actor_id',COALESCE(NULLIF(current_setting('multica.actor_id',true),''),p_agent::text)) || p_payload;+ FOR w IN SELECT * FROM issue_wakeup WHERE issue_id=p_issue AND workspace_id=owner_workspace AND enabled AND kind='event'+ AND p_type=ANY(event_types) AND (filter_agent_id IS NULL OR filter_agent_id=p_agent)+ AND (filter_task_id IS NULL OR filter_task_id=p_task)+ AND (p_task IS NULL OR source_task_id IS DISTINCT FROM p_task)+ AND NOT EXISTS (SELECT 1 FROM agent_task_queue t WHERE t.id=p_task AND t.context->>'wakeup_id'=issue_wakeup.id::text)+ ORDER BY id+ LOOP+ INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload)+ VALUES(gen_random_uuid(),w.id,w.revision,p_key,p_type,evidence) ON CONFLICT DO NOTHING;+ END LOOP;+END $$;diff --git a/server/migrations/524_wakeup_workspace_history.down.sql b/server/migrations/524_wakeup_workspace_history.down.sqlnew file mode 100644index 0000000000..f96860ec44--- /dev/null+++ b/server/migrations/524_wakeup_workspace_history.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS issue_wakeup_workspace_history_idx;diff --git a/server/migrations/524_wakeup_workspace_history.up.sql b/server/migrations/524_wakeup_workspace_history.up.sqlnew file mode 100644index 0000000000..4510047bed--- /dev/null+++ b/server/migrations/524_wakeup_workspace_history.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY issue_wakeup_workspace_history_idx ON issue_wakeup(workspace_id,created_at DESC,id DESC);diff --git a/server/migrations/525_wakeup_active_runs.down.sql b/server/migrations/525_wakeup_active_runs.down.sqlnew file mode 100644index 0000000000..1758a0c01c--- /dev/null+++ b/server/migrations/525_wakeup_active_runs.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS agent_task_wakeup_active_idx;diff --git a/server/migrations/525_wakeup_active_runs.up.sql b/server/migrations/525_wakeup_active_runs.up.sqlnew file mode 100644index 0000000000..1cbd46f129--- /dev/null+++ b/server/migrations/525_wakeup_active_runs.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY agent_task_wakeup_active_idx ON agent_task_queue ((context->>'wakeup_id'), (status IN ('running','waiting_local_directory','dispatched')) DESC,created_at DESC,id DESC) WHERE context->>'wakeup_id' IS NOT NULL AND status IN ('queued','deferred','dispatched','running','waiting_local_directory');diff --git a/server/migrations/526_wakeup_terminal_runs.down.sql b/server/migrations/526_wakeup_terminal_runs.down.sqlnew file mode 100644index 0000000000..4e16e56c5b--- /dev/null+++ b/server/migrations/526_wakeup_terminal_runs.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS agent_task_wakeup_terminal_idx;diff --git a/server/migrations/526_wakeup_terminal_runs.up.sql b/server/migrations/526_wakeup_terminal_runs.up.sqlnew file mode 100644index 0000000000..6c015f3524--- /dev/null+++ b/server/migrations/526_wakeup_terminal_runs.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY agent_task_wakeup_terminal_idx ON agent_task_queue ((context->>'wakeup_id'),created_at DESC,id DESC) WHERE context->>'wakeup_id' IS NOT NULL AND status NOT IN ('queued','deferred','dispatched','running','waiting_local_directory');diff --git a/server/migrations/527_wakeup_receipt_expiry.down.sql b/server/migrations/527_wakeup_receipt_expiry.down.sqlnew file mode 100644index 0000000000..814f9ec3a0--- /dev/null+++ b/server/migrations/527_wakeup_receipt_expiry.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS issue_wakeup_receipt_expiry_idx;diff --git a/server/migrations/527_wakeup_receipt_expiry.up.sql b/server/migrations/527_wakeup_receipt_expiry.up.sqlnew file mode 100644index 0000000000..89ab6e9ae7--- /dev/null+++ b/server/migrations/527_wakeup_receipt_expiry.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY issue_wakeup_receipt_expiry_idx ON issue_wakeup_receipt(processed_at,id) WHERE processed_at IS NOT NULL;diff --git a/server/migrations/528_wakeup_receipt_coalescing.down.sql b/server/migrations/528_wakeup_receipt_coalescing.down.sqlnew file mode 100644index 0000000000..0eb9447692--- /dev/null+++ b/server/migrations/528_wakeup_receipt_coalescing.down.sql@@ -0,0 +1 @@+ALTER TABLE issue_wakeup_receipt DROP COLUMN coalesce_key;diff --git a/server/migrations/528_wakeup_receipt_coalescing.up.sql b/server/migrations/528_wakeup_receipt_coalescing.up.sqlnew file mode 100644index 0000000000..a37c431cfd--- /dev/null+++ b/server/migrations/528_wakeup_receipt_coalescing.up.sql@@ -0,0 +1,2 @@+-- Existing receipts retain their original evidence and drain normally.+ALTER TABLE issue_wakeup_receipt ADD COLUMN coalesce_key text;diff --git a/server/migrations/529_wakeup_pending_event.down.sql b/server/migrations/529_wakeup_pending_event.down.sqlnew file mode 100644index 0000000000..8a2260441b--- /dev/null+++ b/server/migrations/529_wakeup_pending_event.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS issue_wakeup_pending_event_idx;diff --git a/server/migrations/529_wakeup_pending_event.up.sql b/server/migrations/529_wakeup_pending_event.up.sqlnew file mode 100644index 0000000000..87071815eb--- /dev/null+++ b/server/migrations/529_wakeup_pending_event.up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX CONCURRENTLY issue_wakeup_pending_event_idx ON issue_wakeup_receipt(wakeup_id,revision,coalesce_key) WHERE processed_at IS NULL AND coalesce_key IS NOT NULL;diff --git a/server/migrations/530_wakeup_bounded_capture.down.sql b/server/migrations/530_wakeup_bounded_capture.down.sqlnew file mode 100644index 0000000000..ea5d7cbe57--- /dev/null+++ b/server/migrations/530_wakeup_bounded_capture.down.sql@@ -0,0 +1,34 @@+DROP TRIGGER IF EXISTS guard_issue_wakeup_capacity ON issue_wakeup;+DROP FUNCTION IF EXISTS guard_issue_wakeup_capacity();+-- Ignore events emitted by the run that registered this subscription.+-- Extend transactional capture without an event archive or a second run lifecycle.+-- Payloads contain references and changed field names, never comment bodies,+-- attachment URLs, or arbitrary metadata values.+CREATE OR REPLACE FUNCTION capture_issue_wakeup(p_issue uuid, p_type text, p_key text, p_agent uuid, p_task uuid, p_payload jsonb)+RETURNS void LANGUAGE plpgsql AS $$+DECLARE w issue_wakeup; owner_workspace uuid; evidence jsonb;+BEGIN+ IF NOT EXISTS (SELECT 1 FROM issue_wakeup WHERE issue_id=p_issue AND enabled AND kind='event' AND p_type=ANY(event_types)) THEN RETURN; END IF;+ IF p_agent IS NULL AND current_setting('multica.actor_type',true)='agent' THEN+ p_agent := NULLIF(current_setting('multica.actor_id',true),'')::uuid;+ END IF;+ SELECT i.workspace_id INTO owner_workspace FROM issue i+ WHERE i.id=p_issue AND i.status NOT IN ('done','cancelled') AND NOT EXISTS+ (SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'));+ IF owner_workspace IS NULL THEN RETURN; END IF;+ evidence := jsonb_build_object('event_id',p_key,'event_type',p_type,'version',1,+ 'occurred_at',clock_timestamp(),'workspace_id',owner_workspace,'issue_id',p_issue,+ 'source_task_id',p_task,'agent_id',p_agent,+ 'actor_type',COALESCE(NULLIF(current_setting('multica.actor_type',true),''),CASE WHEN p_agent IS NOT NULL THEN 'agent' ELSE 'system' END),+ 'actor_id',COALESCE(NULLIF(current_setting('multica.actor_id',true),''),p_agent::text)) || p_payload;+ FOR w IN SELECT * FROM issue_wakeup WHERE issue_id=p_issue AND workspace_id=owner_workspace AND enabled AND kind='event'+ AND p_type=ANY(event_types) AND (filter_agent_id IS NULL OR filter_agent_id=p_agent)+ AND (filter_task_id IS NULL OR filter_task_id=p_task)+ AND (p_task IS NULL OR source_task_id IS DISTINCT FROM p_task)+ AND NOT EXISTS (SELECT 1 FROM agent_task_queue t WHERE t.id=p_task AND t.context->>'wakeup_id'=issue_wakeup.id::text)+ ORDER BY id+ LOOP+ INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload)+ VALUES(gen_random_uuid(),w.id,w.revision,p_key,p_type,evidence) ON CONFLICT DO NOTHING;+ END LOOP;+END $$;diff --git a/server/migrations/530_wakeup_bounded_capture.up.sql b/server/migrations/530_wakeup_bounded_capture.up.sqlnew file mode 100644index 0000000000..e9f0aa4601--- /dev/null+++ b/server/migrations/530_wakeup_bounded_capture.up.sql@@ -0,0 +1,69 @@+-- Ignore events emitted by the run that registered this subscription.+-- Extend transactional capture without an event archive or a second run lifecycle.+-- Payloads contain references and changed field names, never comment bodies,+-- attachment URLs, or arbitrary metadata values.+CREATE OR REPLACE FUNCTION capture_issue_wakeup(p_issue uuid, p_type text, p_key text, p_agent uuid, p_task uuid, p_payload jsonb)+RETURNS void LANGUAGE plpgsql AS $$+DECLARE w issue_wakeup; owner_workspace uuid; evidence jsonb; violated_constraint text;+BEGIN+ IF NOT EXISTS (SELECT 1 FROM issue_wakeup WHERE issue_id=p_issue AND enabled AND kind='event' AND p_type=ANY(event_types)) THEN RETURN; END IF;+ IF p_agent IS NULL AND current_setting('multica.actor_type',true)='agent' THEN+ p_agent := NULLIF(current_setting('multica.actor_id',true),'')::uuid;+ END IF;+ SELECT i.workspace_id INTO owner_workspace FROM issue i+ WHERE i.id=p_issue AND i.status NOT IN ('done','cancelled') AND NOT EXISTS+ (SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'));+ IF owner_workspace IS NULL THEN RETURN; END IF;+ evidence := jsonb_build_object('event_id',p_key,'event_type',p_type,'version',1,+ 'occurred_at',clock_timestamp(),'workspace_id',owner_workspace,'issue_id',p_issue,+ 'source_task_id',p_task,'agent_id',p_agent,+ 'actor_type',COALESCE(NULLIF(current_setting('multica.actor_type',true),''),CASE WHEN p_agent IS NOT NULL THEN 'agent' ELSE 'system' END),+ 'actor_id',COALESCE(NULLIF(current_setting('multica.actor_id',true),''),p_agent::text)) || p_payload;+ FOR w IN SELECT * FROM issue_wakeup WHERE issue_id=p_issue AND workspace_id=owner_workspace AND enabled AND kind='event'+ AND p_type=ANY(event_types) AND (filter_agent_id IS NULL OR filter_agent_id=p_agent)+ AND (filter_task_id IS NULL OR filter_task_id=p_task)+ AND (p_task IS NULL OR source_task_id IS DISTINCT FROM p_task)+ AND NOT EXISTS (SELECT 1 FROM agent_task_queue t WHERE t.id=p_task AND t.context->>'wakeup_id'=issue_wakeup.id::text)+ ORDER BY id+ LOOP+ -- One pending notification per event type. Preserve the first key for+ -- duplicate suppression and the latest source reference for state reads.+ BEGIN+ INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload,coalesce_key)+ VALUES(gen_random_uuid(),w.id,w.revision,p_key,p_type,+ evidence || jsonb_build_object('coalesced_count',1,'first_occurred_at',evidence->'occurred_at'),p_type)+ ON CONFLICT(wakeup_id,revision,coalesce_key) WHERE processed_at IS NULL AND coalesce_key IS NOT NULL+ -- Rotate the receipt identity on merge. An older dispatcher that read+ -- without FOR UPDATE can only consume its observed version, leaving the+ -- replacement pending instead of silently consuming unseen evidence.+ DO UPDATE SET id=EXCLUDED.id,payload=EXCLUDED.payload || jsonb_build_object(+ 'coalesced_count',COALESCE((issue_wakeup_receipt.payload->>'coalesced_count')::bigint,1)+1,+ 'first_occurred_at',issue_wakeup_receipt.payload->'first_occurred_at')+ WHERE issue_wakeup_receipt.event_key<>p_key AND issue_wakeup_receipt.payload->>'event_id' IS DISTINCT FROM p_key;+ EXCEPTION WHEN unique_violation THEN+ GET STACKED DIAGNOSTICS violated_constraint = CONSTRAINT_NAME;+ -- A retained receipt already handled this exact source fact. This also+ -- fences the locked registration snapshot against terminal-task capture.+ IF violated_constraint <> 'issue_wakeup_receipt_key_idx' THEN RAISE; END IF;+ END;++ END LOOP;+END $$;++-- Serialize only rule activation, not source events or normal dispatch.+-- 32 rules cover all 25 current event types plus time schedules on one issue;+-- 1000/workspace bounds fanout and scheduler load without limiting history.+CREATE FUNCTION guard_issue_wakeup_capacity() RETURNS trigger LANGUAGE plpgsql AS $$+BEGIN+ IF NOT NEW.enabled THEN RETURN NEW; END IF;+ IF TG_OP='UPDATE' AND OLD.enabled AND OLD.issue_id=NEW.issue_id AND OLD.workspace_id=NEW.workspace_id THEN RETURN NEW; END IF;+ PERFORM pg_advisory_xact_lock(hashtextextended('issue-wakeup-capacity:'||NEW.workspace_id::text,0));+ IF (SELECT count(*) FROM (SELECT 1 FROM issue_wakeup WHERE workspace_id=NEW.workspace_id AND issue_id=NEW.issue_id AND enabled AND id<>NEW.id LIMIT 32) slots)>=32 THEN+ RAISE EXCEPTION 'An issue can have at most 32 enabled wakeups' USING ERRCODE='23514',CONSTRAINT='issue_wakeup_active_limit';+ END IF;+ IF (SELECT count(*) FROM (SELECT 1 FROM issue_wakeup WHERE workspace_id=NEW.workspace_id AND enabled AND id<>NEW.id LIMIT 1000) slots)>=1000 THEN+ RAISE EXCEPTION 'A workspace can have at most 1000 enabled wakeups' USING ERRCODE='23514',CONSTRAINT='issue_wakeup_active_limit';+ END IF;+ RETURN NEW;+END $$;+CREATE TRIGGER guard_issue_wakeup_capacity BEFORE INSERT OR UPDATE OF enabled,issue_id,workspace_id ON issue_wakeup FOR EACH ROW EXECUTE FUNCTION guard_issue_wakeup_capacity();diff --git a/server/migrations/531_wakeup_actor_filter.down.sql b/server/migrations/531_wakeup_actor_filter.down.sqlnew file mode 100644index 0000000000..1250fee54a--- /dev/null+++ b/server/migrations/531_wakeup_actor_filter.down.sql@@ -0,0 +1,9 @@+-- Removing the filter function while rules still reference actors would widen+-- subscriptions. Retain the additive schema on application rollback, or first+-- disable/drain and remove these configurations before schema rollback.+DO $$ BEGIN+ IF EXISTS(SELECT 1 FROM issue_wakeup WHERE filter_actor_type IS NOT NULL) THEN+ RAISE EXCEPTION 'Remove actor-filtered wakeups before rolling back actor subscription support';+ END IF;+END $$;+ALTER TABLE issue_wakeup DROP CONSTRAINT issue_wakeup_actor_filter, DROP COLUMN filter_actor_id, DROP COLUMN filter_actor_type;diff --git a/server/migrations/531_wakeup_actor_filter.up.sql b/server/migrations/531_wakeup_actor_filter.up.sqlnew file mode 100644index 0000000000..8c8d6061f8--- /dev/null+++ b/server/migrations/531_wakeup_actor_filter.up.sql@@ -0,0 +1,7 @@+ALTER TABLE issue_wakeup+ ADD COLUMN filter_actor_type text,+ ADD COLUMN filter_actor_id uuid,+ ADD CONSTRAINT issue_wakeup_actor_filter CHECK (+ (filter_actor_type IS NULL AND filter_actor_id IS NULL) OR+ (filter_actor_type IS NOT NULL AND filter_actor_type IN ('member','agent') AND filter_actor_id IS NOT NULL AND kind='event')+ ) NOT VALID;diff --git a/server/migrations/532_wakeup_actor_capture.down.sql b/server/migrations/532_wakeup_actor_capture.down.sqlnew file mode 100644index 0000000000..858f762804--- /dev/null+++ b/server/migrations/532_wakeup_actor_capture.down.sql@@ -0,0 +1,59 @@+-- Removing the filter function while rules still reference actors would widen+-- subscriptions. Retain the additive schema on application rollback, or first+-- disable/drain and remove these configurations before schema rollback.+DO $$ BEGIN+ IF EXISTS(SELECT 1 FROM issue_wakeup WHERE filter_actor_type IS NOT NULL) THEN+ RAISE EXCEPTION 'Remove actor-filtered wakeups before rolling back actor subscription support';+ END IF;+END $$;+-- Ignore events emitted by the run that registered this subscription.+-- Extend transactional capture without an event archive or a second run lifecycle.+-- Payloads contain references and changed field names, never comment bodies,+-- attachment URLs, or arbitrary metadata values.+CREATE OR REPLACE FUNCTION capture_issue_wakeup(p_issue uuid, p_type text, p_key text, p_agent uuid, p_task uuid, p_payload jsonb)+RETURNS void LANGUAGE plpgsql AS $$+DECLARE w issue_wakeup; owner_workspace uuid; evidence jsonb; violated_constraint text;+BEGIN+ IF NOT EXISTS (SELECT 1 FROM issue_wakeup WHERE issue_id=p_issue AND enabled AND kind='event' AND p_type=ANY(event_types)) THEN RETURN; END IF;+ IF p_agent IS NULL AND current_setting('multica.actor_type',true)='agent' THEN+ p_agent := NULLIF(current_setting('multica.actor_id',true),'')::uuid;+ END IF;+ SELECT i.workspace_id INTO owner_workspace FROM issue i+ WHERE i.id=p_issue AND i.status NOT IN ('done','cancelled') AND NOT EXISTS+ (SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'));+ IF owner_workspace IS NULL THEN RETURN; END IF;+ evidence := jsonb_build_object('event_id',p_key,'event_type',p_type,'version',1,+ 'occurred_at',clock_timestamp(),'workspace_id',owner_workspace,'issue_id',p_issue,+ 'source_task_id',p_task,'agent_id',p_agent,+ 'actor_type',COALESCE(NULLIF(current_setting('multica.actor_type',true),''),CASE WHEN p_agent IS NOT NULL THEN 'agent' ELSE 'system' END),+ 'actor_id',COALESCE(NULLIF(current_setting('multica.actor_id',true),''),p_agent::text)) || p_payload;+ FOR w IN SELECT * FROM issue_wakeup WHERE issue_id=p_issue AND workspace_id=owner_workspace AND enabled AND kind='event'+ AND p_type=ANY(event_types) AND (filter_agent_id IS NULL OR filter_agent_id=p_agent)+ AND (filter_task_id IS NULL OR filter_task_id=p_task)+ AND (p_task IS NULL OR source_task_id IS DISTINCT FROM p_task)+ AND NOT EXISTS (SELECT 1 FROM agent_task_queue t WHERE t.id=p_task AND t.context->>'wakeup_id'=issue_wakeup.id::text)+ ORDER BY id+ LOOP+ -- One pending notification per event type. Preserve the first key for+ -- duplicate suppression and the latest source reference for state reads.+ BEGIN+ INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload,coalesce_key)+ VALUES(gen_random_uuid(),w.id,w.revision,p_key,p_type,+ evidence || jsonb_build_object('coalesced_count',1,'first_occurred_at',evidence->'occurred_at'),p_type)+ ON CONFLICT(wakeup_id,revision,coalesce_key) WHERE processed_at IS NULL AND coalesce_key IS NOT NULL+ -- Rotate the receipt identity on merge. An older dispatcher that read+ -- without FOR UPDATE can only consume its observed version, leaving the+ -- replacement pending instead of silently consuming unseen evidence.+ DO UPDATE SET id=EXCLUDED.id,payload=EXCLUDED.payload || jsonb_build_object(+ 'coalesced_count',COALESCE((issue_wakeup_receipt.payload->>'coalesced_count')::bigint,1)+1,+ 'first_occurred_at',issue_wakeup_receipt.payload->'first_occurred_at')+ WHERE issue_wakeup_receipt.event_key<>p_key AND issue_wakeup_receipt.payload->>'event_id' IS DISTINCT FROM p_key;+ EXCEPTION WHEN unique_violation THEN+ GET STACKED DIAGNOSTICS violated_constraint = CONSTRAINT_NAME;+ -- A retained receipt already handled this exact source fact. This also+ -- fences the locked registration snapshot against terminal-task capture.+ IF violated_constraint <> 'issue_wakeup_receipt_key_idx' THEN RAISE; END IF;+ END;++ END LOOP;+END $$;diff --git a/server/migrations/532_wakeup_actor_capture.up.sql b/server/migrations/532_wakeup_actor_capture.up.sqlnew file mode 100644index 0000000000..e11a3ea58c--- /dev/null+++ b/server/migrations/532_wakeup_actor_capture.up.sql@@ -0,0 +1,53 @@+-- Ignore events emitted by the run that registered this subscription.+-- Extend transactional capture without an event archive or a second run lifecycle.+-- Payloads contain references and changed field names, never comment bodies,+-- attachment URLs, or arbitrary metadata values.+CREATE OR REPLACE FUNCTION capture_issue_wakeup(p_issue uuid, p_type text, p_key text, p_agent uuid, p_task uuid, p_payload jsonb)+RETURNS void LANGUAGE plpgsql AS $$+DECLARE w issue_wakeup; owner_workspace uuid; evidence jsonb; violated_constraint text;+BEGIN+ IF NOT EXISTS (SELECT 1 FROM issue_wakeup WHERE issue_id=p_issue AND enabled AND kind='event' AND p_type=ANY(event_types)) THEN RETURN; END IF;+ IF p_agent IS NULL AND current_setting('multica.actor_type',true)='agent' THEN+ p_agent := NULLIF(current_setting('multica.actor_id',true),'')::uuid;+ END IF;+ SELECT i.workspace_id INTO owner_workspace FROM issue i+ WHERE i.id=p_issue AND i.status NOT IN ('done','cancelled') AND NOT EXISTS+ (SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'));+ IF owner_workspace IS NULL THEN RETURN; END IF;+ evidence := jsonb_build_object('event_id',p_key,'event_type',p_type,'version',1,+ 'occurred_at',clock_timestamp(),'workspace_id',owner_workspace,'issue_id',p_issue,+ 'source_task_id',p_task,'agent_id',p_agent,+ 'actor_type',COALESCE(NULLIF(current_setting('multica.actor_type',true),''),CASE WHEN p_agent IS NOT NULL THEN 'agent' ELSE 'system' END),+ 'actor_id',COALESCE(NULLIF(current_setting('multica.actor_id',true),''),p_agent::text)) || p_payload;+ FOR w IN SELECT * FROM issue_wakeup WHERE issue_id=p_issue AND workspace_id=owner_workspace AND enabled AND kind='event'+ AND p_type=ANY(event_types)+ AND (filter_actor_type IS NULL OR (filter_actor_type=evidence->>'actor_type' AND filter_actor_id::text=evidence->>'actor_id'))+ AND (filter_agent_id IS NULL OR filter_agent_id=p_agent)+ AND (filter_task_id IS NULL OR filter_task_id=p_task)+ AND (p_task IS NULL OR source_task_id IS DISTINCT FROM p_task)+ AND NOT EXISTS (SELECT 1 FROM agent_task_queue t WHERE t.id=p_task AND t.context->>'wakeup_id'=issue_wakeup.id::text)+ ORDER BY id+ LOOP+ -- One pending notification per event type. Preserve the first key for+ -- duplicate suppression and the latest source reference for state reads.+ BEGIN+ INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload,coalesce_key)+ VALUES(gen_random_uuid(),w.id,w.revision,p_key,p_type,+ evidence || jsonb_build_object('coalesced_count',1,'first_occurred_at',evidence->'occurred_at'),p_type)+ ON CONFLICT(wakeup_id,revision,coalesce_key) WHERE processed_at IS NULL AND coalesce_key IS NOT NULL+ -- Rotate the receipt identity on merge. An older dispatcher that read+ -- without FOR UPDATE can only consume its observed version, leaving the+ -- replacement pending instead of silently consuming unseen evidence.+ DO UPDATE SET id=EXCLUDED.id,payload=EXCLUDED.payload || jsonb_build_object(+ 'coalesced_count',COALESCE((issue_wakeup_receipt.payload->>'coalesced_count')::bigint,1)+1,+ 'first_occurred_at',issue_wakeup_receipt.payload->'first_occurred_at')+ WHERE issue_wakeup_receipt.event_key<>p_key AND issue_wakeup_receipt.payload->>'event_id' IS DISTINCT FROM p_key;+ EXCEPTION WHEN unique_violation THEN+ GET STACKED DIAGNOSTICS violated_constraint = CONSTRAINT_NAME;+ -- A retained receipt already handled this exact source fact. This also+ -- fences the locked registration snapshot against terminal-task capture.+ IF violated_constraint <> 'issue_wakeup_receipt_key_idx' THEN RAISE; END IF;+ END;++ END LOOP;+END $$;diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 51e486ee58..73fabfbc2f 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -1640,6 +1640,7 @@ WHERE id = (WHERE atq.agent_id = $2AND atq.runtime_id = $3AND atq.status = 'queued'+ AND (atq.context->>'wakeup_id' IS NULL OR EXISTS (SELECT 1 FROM issue_wakeup w WHERE w.id=(atq.context->>'wakeup_id')::uuid AND w.disabled_at IS NULL AND w.revision=(atq.context->>'wakeup_revision')::bigint))AND EXISTS (SELECT 1FROM agent a@@ -2933,7 +2934,7 @@ INSERT INTO agent_task_queue (originator_source, delegated_from_task_id, rule_version_id,trigger_evidence_kind, trigger_evidence_ref_id, retry_of_task_id,chat_input_task_id, fire_at,- channel_context_revision, id+ channel_context_revision, handoff_note, id)SELECTp.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,@@ -2954,6 +2955,7 @@ SELECTp.trigger_evidence_kind, p.trigger_evidence_ref_id, p.id,p.chat_input_task_id, $2,p.channel_context_revision,+ CASE WHEN p.context->>'wakeup_id' IS NOT NULL THEN p.handoff_note END,-- Named new_task_id, not id: $1 above is the PARENT task's id.COALESCE($6::uuid, gen_random_uuid())FROM agent_task_queue p@@ -3252,7 +3254,7 @@ func (q *Queries) DeleteUnstartedQuickCreateRetryTask(ctx context.Context, taskIconst expireStaleQueuedTasks = `-- name: ExpireStaleQueuedTasks :manyWITH victims AS (SELECT id FROM agent_task_queue- WHERE status = 'queued'+ WHERE status = 'queued' AND context->>'wakeup_id' IS NULLAND created_at < now() - make_interval(secs => $1::double precision)AND (runtime_id IS NULL@@ -4949,7 +4951,7 @@ func (q *Queries) HasActiveTaskForIssueAndAgentInThread(ctx context.Context, argconst hasPendingTaskForIssue = `-- name: HasPendingTaskForIssue :oneSELECT count(*) > 0 AS has_pending FROM agent_task_queue-WHERE issue_id = $1 AND status IN ('queued', 'dispatched')+WHERE context->>'wakeup_id' IS NULL AND issue_id = $1 AND status IN ('queued', 'dispatched')`// Returns true if there is a queued or dispatched (but not yet running) task for the issue.@@ -4965,7 +4967,7 @@ func (q *Queries) HasPendingTaskForIssue(ctx context.Context, issueID pgtype.UUIconst hasPendingTaskForIssueAndAgent = `-- name: HasPendingTaskForIssueAndAgent :oneSELECT count(*) > 0 AS has_pending FROM agent_task_queue-WHERE issue_id = $1 AND agent_id = $2+WHERE context->>'wakeup_id' IS NULL AND issue_id = $1 AND agent_id = $2AND (status IN ('queued', 'dispatched')OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')@@ -5002,7 +5004,7 @@ func (q *Queries) HasPendingTaskForIssueAndAgent(ctx context.Context, arg HasPenconst hasPendingTaskForIssueAndAgentExcludingTriggerComment = `-- name: HasPendingTaskForIssueAndAgentExcludingTriggerComment :oneSELECT count(*) > 0 AS has_pending FROM agent_task_queue-WHERE issue_id = $1+WHERE context->>'wakeup_id' IS NULL AND issue_id = $1AND agent_id = $2AND (status IN ('queued', 'dispatched')@@ -5040,7 +5042,7 @@ func (q *Queries) HasPendingTaskForIssueAndAgentExcludingTriggerComment(ctx contconst hasPendingTaskForIssueAndAgentExcludingTriggerCommentInThread = `-- name: HasPendingTaskForIssueAndAgentExcludingTriggerCommentInThread :oneSELECT count(*) > 0 AS has_pending FROM agent_task_queue-WHERE issue_id = $1+WHERE context->>'wakeup_id' IS NULL AND issue_id = $1AND agent_id = $2AND (status IN ('queued', 'dispatched')@@ -5078,7 +5080,7 @@ func (q *Queries) HasPendingTaskForIssueAndAgentExcludingTriggerCommentInThread(const hasPendingTaskForIssueAndAgentInThread = `-- name: HasPendingTaskForIssueAndAgentInThread :oneSELECT count(*) > 0 AS has_pending FROM agent_task_queue-WHERE issue_id = $1 AND agent_id = $2+WHERE context->>'wakeup_id' IS NULL AND issue_id = $1 AND agent_id = $2AND (status IN ('queued', 'dispatched')OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')@@ -6095,6 +6097,7 @@ const listQueuedClaimCandidatesByRuntime = `-- name: ListQueuedClaimCandidatesBySELECT 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 FROM agent_task_queue atqWHERE atq.runtime_id = $1AND atq.status = 'queued'+ AND (atq.context->>'wakeup_id' IS NULL OR EXISTS (SELECT 1 FROM issue_wakeup w WHERE w.id=(atq.context->>'wakeup_id')::uuid AND w.disabled_at IS NULL AND w.revision=(atq.context->>'wakeup_revision')::bigint))AND EXISTS (-- Keep this authorization fence in sync with ClaimAgentTask.SELECT 1@@ -6202,6 +6205,7 @@ const listQueuedClaimCandidatesByRuntimes = `-- name: ListQueuedClaimCandidatesBSELECT 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 FROM agent_task_queue atqWHERE atq.runtime_id = ANY($1::uuid[])AND atq.status = 'queued'+ AND (atq.context->>'wakeup_id' IS NULL OR EXISTS (SELECT 1 FROM issue_wakeup w WHERE w.id=(atq.context->>'wakeup_id')::uuid AND w.disabled_at IS NULL AND w.revision=(atq.context->>'wakeup_revision')::bigint))AND EXISTS (-- Keep this authorization fence in sync with ClaimAgentTask.SELECT 1@@ -6492,7 +6496,8 @@ const listWorkspaceAgentTaskSnapshot = `-- name: ListWorkspaceAgentTaskSnapshotSELECT 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 FROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idWHERE a.workspace_id = $1- AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+ AND (atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+ OR (atq.status='deferred' AND atq.context->>'wakeup_id' IS NOT NULL))UNION ALL@@ -6530,7 +6535,7 @@ WHERE a.workspace_id = $1// grows with how much terminal history the workspace has accumulated. The// (created_at, id) tie-break makes the pick deterministic when completed_at// ties or is NULL — plain completed_at DESC returned an arbitrary row there.-// Row shape and row set are unchanged.+// Deferred wakeup retries also remain visible as queued work.//// Both halves JOIN / scan agent because agent_task_queue has no workspace_id.func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceID pgtype.UUID) ([]AgentTaskQueue, error) {@@ -7040,7 +7045,7 @@ SET coalesced_comment_ids = (runtime_connected_apps = $11WHERE id = (SELECT t.id FROM agent_task_queue t- WHERE t.issue_id = $12+ WHERE t.context->>'wakeup_id' IS NULL AND t.issue_id = $12AND t.agent_id = $13AND t.comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id($1::uuid)AND (@@ -7159,7 +7164,7 @@ SET coalesced_comment_ids = (trigger_summary = $2WHERE id = (SELECT t.id FROM agent_task_queue t- WHERE t.issue_id = $3+ WHERE t.context->>'wakeup_id' IS NULL AND t.issue_id = $3AND t.agent_id = $4AND t.comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id($1::uuid)AND (@@ -8151,7 +8156,7 @@ SET coalesced_comment_ids = ()WHERE id = (SELECT t.id FROM agent_task_queue t- WHERE t.issue_id = $2+ WHERE t.context->>'wakeup_id' IS NULL AND t.issue_id = $2AND t.agent_id = $3AND t.comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id($1::uuid)AND t.status IN ('dispatched', 'running', 'waiting_local_directory')diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex 3b39fa16bf..57f621021e 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -403,6 +403,12 @@ const deleteIssue = `-- name: DeleteIssue :execWITH target AS (SELECT issue.id FROM issue WHERE issue.id = $1 AND issue.workspace_id = $2),+cleared_wakeup_receipts AS (+ DELETE FROM issue_wakeup_receipt WHERE wakeup_id IN (SELECT id FROM issue_wakeup WHERE issue_id IN (SELECT target.id FROM target))+),+cleared_wakeups AS (+ DELETE FROM issue_wakeup WHERE issue_id IN (SELECT target.id FROM target)+),cleared_vcs_pr_links AS (DELETE FROM issue_vcs_pull_request WHERE issue_id IN (SELECT target.id FROM target))@@ -1760,20 +1766,20 @@ func (q *Queries) SetIssueMetadataKey(ctx context.Context, arg SetIssueMetadataK}const updateIssue = `-- name: UpdateIssue :one-WITH candidate AS (+WITH wakeup_source AS MATERIALIZED (SELECT set_config('multica.source_task_id', COALESCE($3::uuid::text, ''), true)), candidate AS (SELECTi.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state,- COALESCE($3::text, i.title) AS next_title,- COALESCE($4::text, i.description) AS next_description,- COALESCE($5::text, i.status) AS next_status,- COALESCE($6::text, i.priority) AS next_priority,- $7::text AS next_assignee_type,- $8::uuid AS next_assignee_id,+ COALESCE($4::text, i.title) AS next_title,+ COALESCE($5::text, i.description) AS next_description,+ COALESCE($6::text, i.status) AS next_status,+ COALESCE($7::text, i.priority) AS next_priority,+ $8::text AS next_assignee_type,+ $9::uuid AS next_assignee_id,CASE-- An explicit position wins. Cross-column drag-and-drop sends-- status and position together and means the slot it dropped on.- WHEN $9::double precision IS NOT NULL- THEN $9::double precision+ WHEN $10::double precision IS NOT NULL+ THEN $10::double precision-- position ranks an issue *within* its (workspace, status)-- column, so it stops meaning anything the moment the column-- changes: the value that put the issue on top of Todo lands it@@ -1788,20 +1794,20 @@ WITH candidate AS (-- unstable across pages. Creation avoids the tie by computing its-- min under the workspace counter lock; a status change holds no-- such lock and is not worth taking one for.- WHEN i.status IS DISTINCT FROM COALESCE($5::text, i.status)+ WHEN i.status IS DISTINCT FROM COALESCE($6::text, i.status)THEN (SELECT COALESCE(MIN(target.position), 0) - 1FROM issue AS targetWHERE target.workspace_id = i.workspace_id- AND target.status = $5::text+ AND target.status = $6::text)ELSE i.positionEND AS next_position,- $10::date AS next_start_date,- $11::date AS next_due_date,- $12::uuid AS next_parent_issue_id,- $13::uuid AS next_project_id,- $14::integer AS next_stage+ $11::date AS next_start_date,+ $12::date AS next_due_date,+ $13::uuid AS next_parent_issue_id,+ $14::uuid AS next_project_id,+ $15::integer AS next_stageFROM issue AS iWHERE i.id = $1AND ($2::bigint IS NULL OR i.revision = $2::bigint)@@ -1845,7 +1851,7 @@ UPDATE issue AS i SETELSE i.last_activity_atEND,updated_at = CASE WHEN changed.did_change THEN now() ELSE i.updated_at END-FROM changed+FROM changed CROSS JOIN wakeup_sourceWHERE i.id = changed.id-- Re-check the precondition on the row version that UPDATE actually locks.-- Under READ COMMITTED, concurrent statements may both populate candidate@@ -1858,6 +1864,7 @@ RETURNING i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.type UpdateIssueParams struct {ID pgtype.UUID `json:"id"`ExpectedRevision pgtype.Int8 `json:"expected_revision"`+ SourceTaskID pgtype.UUID `json:"source_task_id"`Title pgtype.Text `json:"title"`Description pgtype.Text `json:"description"`Status pgtype.Text `json:"status"`@@ -1876,6 +1883,7 @@ func (q *Queries) UpdateIssue(ctx context.Context, arg UpdateIssueParams) (Issuerow := q.db.QueryRow(ctx, updateIssue,arg.ID,arg.ExpectedRevision,+ arg.SourceTaskID,arg.Title,arg.Description,arg.Status,@@ -1925,6 +1933,7 @@ func (q *Queries) UpdateIssue(ctx context.Context, arg UpdateIssueParams) (Issue}const updateIssueStatus = `-- name: UpdateIssueStatus :one+WITH wakeup_source AS MATERIALIZED (SELECT set_config('multica.source_task_id', COALESCE($4::uuid::text, ''), true))UPDATE issue AS i SETstatus = $2,position = CASE WHEN i.status IS DISTINCT FROM $2 THEN (@@ -1939,14 +1948,16 @@ UPDATE issue AS i SETELSE i.last_activity_atEND,updated_at = now()+FROM wakeup_sourceWHERE i.id = $1 AND i.workspace_id = $3-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state+RETURNING i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state`type UpdateIssueStatusParams struct {- ID pgtype.UUID `json:"id"`- Status string `json:"status"`- WorkspaceID pgtype.UUID `json:"workspace_id"`+ ID pgtype.UUID `json:"id"`+ Status string `json:"status"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ SourceTaskID pgtype.UUID `json:"source_task_id"`}// Workspace_id in the WHERE clause is a SQL-layer tenant guard; see DeleteIssue.@@ -1955,7 +1966,12 @@ type UpdateIssueStatusParams struct {// old column's rank into a new column is the bug this guards against. See the// next_position CASE in UpdateIssue for the policy.func (q *Queries) UpdateIssueStatus(ctx context.Context, arg UpdateIssueStatusParams) (Issue, error) {- row := q.db.QueryRow(ctx, updateIssueStatus, arg.ID, arg.Status, arg.WorkspaceID)+ row := q.db.QueryRow(ctx, updateIssueStatus,+ arg.ID,+ arg.Status,+ arg.WorkspaceID,+ arg.SourceTaskID,+ )var i Issueerr := row.Scan(&i.ID,diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 2be181d149..a6eea38487 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -985,6 +985,48 @@ type IssueViewPreference struct {UpdatedAt pgtype.Timestamptz `json:"updated_at"`}+type IssueWakeup struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ CreatedBy pgtype.UUID `json:"created_by"`+ SourceTaskID pgtype.UUID `json:"source_task_id"`+ ParentCommentID pgtype.UUID `json:"parent_comment_id"`+ Instruction string `json:"instruction"`+ Kind string `json:"kind"`+ Mode string `json:"mode"`+ EventTypes []string `json:"event_types"`+ FilterAgentID pgtype.UUID `json:"filter_agent_id"`+ FilterTaskID pgtype.UUID `json:"filter_task_id"`+ IntervalSeconds pgtype.Int8 `json:"interval_seconds"`+ CronExpression pgtype.Text `json:"cron_expression"`+ Timezone string `json:"timezone"`+ NextFireAt pgtype.Timestamptz `json:"next_fire_at"`+ Enabled bool `json:"enabled"`+ DisabledAt pgtype.Timestamptz `json:"disabled_at"`+ Revision int64 `json:"revision"`+ LastTaskID pgtype.UUID `json:"last_task_id"`+ LastError pgtype.Text `json:"last_error"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ FilterActorType pgtype.Text `json:"filter_actor_type"`+ FilterActorID pgtype.UUID `json:"filter_actor_id"`+}++type IssueWakeupReceipt struct {+ ID pgtype.UUID `json:"id"`+ WakeupID pgtype.UUID `json:"wakeup_id"`+ Revision int64 `json:"revision"`+ EventKey string `json:"event_key"`+ EventType string `json:"event_type"`+ Payload []byte `json:"payload"`+ TaskID pgtype.UUID `json:"task_id"`+ ProcessedAt pgtype.Timestamptz `json:"processed_at"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ CoalesceKey pgtype.Text `json:"coalesce_key"`+}+type LarkBindingToken struct {TokenHash string `json:"token_hash"`WorkspaceID pgtype.UUID `json:"workspace_id"`diff --git a/server/pkg/db/generated/wakeup.sql.go b/server/pkg/db/generated/wakeup.sql.gonew file mode 100644index 0000000000..4d913b17e2--- /dev/null+++ b/server/pkg/db/generated/wakeup.sql.go@@ -0,0 +1,1160 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: wakeup.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const advanceIssueWakeup = `-- name: AdvanceIssueWakeup :exec+UPDATE issue_wakeup SET enabled= $1,next_fire_at=$2,last_task_id=COALESCE($3,last_task_id),last_error=$4,updated_at=clock_timestamp() WHERE id= $5+`++type AdvanceIssueWakeupParams struct {+ Enabled bool `json:"enabled"`+ NextFireAt pgtype.Timestamptz `json:"next_fire_at"`+ LastTaskID pgtype.UUID `json:"last_task_id"`+ LastError pgtype.Text `json:"last_error"`+ ID pgtype.UUID `json:"id"`+}++func (q *Queries) AdvanceIssueWakeup(ctx context.Context, arg AdvanceIssueWakeupParams) error {+ _, err := q.db.Exec(ctx, advanceIssueWakeup,+ arg.Enabled,+ arg.NextFireAt,+ arg.LastTaskID,+ arg.LastError,+ arg.ID,+ )+ return err+}++const cancelUnstartedWakeupTasks = `-- name: CancelUnstartedWakeupTasks :many+UPDATE agent_task_queue SET status='cancelled',completed_at=now(),error='Wakeup disabled or updated'+WHERE context->>'wakeup_id'= $1::text AND status IN ('queued','deferred') AND started_at IS NULL RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot+`++func (q *Queries) CancelUnstartedWakeupTasks(ctx context.Context, wakeupID string) ([]AgentTaskQueue, error) {+ rows, err := q.db.Query(ctx, cancelUnstartedWakeupTasks, wakeupID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []AgentTaskQueue{}+ for rows.Next() {+ var i AgentTaskQueue+ if err := rows.Scan(+ &i.ID,+ &i.AgentID,+ &i.IssueID,+ &i.Status,+ &i.Priority,+ &i.DispatchedAt,+ &i.StartedAt,+ &i.CompletedAt,+ &i.Result,+ &i.Error,+ &i.CreatedAt,+ &i.Context,+ &i.RuntimeID,+ &i.SessionID,+ &i.WorkDir,+ &i.TriggerCommentID,+ &i.ChatSessionID,+ &i.AutopilotRunID,+ &i.Attempt,+ &i.MaxAttempts,+ &i.ParentTaskID,+ &i.FailureReason,+ &i.TriggerSummary,+ &i.ForceFreshSession,+ &i.IsLeaderTask,+ &i.WaitReason,+ &i.InitiatorUserID,+ &i.HandoffNote,+ &i.PrepareLeaseExpiresAt,+ &i.SquadID,+ &i.RuntimeMcpOverlay,+ &i.EscalationForTaskID,+ &i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,+ &i.DeliveredCommentIds,+ &i.ChatInputTaskID,+ &i.ChatFinalizeDeferredAt,+ &i.OriginatorSource,+ &i.DelegatedFromTaskID,+ &i.RetryOfTaskID,+ &i.RerunOfTaskID,+ &i.RuleVersionID,+ &i.TriggerEvidenceKind,+ &i.TriggerEvidenceRefID,+ &i.AccountableUserID,+ &i.SessionRolloutMissing,+ &i.RetiredSessionID,+ &i.QuickActionsDisabled,+ &i.RegenerateQuickActionsFor,+ &i.BranchName,+ &i.DurableWorkDir,+ &i.ChannelContextRevision,+ &i.CommentThreadID,+ &i.CancelledByType,+ &i.CancelledByID,+ &i.CancelledByName,+ &i.IssueSnapshot,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const consumeWakeupReceipts = `-- name: ConsumeWakeupReceipts :exec+UPDATE issue_wakeup_receipt SET task_id=$1,processed_at=now() WHERE id=ANY($2::uuid[])+`++type ConsumeWakeupReceiptsParams struct {+ TaskID pgtype.UUID `json:"task_id"`+ Ids []pgtype.UUID `json:"ids"`+}++func (q *Queries) ConsumeWakeupReceipts(ctx context.Context, arg ConsumeWakeupReceiptsParams) error {+ _, err := q.db.Exec(ctx, consumeWakeupReceipts, arg.TaskID, arg.Ids)+ return err+}++const createIssueWakeup = `-- name: CreateIssueWakeup :one+INSERT INTO issue_wakeup(id,workspace_id,issue_id,agent_id,created_by,source_task_id,parent_comment_id,instruction,kind,mode,event_types,filter_agent_id,filter_task_id,filter_actor_type,filter_actor_id,interval_seconds,cron_expression,timezone,next_fire_at)+VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19) RETURNING id, workspace_id, issue_id, agent_id, created_by, source_task_id, parent_comment_id, instruction, kind, mode, event_types, filter_agent_id, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, disabled_at, revision, last_task_id, last_error, created_at, updated_at, filter_actor_type, filter_actor_id+`++type CreateIssueWakeupParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ CreatedBy pgtype.UUID `json:"created_by"`+ SourceTaskID pgtype.UUID `json:"source_task_id"`+ ParentCommentID pgtype.UUID `json:"parent_comment_id"`+ Instruction string `json:"instruction"`+ Kind string `json:"kind"`+ Mode string `json:"mode"`+ EventTypes []string `json:"event_types"`+ FilterAgentID pgtype.UUID `json:"filter_agent_id"`+ FilterTaskID pgtype.UUID `json:"filter_task_id"`+ FilterActorType pgtype.Text `json:"filter_actor_type"`+ FilterActorID pgtype.UUID `json:"filter_actor_id"`+ IntervalSeconds pgtype.Int8 `json:"interval_seconds"`+ CronExpression pgtype.Text `json:"cron_expression"`+ Timezone string `json:"timezone"`+ NextFireAt pgtype.Timestamptz `json:"next_fire_at"`+}++func (q *Queries) CreateIssueWakeup(ctx context.Context, arg CreateIssueWakeupParams) (IssueWakeup, error) {+ row := q.db.QueryRow(ctx, createIssueWakeup,+ arg.ID,+ arg.WorkspaceID,+ arg.IssueID,+ arg.AgentID,+ arg.CreatedBy,+ arg.SourceTaskID,+ arg.ParentCommentID,+ arg.Instruction,+ arg.Kind,+ arg.Mode,+ arg.EventTypes,+ arg.FilterAgentID,+ arg.FilterTaskID,+ arg.FilterActorType,+ arg.FilterActorID,+ arg.IntervalSeconds,+ arg.CronExpression,+ arg.Timezone,+ arg.NextFireAt,+ )+ var i IssueWakeup+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.AgentID,+ &i.CreatedBy,+ &i.SourceTaskID,+ &i.ParentCommentID,+ &i.Instruction,+ &i.Kind,+ &i.Mode,+ &i.EventTypes,+ &i.FilterAgentID,+ &i.FilterTaskID,+ &i.IntervalSeconds,+ &i.CronExpression,+ &i.Timezone,+ &i.NextFireAt,+ &i.Enabled,+ &i.DisabledAt,+ &i.Revision,+ &i.LastTaskID,+ &i.LastError,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.FilterActorType,+ &i.FilterActorID,+ )+ return i, err+}++const createWakeupTask = `-- name: CreateWakeupTask :one+INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,+ coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,+ squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,+ originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id, trigger_evidence_kind, trigger_evidence_ref_id,+ id+)+SELECT+ $1, $2, $3, 'queued', $4, $5,+ COALESCE($6::uuid[], '{}'),+ $7,+ COALESCE($8::boolean, FALSE),+ COALESCE($9::boolean, FALSE),+ $10,+ $11,+ CASE+ WHEN COALESCE($12::text, '') <> ''+ THEN jsonb_build_object('head_sha', $12::text)+ ELSE '{}'::jsonb+ END || $13::jsonb,+ $14,+ $15,+ $16,+ $17,+ $18,+ $19,+ $20,+ $21,+ $22,+ $23,+ COALESCE($24::uuid, gen_random_uuid())+WHERE lock_task_owner_rows($1, $3, $2)+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot+`++type CreateWakeupTaskParams struct {+ AgentID pgtype.UUID `json:"agent_id"`+ RuntimeID pgtype.UUID `json:"runtime_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ Priority int32 `json:"priority"`+ TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`+ CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`+ TriggerSummary pgtype.Text `json:"trigger_summary"`+ ForceFreshSession pgtype.Bool `json:"force_fresh_session"`+ IsLeaderTask pgtype.Bool `json:"is_leader_task"`+ HandoffNote pgtype.Text `json:"handoff_note"`+ SquadID pgtype.UUID `json:"squad_id"`+ HeadSha pgtype.Text `json:"head_sha"`+ WakeupContext []byte `json:"wakeup_context"`+ OriginatorUserID pgtype.UUID `json:"originator_user_id"`+ AccountableUserID pgtype.UUID `json:"accountable_user_id"`+ RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`+ RuntimeConnectedApps []byte `json:"runtime_connected_apps"`+ OriginatorSource pgtype.Text `json:"originator_source"`+ DelegatedFromTaskID pgtype.UUID `json:"delegated_from_task_id"`+ RuleVersionID pgtype.UUID `json:"rule_version_id"`+ RerunOfTaskID pgtype.UUID `json:"rerun_of_task_id"`+ TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`+ TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`+ ID pgtype.UUID `json:"id"`+}++// Fenced against workspace teardown: lock_task_owner_rows (migration 284)+// locks the owners' workspace rows in the writer's own transaction and returns+// false once they are gone, so this statement writes no row instead of stranding+// a task in a workspace that has just been deleted (MUL-5999).+// head_sha stamps the commit under review into the task's context JSONB so the+// reviewer-loop dedup (HasPendingTaskForIssueAndAgent) can tell a pending run+// against an OLD head apart from a fresh request against a NEW head (TEN-356).+// Empty/absent head_sha leaves context NULL, preserving pre-TEN-356 behavior for+// issues with no linked PR. Issue-linked tasks never hit quick-create context+// parsing (parseQuickCreateContext short-circuits on IssueID.Valid), so this+// key rides harmlessly alongside.+// id is minted by the application as a UUIDv7 (pkg/dbid) so consecutive+// enqueues cluster in a narrow contiguous primary-key range instead of+// scattering across the B-tree. On a table with existing v4 ids, that range+// is not necessarily the tree's right edge.+// COALESCE keeps the column's gen_random_uuid() default reachable, so a caller+// that passes no id still inserts — it just gets a random v4, exactly as before.+// The same pattern is used by every INSERT listed in pkg/dbid's write table.+func (q *Queries) CreateWakeupTask(ctx context.Context, arg CreateWakeupTaskParams) (AgentTaskQueue, error) {+ row := q.db.QueryRow(ctx, createWakeupTask,+ arg.AgentID,+ arg.RuntimeID,+ arg.IssueID,+ arg.Priority,+ arg.TriggerCommentID,+ arg.CoalescedCommentIds,+ arg.TriggerSummary,+ arg.ForceFreshSession,+ arg.IsLeaderTask,+ arg.HandoffNote,+ arg.SquadID,+ arg.HeadSha,+ arg.WakeupContext,+ arg.OriginatorUserID,+ arg.AccountableUserID,+ arg.RuntimeMcpOverlay,+ arg.RuntimeConnectedApps,+ arg.OriginatorSource,+ arg.DelegatedFromTaskID,+ arg.RuleVersionID,+ arg.RerunOfTaskID,+ arg.TriggerEvidenceKind,+ arg.TriggerEvidenceRefID,+ arg.ID,+ )+ var i AgentTaskQueue+ err := row.Scan(+ &i.ID,+ &i.AgentID,+ &i.IssueID,+ &i.Status,+ &i.Priority,+ &i.DispatchedAt,+ &i.StartedAt,+ &i.CompletedAt,+ &i.Result,+ &i.Error,+ &i.CreatedAt,+ &i.Context,+ &i.RuntimeID,+ &i.SessionID,+ &i.WorkDir,+ &i.TriggerCommentID,+ &i.ChatSessionID,+ &i.AutopilotRunID,+ &i.Attempt,+ &i.MaxAttempts,+ &i.ParentTaskID,+ &i.FailureReason,+ &i.TriggerSummary,+ &i.ForceFreshSession,+ &i.IsLeaderTask,+ &i.WaitReason,+ &i.InitiatorUserID,+ &i.HandoffNote,+ &i.PrepareLeaseExpiresAt,+ &i.SquadID,+ &i.RuntimeMcpOverlay,+ &i.EscalationForTaskID,+ &i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,+ &i.DeliveredCommentIds,+ &i.ChatInputTaskID,+ &i.ChatFinalizeDeferredAt,+ &i.OriginatorSource,+ &i.DelegatedFromTaskID,+ &i.RetryOfTaskID,+ &i.RerunOfTaskID,+ &i.RuleVersionID,+ &i.TriggerEvidenceKind,+ &i.TriggerEvidenceRefID,+ &i.AccountableUserID,+ &i.SessionRolloutMissing,+ &i.RetiredSessionID,+ &i.QuickActionsDisabled,+ &i.RegenerateQuickActionsFor,+ &i.BranchName,+ &i.DurableWorkDir,+ &i.ChannelContextRevision,+ &i.CommentThreadID,+ &i.CancelledByType,+ &i.CancelledByID,+ &i.CancelledByName,+ &i.IssueSnapshot,+ )+ return i, err+}++const deleteExpiredWakeupReceipts = `-- name: DeleteExpiredWakeupReceipts :execrows+DELETE FROM issue_wakeup_receipt WHERE id IN (+ SELECT expired.id FROM issue_wakeup_receipt expired WHERE expired.processed_at < $1+ ORDER BY expired.processed_at,expired.id LIMIT 1000 FOR UPDATE SKIP LOCKED+)+`++// Pending inputs are never expired. Bound work and avoid waiting on dispatch.+func (q *Queries) DeleteExpiredWakeupReceipts(ctx context.Context, cutoff pgtype.Timestamptz) (int64, error) {+ result, err := q.db.Exec(ctx, deleteExpiredWakeupReceipts, cutoff)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const discardWakeupReceipts = `-- name: DiscardWakeupReceipts :exec+UPDATE issue_wakeup_receipt SET processed_at=now() WHERE wakeup_id= $1 AND processed_at IS NULL+`++func (q *Queries) DiscardWakeupReceipts(ctx context.Context, id pgtype.UUID) error {+ _, err := q.db.Exec(ctx, discardWakeupReceipts, id)+ return err+}++const findPendingWakeupTask = `-- name: FindPendingWakeupTask :one+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot FROM agent_task_queue WHERE context->>'wakeup_id'= $1::text AND status IN ('queued','dispatched') ORDER BY created_at LIMIT 1 FOR UPDATE+`++func (q *Queries) FindPendingWakeupTask(ctx context.Context, wakeupID string) (AgentTaskQueue, error) {+ row := q.db.QueryRow(ctx, findPendingWakeupTask, wakeupID)+ var i AgentTaskQueue+ err := row.Scan(+ &i.ID,+ &i.AgentID,+ &i.IssueID,+ &i.Status,+ &i.Priority,+ &i.DispatchedAt,+ &i.StartedAt,+ &i.CompletedAt,+ &i.Result,+ &i.Error,+ &i.CreatedAt,+ &i.Context,+ &i.RuntimeID,+ &i.SessionID,+ &i.WorkDir,+ &i.TriggerCommentID,+ &i.ChatSessionID,+ &i.AutopilotRunID,+ &i.Attempt,+ &i.MaxAttempts,+ &i.ParentTaskID,+ &i.FailureReason,+ &i.TriggerSummary,+ &i.ForceFreshSession,+ &i.IsLeaderTask,+ &i.WaitReason,+ &i.InitiatorUserID,+ &i.HandoffNote,+ &i.PrepareLeaseExpiresAt,+ &i.SquadID,+ &i.RuntimeMcpOverlay,+ &i.EscalationForTaskID,+ &i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,+ &i.DeliveredCommentIds,+ &i.ChatInputTaskID,+ &i.ChatFinalizeDeferredAt,+ &i.OriginatorSource,+ &i.DelegatedFromTaskID,+ &i.RetryOfTaskID,+ &i.RerunOfTaskID,+ &i.RuleVersionID,+ &i.TriggerEvidenceKind,+ &i.TriggerEvidenceRefID,+ &i.AccountableUserID,+ &i.SessionRolloutMissing,+ &i.RetiredSessionID,+ &i.QuickActionsDisabled,+ &i.RegenerateQuickActionsFor,+ &i.BranchName,+ &i.DurableWorkDir,+ &i.ChannelContextRevision,+ &i.CommentThreadID,+ &i.CancelledByType,+ &i.CancelledByID,+ &i.CancelledByName,+ &i.IssueSnapshot,+ )+ return i, err+}++const getIssueWakeup = `-- name: GetIssueWakeup :one+SELECT id, workspace_id, issue_id, agent_id, created_by, source_task_id, parent_comment_id, instruction, kind, mode, event_types, filter_agent_id, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, disabled_at, revision, last_task_id, last_error, created_at, updated_at, filter_actor_type, filter_actor_id FROM issue_wakeup WHERE id= $1 AND workspace_id= $2+`++type GetIssueWakeupParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) GetIssueWakeup(ctx context.Context, arg GetIssueWakeupParams) (IssueWakeup, error) {+ row := q.db.QueryRow(ctx, getIssueWakeup, arg.ID, arg.WorkspaceID)+ var i IssueWakeup+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.AgentID,+ &i.CreatedBy,+ &i.SourceTaskID,+ &i.ParentCommentID,+ &i.Instruction,+ &i.Kind,+ &i.Mode,+ &i.EventTypes,+ &i.FilterAgentID,+ &i.FilterTaskID,+ &i.IntervalSeconds,+ &i.CronExpression,+ &i.Timezone,+ &i.NextFireAt,+ &i.Enabled,+ &i.DisabledAt,+ &i.Revision,+ &i.LastTaskID,+ &i.LastError,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.FilterActorType,+ &i.FilterActorID,+ )+ return i, err+}++const listIssueWakeups = `-- name: ListIssueWakeups :many+SELECT w.id,w.workspace_id,w.issue_id,w.agent_id,w.created_by,w.source_task_id,w.parent_comment_id,w.instruction,+ w.kind,w.mode,w.event_types,w.filter_actor_type,+ (CASE WHEN actor_agent.id IS NOT NULL OR actor_member.user_id IS NOT NULL THEN w.filter_actor_id END)::uuid AS filter_actor_id,+ COALESCE(actor_agent.name,actor_user.name,'')::text AS filter_actor_name,+ (CASE WHEN source.id IS NOT NULL THEN w.filter_agent_id END)::uuid AS filter_agent_id,+ (CASE WHEN EXISTS(SELECT 1 FROM agent_task_queue ft JOIN agent fa ON fa.id=ft.agent_id AND fa.workspace_id=w.workspace_id+ WHERE ft.id=w.filter_task_id AND ft.issue_id=w.issue_id AND fa.id=ANY($1::uuid[])) THEN w.filter_task_id END)::uuid AS filter_task_id,+ w.interval_seconds,w.cron_expression,w.timezone,w.next_fire_at,w.enabled,w.disabled_at,w.revision,+ w.last_task_id,w.last_error,w.created_at,w.updated_at,a.name AS agent_name,source.name AS filter_agent_name,t.status AS last_task_status+FROM issue_wakeup w JOIN agent a ON a.id=w.agent_id AND a.workspace_id=w.workspace_id+LEFT JOIN agent actor_agent ON w.filter_actor_type='agent' AND actor_agent.id=w.filter_actor_id AND actor_agent.workspace_id=w.workspace_id AND actor_agent.id=ANY($1::uuid[])+LEFT JOIN member actor_member ON w.filter_actor_type='member' AND actor_member.user_id=w.filter_actor_id AND actor_member.workspace_id=w.workspace_id+LEFT JOIN "user" actor_user ON actor_user.id=actor_member.user_id+LEFT JOIN agent source ON source.id=w.filter_agent_id AND source.workspace_id=w.workspace_id AND source.id=ANY($1::uuid[])+LEFT JOIN agent_task_queue t ON t.id=w.last_task_id AND t.issue_id=w.issue_id AND t.agent_id=w.agent_id+WHERE w.workspace_id= $2 AND w.issue_id= $3 ORDER BY w.created_at,w.id+`++type ListIssueWakeupsParams struct {+ AgentIds []pgtype.UUID `json:"agent_ids"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ IssueID pgtype.UUID `json:"issue_id"`+}++type ListIssueWakeupsRow struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ CreatedBy pgtype.UUID `json:"created_by"`+ SourceTaskID pgtype.UUID `json:"source_task_id"`+ ParentCommentID pgtype.UUID `json:"parent_comment_id"`+ Instruction string `json:"instruction"`+ Kind string `json:"kind"`+ Mode string `json:"mode"`+ EventTypes []string `json:"event_types"`+ FilterActorType pgtype.Text `json:"filter_actor_type"`+ FilterActorID pgtype.UUID `json:"filter_actor_id"`+ FilterActorName string `json:"filter_actor_name"`+ FilterAgentID pgtype.UUID `json:"filter_agent_id"`+ FilterTaskID pgtype.UUID `json:"filter_task_id"`+ IntervalSeconds pgtype.Int8 `json:"interval_seconds"`+ CronExpression pgtype.Text `json:"cron_expression"`+ Timezone string `json:"timezone"`+ NextFireAt pgtype.Timestamptz `json:"next_fire_at"`+ Enabled bool `json:"enabled"`+ DisabledAt pgtype.Timestamptz `json:"disabled_at"`+ Revision int64 `json:"revision"`+ LastTaskID pgtype.UUID `json:"last_task_id"`+ LastError pgtype.Text `json:"last_error"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ AgentName string `json:"agent_name"`+ FilterAgentName pgtype.Text `json:"filter_agent_name"`+ LastTaskStatus pgtype.Text `json:"last_task_status"`+}++func (q *Queries) ListIssueWakeups(ctx context.Context, arg ListIssueWakeupsParams) ([]ListIssueWakeupsRow, error) {+ rows, err := q.db.Query(ctx, listIssueWakeups, arg.AgentIds, arg.WorkspaceID, arg.IssueID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListIssueWakeupsRow{}+ for rows.Next() {+ var i ListIssueWakeupsRow+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.AgentID,+ &i.CreatedBy,+ &i.SourceTaskID,+ &i.ParentCommentID,+ &i.Instruction,+ &i.Kind,+ &i.Mode,+ &i.EventTypes,+ &i.FilterActorType,+ &i.FilterActorID,+ &i.FilterActorName,+ &i.FilterAgentID,+ &i.FilterTaskID,+ &i.IntervalSeconds,+ &i.CronExpression,+ &i.Timezone,+ &i.NextFireAt,+ &i.Enabled,+ &i.DisabledAt,+ &i.Revision,+ &i.LastTaskID,+ &i.LastError,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.AgentName,+ &i.FilterAgentName,+ &i.LastTaskStatus,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listPendingWakeupReceipts = `-- name: ListPendingWakeupReceipts :many+SELECT id, wakeup_id, revision, event_key, event_type, payload, task_id, processed_at, created_at, coalesce_key FROM issue_wakeup_receipt WHERE wakeup_id= $1 AND revision= $2 AND processed_at IS NULL ORDER BY created_at,id LIMIT 100 FOR UPDATE+`++type ListPendingWakeupReceiptsParams struct {+ WakeupID pgtype.UUID `json:"wakeup_id"`+ Revision int64 `json:"revision"`+}++func (q *Queries) ListPendingWakeupReceipts(ctx context.Context, arg ListPendingWakeupReceiptsParams) ([]IssueWakeupReceipt, error) {+ rows, err := q.db.Query(ctx, listPendingWakeupReceipts, arg.WakeupID, arg.Revision)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []IssueWakeupReceipt{}+ for rows.Next() {+ var i IssueWakeupReceipt+ if err := rows.Scan(+ &i.ID,+ &i.WakeupID,+ &i.Revision,+ &i.EventKey,+ &i.EventType,+ &i.Payload,+ &i.TaskID,+ &i.ProcessedAt,+ &i.CreatedAt,+ &i.CoalesceKey,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listReadyWakeups = `-- name: ListReadyWakeups :many+WITH candidates AS (+ SELECT id FROM issue_wakeup WHERE enabled AND kind<>'event' AND next_fire_at<=now()+ UNION+ SELECT wakeup_id FROM issue_wakeup_receipt WHERE processed_at IS NULL+)+SELECT w.id, w.workspace_id, w.issue_id, w.agent_id, w.created_by, w.source_task_id, w.parent_comment_id, w.instruction, w.kind, w.mode, w.event_types, w.filter_agent_id, w.filter_task_id, w.interval_seconds, w.cron_expression, w.timezone, w.next_fire_at, w.enabled, w.disabled_at, w.revision, w.last_task_id, w.last_error, w.created_at, w.updated_at, w.filter_actor_type, w.filter_actor_id FROM candidates c JOIN issue_wakeup w ON w.id=c.id+ORDER BY w.updated_at,w.id LIMIT 100+`++func (q *Queries) ListReadyWakeups(ctx context.Context) ([]IssueWakeup, error) {+ rows, err := q.db.Query(ctx, listReadyWakeups)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []IssueWakeup{}+ for rows.Next() {+ var i IssueWakeup+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.AgentID,+ &i.CreatedBy,+ &i.SourceTaskID,+ &i.ParentCommentID,+ &i.Instruction,+ &i.Kind,+ &i.Mode,+ &i.EventTypes,+ &i.FilterAgentID,+ &i.FilterTaskID,+ &i.IntervalSeconds,+ &i.CronExpression,+ &i.Timezone,+ &i.NextFireAt,+ &i.Enabled,+ &i.DisabledAt,+ &i.Revision,+ &i.LastTaskID,+ &i.LastError,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.FilterActorType,+ &i.FilterActorID,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listWorkspaceWakeupSummaryRows = `-- name: ListWorkspaceWakeupSummaryRows :many+WITH ranked AS (+ SELECT w.issue_id,w.id,w.agent_id,a.name AS agent_name,w.kind,w.mode,w.event_types,w.filter_actor_type,+ (CASE WHEN actor_agent.id IS NOT NULL OR actor_member.user_id IS NOT NULL THEN w.filter_actor_id END)::uuid AS filter_actor_id,+ COALESCE(actor_agent.name,actor_user.name,'')::text AS filter_actor_name,+ (CASE WHEN EXISTS(SELECT 1 FROM agent_task_queue ft JOIN agent fa ON fa.id=ft.agent_id AND fa.workspace_id=w.workspace_id+ WHERE ft.id=w.filter_task_id AND ft.issue_id=w.issue_id AND fa.id=ANY($1::uuid[])) THEN w.filter_task_id END)::uuid AS filter_task_id,+ source.name AS filter_agent_name,w.interval_seconds,w.cron_expression,w.timezone,w.next_fire_at,+ count(*) OVER(PARTITION BY w.issue_id) AS active_count,+ count(*) FILTER(WHERE w.kind='event') OVER(PARTITION BY w.issue_id) AS event_count,+ row_number() OVER(PARTITION BY w.issue_id ORDER BY w.next_fire_at NULLS LAST,w.created_at,w.id) AS rank+ FROM issue_wakeup w+ JOIN issue i ON i.id=w.issue_id AND i.workspace_id=w.workspace_id+ JOIN agent a ON a.id=w.agent_id AND a.workspace_id=w.workspace_id+ LEFT JOIN agent actor_agent ON w.filter_actor_type='agent' AND actor_agent.id=w.filter_actor_id AND actor_agent.workspace_id=w.workspace_id AND actor_agent.id=ANY($1::uuid[])+LEFT JOIN member actor_member ON w.filter_actor_type='member' AND actor_member.user_id=w.filter_actor_id AND actor_member.workspace_id=w.workspace_id+LEFT JOIN "user" actor_user ON actor_user.id=actor_member.user_id+LEFT JOIN agent source ON source.id=w.filter_agent_id AND source.workspace_id=w.workspace_id AND source.id=ANY($1::uuid[])+ WHERE w.workspace_id= $2 AND w.enabled+ AND i.status NOT IN ('done','cancelled')+ AND NOT EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'))+)+SELECT issue_id,id,agent_id,agent_name,kind,mode,event_types,filter_actor_type,filter_actor_id,filter_actor_name,filter_task_id,filter_agent_name,interval_seconds,cron_expression,timezone,next_fire_at,active_count,event_count+FROM ranked WHERE rank<=3 ORDER BY issue_id,rank+`++type ListWorkspaceWakeupSummaryRowsParams struct {+ AgentIds []pgtype.UUID `json:"agent_ids"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++type ListWorkspaceWakeupSummaryRowsRow struct {+ IssueID pgtype.UUID `json:"issue_id"`+ ID pgtype.UUID `json:"id"`+ AgentID pgtype.UUID `json:"agent_id"`+ AgentName string `json:"agent_name"`+ Kind string `json:"kind"`+ Mode string `json:"mode"`+ EventTypes []string `json:"event_types"`+ FilterActorType pgtype.Text `json:"filter_actor_type"`+ FilterActorID pgtype.UUID `json:"filter_actor_id"`+ FilterActorName string `json:"filter_actor_name"`+ FilterTaskID pgtype.UUID `json:"filter_task_id"`+ FilterAgentName pgtype.Text `json:"filter_agent_name"`+ IntervalSeconds pgtype.Int8 `json:"interval_seconds"`+ CronExpression pgtype.Text `json:"cron_expression"`+ Timezone string `json:"timezone"`+ NextFireAt pgtype.Timestamptz `json:"next_fire_at"`+ ActiveCount int64 `json:"active_count"`+ EventCount int64 `json:"event_count"`+}++// No prompts/history; at most three previews per issue plus exact counts.+func (q *Queries) ListWorkspaceWakeupSummaryRows(ctx context.Context, arg ListWorkspaceWakeupSummaryRowsParams) ([]ListWorkspaceWakeupSummaryRowsRow, error) {+ rows, err := q.db.Query(ctx, listWorkspaceWakeupSummaryRows, arg.AgentIds, arg.WorkspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListWorkspaceWakeupSummaryRowsRow{}+ for rows.Next() {+ var i ListWorkspaceWakeupSummaryRowsRow+ if err := rows.Scan(+ &i.IssueID,+ &i.ID,+ &i.AgentID,+ &i.AgentName,+ &i.Kind,+ &i.Mode,+ &i.EventTypes,+ &i.FilterActorType,+ &i.FilterActorID,+ &i.FilterActorName,+ &i.FilterTaskID,+ &i.FilterAgentName,+ &i.IntervalSeconds,+ &i.CronExpression,+ &i.Timezone,+ &i.NextFireAt,+ &i.ActiveCount,+ &i.EventCount,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const lockIssueWakeup = `-- name: LockIssueWakeup :one+SELECT id, workspace_id, issue_id, agent_id, created_by, source_task_id, parent_comment_id, instruction, kind, mode, event_types, filter_agent_id, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, disabled_at, revision, last_task_id, last_error, created_at, updated_at, filter_actor_type, filter_actor_id FROM issue_wakeup WHERE id= $1 FOR UPDATE+`++func (q *Queries) LockIssueWakeup(ctx context.Context, id pgtype.UUID) (IssueWakeup, error) {+ row := q.db.QueryRow(ctx, lockIssueWakeup, id)+ var i IssueWakeup+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.AgentID,+ &i.CreatedBy,+ &i.SourceTaskID,+ &i.ParentCommentID,+ &i.Instruction,+ &i.Kind,+ &i.Mode,+ &i.EventTypes,+ &i.FilterAgentID,+ &i.FilterTaskID,+ &i.IntervalSeconds,+ &i.CronExpression,+ &i.Timezone,+ &i.NextFireAt,+ &i.Enabled,+ &i.DisabledAt,+ &i.Revision,+ &i.LastTaskID,+ &i.LastError,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.FilterActorType,+ &i.FilterActorID,+ )+ return i, err+}++const lockWakeupIssue = `-- name: LockWakeupIssue :one+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state FROM issue WHERE id= $1 FOR NO KEY UPDATE+`++func (q *Queries) LockWakeupIssue(ctx context.Context, id pgtype.UUID) (Issue, error) {+ row := q.db.QueryRow(ctx, lockWakeupIssue, id)+ var i Issue+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Title,+ &i.Description,+ &i.Status,+ &i.Priority,+ &i.AssigneeType,+ &i.AssigneeID,+ &i.CreatorType,+ &i.CreatorID,+ &i.ParentIssueID,+ &i.AcceptanceCriteria,+ &i.ContextRefs,+ &i.Position,+ &i.DueDate,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.Number,+ &i.ProjectID,+ &i.OriginType,+ &i.OriginID,+ &i.FirstExecutedAt,+ &i.StartDate,+ &i.Metadata,+ &i.Stage,+ &i.Properties,+ &i.Revision,+ &i.LastActivityAt,+ &i.TriageState,+ )+ return i, err+}++const lockWakeupSourceTask = `-- name: LockWakeupSourceTask :one+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot FROM agent_task_queue WHERE id= $1 AND issue_id= $2 FOR UPDATE NOWAIT+`++type LockWakeupSourceTaskParams struct {+ ID pgtype.UUID `json:"id"`+ IssueID pgtype.UUID `json:"issue_id"`+}++func (q *Queries) LockWakeupSourceTask(ctx context.Context, arg LockWakeupSourceTaskParams) (AgentTaskQueue, error) {+ row := q.db.QueryRow(ctx, lockWakeupSourceTask, arg.ID, arg.IssueID)+ var i AgentTaskQueue+ err := row.Scan(+ &i.ID,+ &i.AgentID,+ &i.IssueID,+ &i.Status,+ &i.Priority,+ &i.DispatchedAt,+ &i.StartedAt,+ &i.CompletedAt,+ &i.Result,+ &i.Error,+ &i.CreatedAt,+ &i.Context,+ &i.RuntimeID,+ &i.SessionID,+ &i.WorkDir,+ &i.TriggerCommentID,+ &i.ChatSessionID,+ &i.AutopilotRunID,+ &i.Attempt,+ &i.MaxAttempts,+ &i.ParentTaskID,+ &i.FailureReason,+ &i.TriggerSummary,+ &i.ForceFreshSession,+ &i.IsLeaderTask,+ &i.WaitReason,+ &i.InitiatorUserID,+ &i.HandoffNote,+ &i.PrepareLeaseExpiresAt,+ &i.SquadID,+ &i.RuntimeMcpOverlay,+ &i.EscalationForTaskID,+ &i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,+ &i.DeliveredCommentIds,+ &i.ChatInputTaskID,+ &i.ChatFinalizeDeferredAt,+ &i.OriginatorSource,+ &i.DelegatedFromTaskID,+ &i.RetryOfTaskID,+ &i.RerunOfTaskID,+ &i.RuleVersionID,+ &i.TriggerEvidenceKind,+ &i.TriggerEvidenceRefID,+ &i.AccountableUserID,+ &i.SessionRolloutMissing,+ &i.RetiredSessionID,+ &i.QuickActionsDisabled,+ &i.RegenerateQuickActionsFor,+ &i.BranchName,+ &i.DurableWorkDir,+ &i.ChannelContextRevision,+ &i.CommentThreadID,+ &i.CancelledByType,+ &i.CancelledByID,+ &i.CancelledByName,+ &i.IssueSnapshot,+ )+ return i, err+}++const locklessWakeup = `-- name: LocklessWakeup :one+SELECT id, workspace_id, issue_id, agent_id, created_by, source_task_id, parent_comment_id, instruction, kind, mode, event_types, filter_agent_id, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, disabled_at, revision, last_task_id, last_error, created_at, updated_at, filter_actor_type, filter_actor_id FROM issue_wakeup WHERE id= $1+`++func (q *Queries) LocklessWakeup(ctx context.Context, id pgtype.UUID) (IssueWakeup, error) {+ row := q.db.QueryRow(ctx, locklessWakeup, id)+ var i IssueWakeup+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.AgentID,+ &i.CreatedBy,+ &i.SourceTaskID,+ &i.ParentCommentID,+ &i.Instruction,+ &i.Kind,+ &i.Mode,+ &i.EventTypes,+ &i.FilterAgentID,+ &i.FilterTaskID,+ &i.IntervalSeconds,+ &i.CronExpression,+ &i.Timezone,+ &i.NextFireAt,+ &i.Enabled,+ &i.DisabledAt,+ &i.Revision,+ &i.LastTaskID,+ &i.LastError,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.FilterActorType,+ &i.FilterActorID,+ )+ return i, err+}++const noteWakeupFailure = `-- name: NoteWakeupFailure :exec+UPDATE issue_wakeup SET last_error=$1,updated_at=clock_timestamp() WHERE id= $2+`++type NoteWakeupFailureParams struct {+ LastError pgtype.Text `json:"last_error"`+ ID pgtype.UUID `json:"id"`+}++func (q *Queries) NoteWakeupFailure(ctx context.Context, arg NoteWakeupFailureParams) error {+ _, err := q.db.Exec(ctx, noteWakeupFailure, arg.LastError, arg.ID)+ return err+}++const recordWakeupReceipt = `-- name: RecordWakeupReceipt :one+INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload)+VALUES($1,$2,$3,$4,$5,$6)+ON CONFLICT(wakeup_id,revision,event_key) DO UPDATE SET event_key=EXCLUDED.event_key RETURNING id, wakeup_id, revision, event_key, event_type, payload, task_id, processed_at, created_at, coalesce_key+`++type RecordWakeupReceiptParams struct {+ ID pgtype.UUID `json:"id"`+ WakeupID pgtype.UUID `json:"wakeup_id"`+ Revision int64 `json:"revision"`+ EventKey string `json:"event_key"`+ EventType string `json:"event_type"`+ Payload []byte `json:"payload"`+}++func (q *Queries) RecordWakeupReceipt(ctx context.Context, arg RecordWakeupReceiptParams) (IssueWakeupReceipt, error) {+ row := q.db.QueryRow(ctx, recordWakeupReceipt,+ arg.ID,+ arg.WakeupID,+ arg.Revision,+ arg.EventKey,+ arg.EventType,+ arg.Payload,+ )+ var i IssueWakeupReceipt+ err := row.Scan(+ &i.ID,+ &i.WakeupID,+ &i.Revision,+ &i.EventKey,+ &i.EventType,+ &i.Payload,+ &i.TaskID,+ &i.ProcessedAt,+ &i.CreatedAt,+ &i.CoalesceKey,+ )+ return i, err+}++const replaceWakeupEvidence = `-- name: ReplaceWakeupEvidence :one+UPDATE agent_task_queue SET handoff_note=$1, context=COALESCE(context,'{}'::jsonb) || jsonb_build_object('wakeup_evidence', $2::jsonb) WHERE id= $3 AND status='queued' RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot+`++type ReplaceWakeupEvidenceParams struct {+ HandoffNote pgtype.Text `json:"handoff_note"`+ WakeupEvidence []byte `json:"wakeup_evidence"`+ ID pgtype.UUID `json:"id"`+}++func (q *Queries) ReplaceWakeupEvidence(ctx context.Context, arg ReplaceWakeupEvidenceParams) (AgentTaskQueue, error) {+ row := q.db.QueryRow(ctx, replaceWakeupEvidence, arg.HandoffNote, arg.WakeupEvidence, arg.ID)+ var i AgentTaskQueue+ err := row.Scan(+ &i.ID,+ &i.AgentID,+ &i.IssueID,+ &i.Status,+ &i.Priority,+ &i.DispatchedAt,+ &i.StartedAt,+ &i.CompletedAt,+ &i.Result,+ &i.Error,+ &i.CreatedAt,+ &i.Context,+ &i.RuntimeID,+ &i.SessionID,+ &i.WorkDir,+ &i.TriggerCommentID,+ &i.ChatSessionID,+ &i.AutopilotRunID,+ &i.Attempt,+ &i.MaxAttempts,+ &i.ParentTaskID,+ &i.FailureReason,+ &i.TriggerSummary,+ &i.ForceFreshSession,+ &i.IsLeaderTask,+ &i.WaitReason,+ &i.InitiatorUserID,+ &i.HandoffNote,+ &i.PrepareLeaseExpiresAt,+ &i.SquadID,+ &i.RuntimeMcpOverlay,+ &i.EscalationForTaskID,+ &i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,+ &i.DeliveredCommentIds,+ &i.ChatInputTaskID,+ &i.ChatFinalizeDeferredAt,+ &i.OriginatorSource,+ &i.DelegatedFromTaskID,+ &i.RetryOfTaskID,+ &i.RerunOfTaskID,+ &i.RuleVersionID,+ &i.TriggerEvidenceKind,+ &i.TriggerEvidenceRefID,+ &i.AccountableUserID,+ &i.SessionRolloutMissing,+ &i.RetiredSessionID,+ &i.QuickActionsDisabled,+ &i.RegenerateQuickActionsFor,+ &i.BranchName,+ &i.DurableWorkDir,+ &i.ChannelContextRevision,+ &i.CommentThreadID,+ &i.CancelledByType,+ &i.CancelledByID,+ &i.CancelledByName,+ &i.IssueSnapshot,+ )+ return i, err+}++const touchWakeupDispatch = `-- name: TouchWakeupDispatch :exec+UPDATE issue_wakeup SET updated_at=clock_timestamp() WHERE id= $1+`++// Move blocked configurations to the back of the scan so one noisy issue+// cannot monopolize the bounded batch.+func (q *Queries) TouchWakeupDispatch(ctx context.Context, id pgtype.UUID) error {+ _, err := q.db.Exec(ctx, touchWakeupDispatch, id)+ return err+}diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.goindex dbcdc013b1..1249ec4923 100644--- a/server/pkg/db/generated/workspace_delete.sql.go+++ b/server/pkg/db/generated/workspace_delete.sql.go@@ -238,7 +238,11 @@ func (q *Queries) DeleteWorkspaceConnections(ctx context.Context, workspaceID pg}const deleteWorkspaceIssueRoots = `-- name: DeleteWorkspaceIssueRoots :exec-WITH+WITH deleted_wakeup_receipts AS (+ DELETE FROM issue_wakeup_receipt WHERE wakeup_id IN (SELECT id FROM issue_wakeup WHERE workspace_id=$1)+), deleted_wakeups AS (+ DELETE FROM issue_wakeup WHERE workspace_id=$1+),deleted_issues AS (DELETE FROM issue WHERE issue.workspace_id = $1),diff --git a/server/pkg/db/generated/workspace_wakeup.sql.go b/server/pkg/db/generated/workspace_wakeup.sql.gonew file mode 100644index 0000000000..fe968e07a8--- /dev/null+++ b/server/pkg/db/generated/workspace_wakeup.sql.go@@ -0,0 +1,115 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: workspace_wakeup.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const listWorkspaceWakeups = `-- name: ListWorkspaceWakeups :one+WITH base AS MATERIALIZED (+ SELECT w.id,w.issue_id,i.title AS issue_title,ws.issue_prefix||'-'||i.number AS issue_identifier,+ w.agent_id,a.name AS agent_name,w.kind,w.mode,w.event_types,w.filter_actor_type,+ (CASE WHEN actor_agent.id IS NOT NULL OR actor_member.user_id IS NOT NULL THEN w.filter_actor_id END)::uuid AS filter_actor_id,+ COALESCE(actor_agent.name,actor_user.name,'')::text AS filter_actor_name,+ CASE WHEN source.id IS NOT NULL THEN w.filter_agent_id END AS filter_agent_id,+ source.name AS filter_agent_name,+ CASE WHEN EXISTS(SELECT 1 FROM agent_task_queue ft JOIN agent fa ON fa.id=ft.agent_id AND fa.workspace_id=w.workspace_id+ WHERE ft.id=w.filter_task_id AND ft.issue_id=w.issue_id AND fa.id=ANY($1::uuid[])) THEN w.filter_task_id END AS filter_task_id,+ w.interval_seconds,w.cron_expression,w.timezone,+ w.next_fire_at,w.enabled,w.revision,w.disabled_at,w.last_task_id,w.last_error,w.created_at,+ (i.status IN ('done','cancelled') OR EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'))) AS issue_closed,+ COALESCE((w.created_by= $2::uuid OR $3::boolean),false) AS can_manage,+ COALESCE(r.active_runs,0)::int AS active_runs+ FROM issue_wakeup w+ JOIN workspace ws ON ws.id=w.workspace_id+ JOIN issue i ON i.id=w.issue_id AND i.workspace_id=w.workspace_id+ JOIN agent a ON a.id=w.agent_id AND a.workspace_id=w.workspace_id+ LEFT JOIN agent actor_agent ON w.filter_actor_type='agent' AND actor_agent.id=w.filter_actor_id AND actor_agent.workspace_id=w.workspace_id AND actor_agent.id=ANY($1::uuid[])+LEFT JOIN member actor_member ON w.filter_actor_type='member' AND actor_member.user_id=w.filter_actor_id AND actor_member.workspace_id=w.workspace_id+LEFT JOIN "user" actor_user ON actor_user.id=actor_member.user_id+ LEFT JOIN agent source ON source.id=w.filter_agent_id AND source.workspace_id=w.workspace_id AND source.id=ANY($1::uuid[])+ LEFT JOIN LATERAL (+ SELECT count(*) AS active_runs FROM agent_task_queue t+ WHERE t.context->>'wakeup_id'=w.id::text AND t.issue_id=w.issue_id AND t.agent_id=w.agent_id+ AND t.status IN ('queued','deferred','dispatched','running','waiting_local_directory')+ ) r ON true+ WHERE w.workspace_id= $4+), classified AS (+ SELECT id, issue_id, issue_title, issue_identifier, agent_id, agent_name, kind, mode, event_types, filter_actor_type, filter_actor_id, filter_actor_name, filter_agent_id, filter_agent_name, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, revision, disabled_at, last_task_id, last_error, created_at, issue_closed, can_manage, active_runs,CASE WHEN (enabled AND NOT issue_closed) OR active_runs>0 THEN 'active'+ WHEN NOT issue_closed AND disabled_at IS NOT NULL THEN 'disabled' ELSE 'ended' END AS scope+ FROM base+), filtered AS (+ SELECT id, issue_id, issue_title, issue_identifier, agent_id, agent_name, kind, mode, event_types, filter_actor_type, filter_actor_id, filter_actor_name, filter_agent_id, filter_agent_name, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, revision, disabled_at, last_task_id, last_error, created_at, issue_closed, can_manage, active_runs, scope FROM classified WHERE ($5::text='all' OR scope= $5)+ AND ($6::text='all' OR ($6='event' AND kind='event') OR ($6='at' AND kind='at') OR ($6='recurring' AND kind IN ('every','cron')))+ AND ($7::text='' OR agent_id::text= $7)+ AND ($8::text='' OR strpos(lower(issue_title||' '||issue_identifier||' '||agent_name),lower($8))>0)+), page AS (+ SELECT id, issue_id, issue_title, issue_identifier, agent_id, agent_name, kind, mode, event_types, filter_actor_type, filter_actor_id, filter_actor_name, filter_agent_id, filter_agent_name, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, revision, disabled_at, last_task_id, last_error, created_at, issue_closed, can_manage, active_runs, scope FROM filtered ORDER BY created_at DESC,id DESC LIMIT $10::int OFFSET $9::int+), details AS (+ SELECT p.id, p.issue_id, p.issue_title, p.issue_identifier, p.agent_id, p.agent_name, p.kind, p.mode, p.event_types, p.filter_actor_type, p.filter_actor_id, p.filter_actor_name, p.filter_agent_id, p.filter_agent_name, p.filter_task_id, p.interval_seconds, p.cron_expression, p.timezone, p.next_fire_at, p.enabled, p.revision, p.disabled_at, p.last_task_id, p.last_error, p.created_at, p.issue_closed, p.can_manage, p.active_runs, p.scope,r.status AS last_task_status,+ CASE WHEN r.id IS NOT NULL THEN jsonb_build_object(+ 'id',r.id,'agent_id',r.agent_id,'runtime_id',r.runtime_id,'issue_id',r.issue_id,'wakeup_id',p.id,+ 'status',r.status,'priority',r.priority,'created_at',r.created_at,'started_at',r.started_at,+ 'dispatched_at',r.dispatched_at,'completed_at',r.completed_at+ ) END AS task+ FROM page p+ LEFT JOIN LATERAL (+ SELECT candidate.id, candidate.agent_id, candidate.runtime_id, candidate.issue_id, candidate.status, candidate.priority, candidate.created_at, candidate.started_at, candidate.dispatched_at, candidate.completed_at, candidate.active FROM (+ (SELECT t.id,t.agent_id,t.runtime_id,t.issue_id,t.status,t.priority,t.created_at,t.started_at,t.dispatched_at,t.completed_at,1 AS active+ FROM agent_task_queue t WHERE t.context->>'wakeup_id'=p.id::text AND t.issue_id=p.issue_id AND t.agent_id=p.agent_id+ AND t.status IN ('queued','deferred','dispatched','running','waiting_local_directory')+ ORDER BY (t.status IN ('running','waiting_local_directory','dispatched')) DESC,t.created_at DESC,t.id DESC LIMIT 1)+ UNION ALL+ (SELECT t.id,t.agent_id,t.runtime_id,t.issue_id,t.status,t.priority,t.created_at,t.started_at,t.dispatched_at,t.completed_at,0 AS active+ FROM agent_task_queue t WHERE t.context->>'wakeup_id'=p.id::text AND t.issue_id=p.issue_id AND t.agent_id=p.agent_id+ AND t.status NOT IN ('queued','deferred','dispatched','running','waiting_local_directory')+ ORDER BY t.created_at DESC,t.id DESC LIMIT 1)+ ) candidate ORDER BY active DESC LIMIT 1+ ) r ON true+)+SELECT jsonb_build_object(+ 'items',COALESCE((SELECT jsonb_agg(to_jsonb(details)-'created_at'-'scope' ORDER BY created_at DESC,id DESC) FROM details),'[]'::jsonb),+ 'total',(SELECT count(*) FROM filtered),+ 'counts',jsonb_build_object('all',(SELECT count(*) FROM classified),'active',(SELECT count(*) FROM classified WHERE scope='active'),+ 'disabled',(SELECT count(*) FROM classified WHERE scope='disabled'),'ended',(SELECT count(*) FROM classified WHERE scope='ended')),+ 'agents',COALESCE((SELECT jsonb_agg(x ORDER BY x.name,x.id) FROM (SELECT DISTINCT agent_id AS id,agent_name AS name FROM base) x),'[]'::jsonb)+) AS result+`++type ListWorkspaceWakeupsParams struct {+ AgentIds []pgtype.UUID `json:"agent_ids"`+ MemberID pgtype.UUID `json:"member_id"`+ IsAdmin bool `json:"is_admin"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Scope string `json:"scope"`+ Kind string `json:"kind"`+ AgentID string `json:"agent_id"`+ Search string `json:"search"`+ PageOffset int32 `json:"page_offset"`+ PageLimit int32 `json:"page_limit"`+}++// Counts, filter choices, and page share one snapshot and the same access scope.+func (q *Queries) ListWorkspaceWakeups(ctx context.Context, arg ListWorkspaceWakeupsParams) ([]byte, error) {+ row := q.db.QueryRow(ctx, listWorkspaceWakeups,+ arg.AgentIds,+ arg.MemberID,+ arg.IsAdmin,+ arg.WorkspaceID,+ arg.Scope,+ arg.Kind,+ arg.AgentID,+ arg.Search,+ arg.PageOffset,+ arg.PageLimit,+ )+ var result []byte+ err := row.Scan(&result)+ return result, err+}diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex e70c6c1980..a4f684420d 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -538,7 +538,7 @@ INSERT INTO agent_task_queue (originator_source, delegated_from_task_id, rule_version_id,trigger_evidence_kind, trigger_evidence_ref_id, retry_of_task_id,chat_input_task_id, fire_at,- channel_context_revision, id+ channel_context_revision, handoff_note, id)SELECTp.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,@@ -559,6 +559,7 @@ SELECTp.trigger_evidence_kind, p.trigger_evidence_ref_id, p.id,p.chat_input_task_id, sqlc.narg(fire_at),p.channel_context_revision,+ CASE WHEN p.context->>'wakeup_id' IS NOT NULL THEN p.handoff_note END,-- Named new_task_id, not id: $1 above is the PARENT task's id.COALESCE(sqlc.narg('new_task_id')::uuid, gen_random_uuid())FROM agent_task_queue p@@ -781,6 +782,7 @@ WHERE id = (WHERE atq.agent_id = @agent_idAND atq.runtime_id = @runtime_idAND atq.status = 'queued'+ AND (atq.context->>'wakeup_id' IS NULL OR EXISTS (SELECT 1 FROM issue_wakeup w WHERE w.id=(atq.context->>'wakeup_id')::uuid AND w.disabled_at IS NULL AND w.revision=(atq.context->>'wakeup_revision')::bigint))AND EXISTS (SELECT 1FROM agent a@@ -1480,7 +1482,7 @@ RETURNING *;-- subsequent ticks.WITH victims AS (SELECT id FROM agent_task_queue- WHERE status = 'queued'+ WHERE status = 'queued' AND context->>'wakeup_id' IS NULLAND created_at < now() - make_interval(secs => @reconnect_grace_secs::double precision)AND (runtime_id IS NULL@@ -1807,7 +1809,7 @@ WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_l-- the agent picks up new comments on the next cycle) but skip if a pending-- task already exists (natural dedup).SELECT count(*) > 0 AS has_pending FROM agent_task_queue-WHERE issue_id = $1 AND status IN ('queued', 'dispatched');+WHERE context->>'wakeup_id' IS NULL AND issue_id = $1 AND status IN ('queued', 'dispatched');-- name: HasPendingTaskForIssueAndAgent :one-- Returns true if a specific agent already has a queued or dispatched task@@ -1822,7 +1824,7 @@ WHERE issue_id = $1 AND status IN ('queued', 'dispatched');-- When head_sha is empty/NULL (issue has no linked PR) the check falls back to-- the pre-TEN-356 (issue_id, agent_id) key so non-PR issues keep coalescing.SELECT count(*) > 0 AS has_pending FROM agent_task_queue-WHERE issue_id = $1 AND agent_id = $2+WHERE context->>'wakeup_id' IS NULL AND issue_id = $1 AND agent_id = $2AND (status IN ('queued', 'dispatched')OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')@@ -1836,7 +1838,7 @@ WHERE issue_id = $1 AND agent_id = $2-- Same pending/head rules as HasPendingTaskForIssueAndAgent, scoped to one-- root comment and all descendants. NULL selects assignment-level work.SELECT count(*) > 0 AS has_pending FROM agent_task_queue-WHERE issue_id = $1 AND agent_id = $2+WHERE context->>'wakeup_id' IS NULL AND issue_id = $1 AND agent_id = $2AND (status IN ('queued', 'dispatched')OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')@@ -1853,7 +1855,7 @@ WHERE issue_id = $1 AND agent_id = $2-- that comment's old queued/dispatched tasks before re-computing triggers.-- Carries the same head_sha dedup key as HasPendingTaskForIssueAndAgent (TEN-356).SELECT count(*) > 0 AS has_pending FROM agent_task_queue-WHERE issue_id = @issue_id+WHERE context->>'wakeup_id' IS NULL AND issue_id = @issue_idAND agent_id = @agent_idAND (status IN ('queued', 'dispatched')@@ -1868,7 +1870,7 @@ WHERE issue_id = @issue_id-- name: HasPendingTaskForIssueAndAgentExcludingTriggerCommentInThread :one-- Thread-scoped edit preview: ignore the comment whose old run save replaces.SELECT count(*) > 0 AS has_pending FROM agent_task_queue-WHERE issue_id = @issue_id+WHERE context->>'wakeup_id' IS NULL AND issue_id = @issue_idAND agent_id = @agent_idAND (status IN ('queued', 'dispatched')@@ -1950,7 +1952,7 @@ SET coalesced_comment_ids = (runtime_connected_apps = sqlc.narg('new_runtime_connected_apps')WHERE id = (SELECT t.id FROM agent_task_queue t- WHERE t.issue_id = @issue_id+ WHERE t.context->>'wakeup_id' IS NULL AND t.issue_id = @issue_idAND t.agent_id = @agent_idAND t.comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id(@new_trigger_comment_id::uuid)AND (@@ -2006,7 +2008,7 @@ SET coalesced_comment_ids = ()WHERE id = (SELECT t.id FROM agent_task_queue t- WHERE t.issue_id = @issue_id+ WHERE t.context->>'wakeup_id' IS NULL AND t.issue_id = @issue_idAND t.agent_id = @agent_idAND t.comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id(@comment_id::uuid)AND t.status IN ('dispatched', 'running', 'waiting_local_directory')@@ -2037,7 +2039,7 @@ SET coalesced_comment_ids = (trigger_summary = sqlc.narg('trigger_summary')WHERE id = (SELECT t.id FROM agent_task_queue t- WHERE t.issue_id = @issue_id+ WHERE t.context->>'wakeup_id' IS NULL AND t.issue_id = @issue_idAND t.agent_id = @agent_idAND t.comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id(@comment_id::uuid)AND (@@ -2300,6 +2302,7 @@ ORDER BY priority DESC, created_at ASC;SELECT atq.* FROM agent_task_queue atqWHERE atq.runtime_id = $1AND atq.status = 'queued'+ AND (atq.context->>'wakeup_id' IS NULL OR EXISTS (SELECT 1 FROM issue_wakeup w WHERE w.id=(atq.context->>'wakeup_id')::uuid AND w.disabled_at IS NULL AND w.revision=(atq.context->>'wakeup_revision')::bigint))AND EXISTS (-- Keep this authorization fence in sync with ClaimAgentTask.SELECT 1@@ -2420,6 +2423,7 @@ RETURNING *;SELECT atq.* FROM agent_task_queue atqWHERE atq.runtime_id = ANY(@runtime_ids::uuid[])AND atq.status = 'queued'+ AND (atq.context->>'wakeup_id' IS NULL OR EXISTS (SELECT 1 FROM issue_wakeup w WHERE w.id=(atq.context->>'wakeup_id')::uuid AND w.disabled_at IS NULL AND w.revision=(atq.context->>'wakeup_revision')::bigint))AND EXISTS (-- Keep this authorization fence in sync with ClaimAgentTask.SELECT 1@@ -2639,13 +2643,14 @@ ORDER BY atq.agent_id, bucket;-- grows with how much terminal history the workspace has accumulated. The-- (created_at, id) tie-break makes the pick deterministic when completed_at-- ties or is NULL — plain completed_at DESC returned an arbitrary row there.--- Row shape and row set are unchanged.+-- Deferred wakeup retries also remain visible as queued work.---- Both halves JOIN / scan agent because agent_task_queue has no workspace_id.SELECT atq.* FROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idWHERE a.workspace_id = $1- AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+ AND (atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+ OR (atq.status='deferred' AND atq.context->>'wakeup_id' IS NOT NULL))UNION ALLdiff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex 5d5d8b845f..f8085fb2f8 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -193,7 +193,7 @@ SELECT * FROM issueWHERE workspace_id = $1 AND number = $2;-- name: UpdateIssue :one-WITH candidate AS (+WITH wakeup_source AS MATERIALIZED (SELECT set_config('multica.source_task_id', COALESCE(sqlc.narg('source_task_id')::uuid::text, ''), true)), candidate AS (SELECTi.*,COALESCE(sqlc.narg('title')::text, i.title) AS next_title,@@ -278,7 +278,7 @@ UPDATE issue AS i SETELSE i.last_activity_atEND,updated_at = CASE WHEN changed.did_change THEN now() ELSE i.updated_at END-FROM changed+FROM changed CROSS JOIN wakeup_sourceWHERE i.id = changed.id-- Re-check the precondition on the row version that UPDATE actually locks.-- Under READ COMMITTED, concurrent statements may both populate candidate@@ -293,6 +293,7 @@ RETURNING i.*;-- completion) so a status write cannot land without one: an issue carrying its-- old column's rank into a new column is the bug this guards against. See the-- next_position CASE in UpdateIssue for the policy.+WITH wakeup_source AS MATERIALIZED (SELECT set_config('multica.source_task_id', COALESCE(sqlc.narg('source_task_id')::uuid::text, ''), true))UPDATE issue AS i SETstatus = $2,position = CASE WHEN i.status IS DISTINCT FROM $2 THEN (@@ -307,8 +308,9 @@ UPDATE issue AS i SETELSE i.last_activity_atEND,updated_at = now()+FROM wakeup_sourceWHERE i.id = $1 AND i.workspace_id = $3-RETURNING *;+RETURNING i.*;-- name: CreateIssueWithOrigin :oneINSERT INTO issue (@@ -383,6 +385,12 @@ LIMIT 1;WITH target AS (SELECT issue.id FROM issue WHERE issue.id = $1 AND issue.workspace_id = $2),+cleared_wakeup_receipts AS (+ DELETE FROM issue_wakeup_receipt WHERE wakeup_id IN (SELECT id FROM issue_wakeup WHERE issue_id IN (SELECT target.id FROM target))+),+cleared_wakeups AS (+ DELETE FROM issue_wakeup WHERE issue_id IN (SELECT target.id FROM target)+),cleared_vcs_pr_links AS (DELETE FROM issue_vcs_pull_request WHERE issue_id IN (SELECT target.id FROM target))diff --git a/server/pkg/db/queries/wakeup.sql b/server/pkg/db/queries/wakeup.sqlnew file mode 100644index 0000000000..b4b17f8eeb--- /dev/null+++ b/server/pkg/db/queries/wakeup.sql@@ -0,0 +1,151 @@+-- name: CreateIssueWakeup :one+INSERT INTO issue_wakeup(id,workspace_id,issue_id,agent_id,created_by,source_task_id,parent_comment_id,instruction,kind,mode,event_types,filter_agent_id,filter_task_id,filter_actor_type,filter_actor_id,interval_seconds,cron_expression,timezone,next_fire_at)+VALUES(@id,@workspace_id,@issue_id,@agent_id,@created_by,sqlc.narg(source_task_id),sqlc.narg(parent_comment_id),@instruction,@kind,@mode,@event_types,sqlc.narg(filter_agent_id),sqlc.narg(filter_task_id),sqlc.narg(filter_actor_type),sqlc.narg(filter_actor_id),sqlc.narg(interval_seconds),sqlc.narg(cron_expression),@timezone,sqlc.narg(next_fire_at)) RETURNING *;+-- name: ListIssueWakeups :many+SELECT w.id,w.workspace_id,w.issue_id,w.agent_id,w.created_by,w.source_task_id,w.parent_comment_id,w.instruction,+ w.kind,w.mode,w.event_types,w.filter_actor_type,+ (CASE WHEN actor_agent.id IS NOT NULL OR actor_member.user_id IS NOT NULL THEN w.filter_actor_id END)::uuid AS filter_actor_id,+ COALESCE(actor_agent.name,actor_user.name,'')::text AS filter_actor_name,+ (CASE WHEN source.id IS NOT NULL THEN w.filter_agent_id END)::uuid AS filter_agent_id,+ (CASE WHEN EXISTS(SELECT 1 FROM agent_task_queue ft JOIN agent fa ON fa.id=ft.agent_id AND fa.workspace_id=w.workspace_id+ WHERE ft.id=w.filter_task_id AND ft.issue_id=w.issue_id AND fa.id=ANY(@agent_ids::uuid[])) THEN w.filter_task_id END)::uuid AS filter_task_id,+ w.interval_seconds,w.cron_expression,w.timezone,w.next_fire_at,w.enabled,w.disabled_at,w.revision,+ w.last_task_id,w.last_error,w.created_at,w.updated_at,a.name AS agent_name,source.name AS filter_agent_name,t.status AS last_task_status+FROM issue_wakeup w JOIN agent a ON a.id=w.agent_id AND a.workspace_id=w.workspace_id+LEFT JOIN agent actor_agent ON w.filter_actor_type='agent' AND actor_agent.id=w.filter_actor_id AND actor_agent.workspace_id=w.workspace_id AND actor_agent.id=ANY(@agent_ids::uuid[])+LEFT JOIN member actor_member ON w.filter_actor_type='member' AND actor_member.user_id=w.filter_actor_id AND actor_member.workspace_id=w.workspace_id+LEFT JOIN "user" actor_user ON actor_user.id=actor_member.user_id+LEFT JOIN agent source ON source.id=w.filter_agent_id AND source.workspace_id=w.workspace_id AND source.id=ANY(@agent_ids::uuid[])+LEFT JOIN agent_task_queue t ON t.id=w.last_task_id AND t.issue_id=w.issue_id AND t.agent_id=w.agent_id+WHERE w.workspace_id= @workspace_id AND w.issue_id= @issue_id ORDER BY w.created_at,w.id;++-- name: ListWorkspaceWakeupSummaryRows :many+-- No prompts/history; at most three previews per issue plus exact counts.+WITH ranked AS (+ SELECT w.issue_id,w.id,w.agent_id,a.name AS agent_name,w.kind,w.mode,w.event_types,w.filter_actor_type,+ (CASE WHEN actor_agent.id IS NOT NULL OR actor_member.user_id IS NOT NULL THEN w.filter_actor_id END)::uuid AS filter_actor_id,+ COALESCE(actor_agent.name,actor_user.name,'')::text AS filter_actor_name,+ (CASE WHEN EXISTS(SELECT 1 FROM agent_task_queue ft JOIN agent fa ON fa.id=ft.agent_id AND fa.workspace_id=w.workspace_id+ WHERE ft.id=w.filter_task_id AND ft.issue_id=w.issue_id AND fa.id=ANY(@agent_ids::uuid[])) THEN w.filter_task_id END)::uuid AS filter_task_id,+ source.name AS filter_agent_name,w.interval_seconds,w.cron_expression,w.timezone,w.next_fire_at,+ count(*) OVER(PARTITION BY w.issue_id) AS active_count,+ count(*) FILTER(WHERE w.kind='event') OVER(PARTITION BY w.issue_id) AS event_count,+ row_number() OVER(PARTITION BY w.issue_id ORDER BY w.next_fire_at NULLS LAST,w.created_at,w.id) AS rank+ FROM issue_wakeup w+ JOIN issue i ON i.id=w.issue_id AND i.workspace_id=w.workspace_id+ JOIN agent a ON a.id=w.agent_id AND a.workspace_id=w.workspace_id+ LEFT JOIN agent actor_agent ON w.filter_actor_type='agent' AND actor_agent.id=w.filter_actor_id AND actor_agent.workspace_id=w.workspace_id AND actor_agent.id=ANY(@agent_ids::uuid[])+LEFT JOIN member actor_member ON w.filter_actor_type='member' AND actor_member.user_id=w.filter_actor_id AND actor_member.workspace_id=w.workspace_id+LEFT JOIN "user" actor_user ON actor_user.id=actor_member.user_id+LEFT JOIN agent source ON source.id=w.filter_agent_id AND source.workspace_id=w.workspace_id AND source.id=ANY(@agent_ids::uuid[])+ WHERE w.workspace_id= @workspace_id AND w.enabled+ AND i.status NOT IN ('done','cancelled')+ AND NOT EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'))+)+SELECT issue_id,id,agent_id,agent_name,kind,mode,event_types,filter_actor_type,filter_actor_id,filter_actor_name,filter_task_id,filter_agent_name,interval_seconds,cron_expression,timezone,next_fire_at,active_count,event_count+FROM ranked WHERE rank<=3 ORDER BY issue_id,rank;+-- name: GetIssueWakeup :one+SELECT * FROM issue_wakeup WHERE id= @id AND workspace_id= @workspace_id;+-- name: LockIssueWakeup :one+SELECT * FROM issue_wakeup WHERE id= @id FOR UPDATE;+-- name: LockWakeupIssue :one+SELECT * FROM issue WHERE id= @id FOR NO KEY UPDATE;+-- name: LockWakeupSourceTask :one+SELECT * FROM agent_task_queue WHERE id= @id AND issue_id= @issue_id FOR UPDATE NOWAIT;+-- name: CancelUnstartedWakeupTasks :many+UPDATE agent_task_queue SET status='cancelled',completed_at=now(),error='Wakeup disabled or updated'+WHERE context->>'wakeup_id'= @wakeup_id::text AND status IN ('queued','deferred') AND started_at IS NULL RETURNING *;+-- name: ListReadyWakeups :many+WITH candidates AS (+ SELECT id FROM issue_wakeup WHERE enabled AND kind<>'event' AND next_fire_at<=now()+ UNION+ SELECT wakeup_id FROM issue_wakeup_receipt WHERE processed_at IS NULL+)+SELECT w.* FROM candidates c JOIN issue_wakeup w ON w.id=c.id+ORDER BY w.updated_at,w.id LIMIT 100;+-- name: ListPendingWakeupReceipts :many+SELECT * FROM issue_wakeup_receipt WHERE wakeup_id= @wakeup_id AND revision= @revision AND processed_at IS NULL ORDER BY created_at,id LIMIT 100 FOR UPDATE;++-- name: DeleteExpiredWakeupReceipts :execrows+-- Pending inputs are never expired. Bound work and avoid waiting on dispatch.+DELETE FROM issue_wakeup_receipt WHERE id IN (+ SELECT expired.id FROM issue_wakeup_receipt expired WHERE expired.processed_at < @cutoff+ ORDER BY expired.processed_at,expired.id LIMIT 1000 FOR UPDATE SKIP LOCKED+);+-- name: RecordWakeupReceipt :one+INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload)+VALUES(@id,@wakeup_id,@revision,@event_key,@event_type,@payload)+ON CONFLICT(wakeup_id,revision,event_key) DO UPDATE SET event_key=EXCLUDED.event_key RETURNING *;+-- name: ConsumeWakeupReceipts :exec+UPDATE issue_wakeup_receipt SET task_id=sqlc.narg(task_id),processed_at=now() WHERE id=ANY(@ids::uuid[]);+-- name: DiscardWakeupReceipts :exec+UPDATE issue_wakeup_receipt SET processed_at=now() WHERE wakeup_id= @id AND processed_at IS NULL;+-- name: AdvanceIssueWakeup :exec+UPDATE issue_wakeup SET enabled= @enabled,next_fire_at=sqlc.narg(next_fire_at),last_task_id=COALESCE(sqlc.narg(last_task_id),last_task_id),last_error=sqlc.narg(last_error),updated_at=clock_timestamp() WHERE id= @id;+-- name: FindPendingWakeupTask :one+SELECT * FROM agent_task_queue WHERE context->>'wakeup_id'= @wakeup_id::text AND status IN ('queued','dispatched') ORDER BY created_at LIMIT 1 FOR UPDATE;++-- name: CreateWakeupTask :one+-- Fenced against workspace teardown: lock_task_owner_rows (migration 284)+-- locks the owners' workspace rows in the writer's own transaction and returns+-- false once they are gone, so this statement writes no row instead of stranding+-- a task in a workspace that has just been deleted (MUL-5999).+-- head_sha stamps the commit under review into the task's context JSONB so the+-- reviewer-loop dedup (HasPendingTaskForIssueAndAgent) can tell a pending run+-- against an OLD head apart from a fresh request against a NEW head (TEN-356).+-- Empty/absent head_sha leaves context NULL, preserving pre-TEN-356 behavior for+-- issues with no linked PR. Issue-linked tasks never hit quick-create context+-- parsing (parseQuickCreateContext short-circuits on IssueID.Valid), so this+-- key rides harmlessly alongside.+-- id is minted by the application as a UUIDv7 (pkg/dbid) so consecutive+-- enqueues cluster in a narrow contiguous primary-key range instead of+-- scattering across the B-tree. On a table with existing v4 ids, that range+-- is not necessarily the tree's right edge.+-- COALESCE keeps the column's gen_random_uuid() default reachable, so a caller+-- that passes no id still inserts — it just gets a random v4, exactly as before.+-- The same pattern is used by every INSERT listed in pkg/dbid's write table.+INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,+ coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,+ squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,+ originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id, trigger_evidence_kind, trigger_evidence_ref_id,+ id+)+SELECT+ $1, $2, $3, 'queued', $4, sqlc.narg(trigger_comment_id),+ COALESCE(sqlc.narg(coalesced_comment_ids)::uuid[], '{}'),+ sqlc.narg(trigger_summary),+ COALESCE(sqlc.narg('force_fresh_session')::boolean, FALSE),+ COALESCE(sqlc.narg('is_leader_task')::boolean, FALSE),+ sqlc.narg(handoff_note),+ sqlc.narg(squad_id),+ CASE+ WHEN COALESCE(sqlc.narg('head_sha')::text, '') <> ''+ THEN jsonb_build_object('head_sha', sqlc.narg('head_sha')::text)+ ELSE '{}'::jsonb+ END || @wakeup_context::jsonb,+ sqlc.narg(originator_user_id),+ sqlc.narg(accountable_user_id),+ sqlc.narg(runtime_mcp_overlay),+ sqlc.narg(runtime_connected_apps),+ sqlc.narg(originator_source),+ sqlc.narg(delegated_from_task_id),+ sqlc.narg(rule_version_id),+ sqlc.narg(rerun_of_task_id),+ sqlc.narg(trigger_evidence_kind),+ sqlc.narg(trigger_evidence_ref_id),+ COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())+WHERE lock_task_owner_rows($1, $3, $2)+RETURNING *;++-- name: LocklessWakeup :one+SELECT * FROM issue_wakeup WHERE id= @id;++-- name: ReplaceWakeupEvidence :one+UPDATE agent_task_queue SET handoff_note=sqlc.narg(handoff_note), context=COALESCE(context,'{}'::jsonb) || jsonb_build_object('wakeup_evidence', @wakeup_evidence::jsonb) WHERE id= @id AND status='queued' RETURNING *;+-- name: NoteWakeupFailure :exec+UPDATE issue_wakeup SET last_error=sqlc.narg(last_error),updated_at=clock_timestamp() WHERE id= @id;+-- name: TouchWakeupDispatch :exec+-- Move blocked configurations to the back of the scan so one noisy issue+-- cannot monopolize the bounded batch.+UPDATE issue_wakeup SET updated_at=clock_timestamp() WHERE id= @id;diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sqlindex 82d8d4bf50..9e8f5c3f73 100644--- a/server/pkg/db/queries/workspace_delete.sql+++ b/server/pkg/db/queries/workspace_delete.sql@@ -544,7 +544,11 @@ deleted_comment_agent_deliveries AS (DELETE FROM comment WHERE id IN (SELECT id FROM ws_comments);-- name: DeleteWorkspaceIssueRoots :exec-WITH+WITH deleted_wakeup_receipts AS (+ DELETE FROM issue_wakeup_receipt WHERE wakeup_id IN (SELECT id FROM issue_wakeup WHERE workspace_id=$1)+), deleted_wakeups AS (+ DELETE FROM issue_wakeup WHERE workspace_id=$1+),deleted_issues AS (DELETE FROM issue WHERE issue.workspace_id = $1),diff --git a/server/pkg/db/queries/workspace_wakeup.sql b/server/pkg/db/queries/workspace_wakeup.sqlnew file mode 100644index 0000000000..0ba7e29efa--- /dev/null+++ b/server/pkg/db/queries/workspace_wakeup.sql@@ -0,0 +1,70 @@+-- name: ListWorkspaceWakeups :one+-- Counts, filter choices, and page share one snapshot and the same access scope.+WITH base AS MATERIALIZED (+ SELECT w.id,w.issue_id,i.title AS issue_title,ws.issue_prefix||'-'||i.number AS issue_identifier,+ w.agent_id,a.name AS agent_name,w.kind,w.mode,w.event_types,w.filter_actor_type,+ (CASE WHEN actor_agent.id IS NOT NULL OR actor_member.user_id IS NOT NULL THEN w.filter_actor_id END)::uuid AS filter_actor_id,+ COALESCE(actor_agent.name,actor_user.name,'')::text AS filter_actor_name,+ CASE WHEN source.id IS NOT NULL THEN w.filter_agent_id END AS filter_agent_id,+ source.name AS filter_agent_name,+ CASE WHEN EXISTS(SELECT 1 FROM agent_task_queue ft JOIN agent fa ON fa.id=ft.agent_id AND fa.workspace_id=w.workspace_id+ WHERE ft.id=w.filter_task_id AND ft.issue_id=w.issue_id AND fa.id=ANY(@agent_ids::uuid[])) THEN w.filter_task_id END AS filter_task_id,+ w.interval_seconds,w.cron_expression,w.timezone,+ w.next_fire_at,w.enabled,w.revision,w.disabled_at,w.last_task_id,w.last_error,w.created_at,+ (i.status IN ('done','cancelled') OR EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'))) AS issue_closed,+ COALESCE((w.created_by= @member_id::uuid OR @is_admin::boolean),false) AS can_manage,+ COALESCE(r.active_runs,0)::int AS active_runs+ FROM issue_wakeup w+ JOIN workspace ws ON ws.id=w.workspace_id+ JOIN issue i ON i.id=w.issue_id AND i.workspace_id=w.workspace_id+ JOIN agent a ON a.id=w.agent_id AND a.workspace_id=w.workspace_id+ LEFT JOIN agent actor_agent ON w.filter_actor_type='agent' AND actor_agent.id=w.filter_actor_id AND actor_agent.workspace_id=w.workspace_id AND actor_agent.id=ANY(@agent_ids::uuid[])+LEFT JOIN member actor_member ON w.filter_actor_type='member' AND actor_member.user_id=w.filter_actor_id AND actor_member.workspace_id=w.workspace_id+LEFT JOIN "user" actor_user ON actor_user.id=actor_member.user_id+ LEFT JOIN agent source ON source.id=w.filter_agent_id AND source.workspace_id=w.workspace_id AND source.id=ANY(@agent_ids::uuid[])+ LEFT JOIN LATERAL (+ SELECT count(*) AS active_runs FROM agent_task_queue t+ WHERE t.context->>'wakeup_id'=w.id::text AND t.issue_id=w.issue_id AND t.agent_id=w.agent_id+ AND t.status IN ('queued','deferred','dispatched','running','waiting_local_directory')+ ) r ON true+ WHERE w.workspace_id= @workspace_id+), classified AS (+ SELECT *,CASE WHEN (enabled AND NOT issue_closed) OR active_runs>0 THEN 'active'+ WHEN NOT issue_closed AND disabled_at IS NOT NULL THEN 'disabled' ELSE 'ended' END AS scope+ FROM base+), filtered AS (+ SELECT * FROM classified WHERE (@scope::text='all' OR scope= @scope)+ AND (@kind::text='all' OR (@kind='event' AND kind='event') OR (@kind='at' AND kind='at') OR (@kind='recurring' AND kind IN ('every','cron')))+ AND (@agent_id::text='' OR agent_id::text= @agent_id)+ AND (@search::text='' OR strpos(lower(issue_title||' '||issue_identifier||' '||agent_name),lower(@search))>0)+), page AS (+ SELECT * FROM filtered ORDER BY created_at DESC,id DESC LIMIT @page_limit::int OFFSET @page_offset::int+), details AS (+ SELECT p.*,r.status AS last_task_status,+ CASE WHEN r.id IS NOT NULL THEN jsonb_build_object(+ 'id',r.id,'agent_id',r.agent_id,'runtime_id',r.runtime_id,'issue_id',r.issue_id,'wakeup_id',p.id,+ 'status',r.status,'priority',r.priority,'created_at',r.created_at,'started_at',r.started_at,+ 'dispatched_at',r.dispatched_at,'completed_at',r.completed_at+ ) END AS task+ FROM page p+ LEFT JOIN LATERAL (+ SELECT candidate.* FROM (+ (SELECT t.id,t.agent_id,t.runtime_id,t.issue_id,t.status,t.priority,t.created_at,t.started_at,t.dispatched_at,t.completed_at,1 AS active+ FROM agent_task_queue t WHERE t.context->>'wakeup_id'=p.id::text AND t.issue_id=p.issue_id AND t.agent_id=p.agent_id+ AND t.status IN ('queued','deferred','dispatched','running','waiting_local_directory')+ ORDER BY (t.status IN ('running','waiting_local_directory','dispatched')) DESC,t.created_at DESC,t.id DESC LIMIT 1)+ UNION ALL+ (SELECT t.id,t.agent_id,t.runtime_id,t.issue_id,t.status,t.priority,t.created_at,t.started_at,t.dispatched_at,t.completed_at,0 AS active+ FROM agent_task_queue t WHERE t.context->>'wakeup_id'=p.id::text AND t.issue_id=p.issue_id AND t.agent_id=p.agent_id+ AND t.status NOT IN ('queued','deferred','dispatched','running','waiting_local_directory')+ ORDER BY t.created_at DESC,t.id DESC LIMIT 1)+ ) candidate ORDER BY active DESC LIMIT 1+ ) r ON true+)+SELECT jsonb_build_object(+ 'items',COALESCE((SELECT jsonb_agg(to_jsonb(details)-'created_at'-'scope' ORDER BY created_at DESC,id DESC) FROM details),'[]'::jsonb),+ 'total',(SELECT count(*) FROM filtered),+ 'counts',jsonb_build_object('all',(SELECT count(*) FROM classified),'active',(SELECT count(*) FROM classified WHERE scope='active'),+ 'disabled',(SELECT count(*) FROM classified WHERE scope='disabled'),'ended',(SELECT count(*) FROM classified WHERE scope='ended')),+ 'agents',COALESCE((SELECT jsonb_agg(x ORDER BY x.name,x.id) FROM (SELECT DISTINCT agent_id AS id,agent_name AS name FROM base) x),'[]'::jsonb)+) AS result;diff --git a/server/pkg/eventcontract/events.go b/server/pkg/eventcontract/events.gonew file mode 100644index 0000000000..47d3275b30--- /dev/null+++ b/server/pkg/eventcontract/events.go@@ -0,0 +1,58 @@+// Package eventcontract names business facts independently of plugins or transport.+package eventcontract++const (+ EventIssueCreated = "issue.created"+ EventIssueDeleted = "issue.deleted"+ EventIssueUpdated = "issue.updated"+ EventIssueStatusChanged = "issue.status_changed"+ EventIssueAssigneeChanged = "issue.assignee_changed"+ EventIssueParentChanged = "issue.parent_changed"+ EventIssueProjectChanged = "issue.project_changed"+ EventIssueLabelsChanged = "issue.labels_changed"+ EventIssuePropertiesChanged = "issue.properties_changed"+ EventIssueMetadataChanged = "issue.metadata_changed"+ EventCommentCreated = "comment.created"+ EventCommentUpdated = "comment.updated"+ EventCommentDeleted = "comment.deleted"+ EventCommentResolved = "comment.resolved"+ EventCommentUnresolved = "comment.unresolved"+ EventTaskQueued = "task.queued"+ EventTaskDispatched = "task.dispatched"+ EventTaskDeferred = "task.deferred"+ EventTaskWaitingLocalDirectory = "task.waiting_local_directory"+ EventTaskStarted = "task.started"+ EventTaskCompleted = "task.completed"+ EventTaskFailed = "task.failed"+ EventTaskCancelled = "task.cancelled"+ EventReactionAdded = "reaction.added"+ EventReactionRemoved = "reaction.removed"+ EventAttachmentAttached = "attachment.attached"+ EventAttachmentDetached = "attachment.detached"+)++// WakeupTypes lists only facts with transactional capture, not every bus event.+var WakeupTypes = []string{+ EventTaskQueued, EventTaskDispatched, EventTaskStarted, EventTaskDeferred,+ EventTaskWaitingLocalDirectory, EventTaskCompleted, EventTaskFailed, EventTaskCancelled,+ EventIssueUpdated, EventIssueStatusChanged, EventIssueAssigneeChanged, EventIssueParentChanged,+ EventIssueProjectChanged, EventIssueLabelsChanged, EventIssuePropertiesChanged, EventIssueMetadataChanged,+ EventCommentCreated, EventCommentUpdated, EventCommentDeleted, EventCommentResolved, EventCommentUnresolved,+ EventReactionAdded, EventReactionRemoved, EventAttachmentAttached, EventAttachmentDetached,+}++// Lifecycle events exist on the platform but cannot wake their own issue:+// subscription requires an existing issue, and deletion withdraws its work.+var LifecycleTypes = []string{EventIssueCreated, EventIssueDeleted}++// TaskEvent translates persisted states to the public vocabulary.+func TaskEvent(status string) string {+ switch status {+ case "running":+ return EventTaskStarted+ case "queued", "dispatched", "deferred", "waiting_local_directory", "completed", "failed", "cancelled":+ return "task." + status+ default:+ return ""+ }+}diff --git a/server/pkg/plugincontract/manifest.go b/server/pkg/plugincontract/manifest.goindex c1b6ce2c50..249d578f18 100644--- a/server/pkg/plugincontract/manifest.go+++ b/server/pkg/plugincontract/manifest.go@@ -22,6 +22,7 @@ import ("strings""time"+ "github.com/multica-ai/multica/server/pkg/eventcontract""github.com/robfig/cron/v3")@@ -107,13 +108,13 @@ const (// Product events an `event`-triggered hook may subscribe to.const (- EventIssueCreated = "issue.created"- EventIssueUpdated = "issue.updated"- EventIssueStatusChanged = "issue.status_changed"- EventCommentCreated = "comment.created"- EventTaskStarted = "task.started"- EventTaskCompleted = "task.completed"- EventTaskFailed = "task.failed"+ EventIssueCreated = eventcontract.EventIssueCreated+ EventIssueUpdated = eventcontract.EventIssueUpdated+ EventIssueStatusChanged = eventcontract.EventIssueStatusChanged+ EventCommentCreated = eventcontract.EventCommentCreated+ EventTaskStarted = eventcontract.EventTaskStarted+ EventTaskCompleted = eventcontract.EventTaskCompleted+ EventTaskFailed = eventcontract.EventTaskFailed)var fixedScopes = map[string]bool{