Files
multica/server/internal/handler/issue_trigger_preview_test.go
Naiyuan Qing 4ab335b8a5 MUL-3416: Issue pre-trigger preview + Handoff Note (#4383)
* feat(issues): unify run-enqueue decision behind WillEnqueueRun + preview endpoint

Collapse the issue update/batch enqueue copies into one service predicate
service.IssueService.WillEnqueueRun, shared verbatim with a new dry-run
endpoint POST /api/issues/preview-trigger so the four entry points stop
drifting (squad/self-loop/batch omissions, MUL-3375). The private-agent gate
stays at the HTTP boundary: write paths inject allow-all, preview injects the
real gate so it never leaks a private agent's readiness.

Add suppress_run to issue update/batch: the change applies but no run starts.
Remove the now-dead handler mirrors shouldEnqueueSquadLeaderOnAssign /
isSquadLeaderReady. service.Create and the comment trigger chain are untouched.

Tests: preview behavior, preview<->write-path match, batch aggregation,
member no-trigger, suppress_run skip, malformed-body 400.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(issues): inject handoff note into assigned runs via first-class task field

Add an optional handoff_note carried by issue assign/promote into the run's
opening prompt and issue_context.md, via a dedicated agent_task_queue column
(migration 122) and a daemon assignment-handoff render branch — never a
fabricated comment, never trigger_comment_id (MUL-3375 §6.1).

Thread the note through enqueueIssueTask/enqueueMentionTask + WithHandoff
public variants and dispatchIssueRun; suppress_run or a parked write drops it
(no run = nothing to inject). Soft version gate: MinHandoffCLIVersion +
HandoffSupported, surfaced per-trigger as handoff_supported in the preview so
the UI can gray the note box on old daemons; the assignment never hard-fails.

Tests: daemon prompt + issue_context render via the assignment branch (not
quick-create/comment), version helper matrix, note persists on the task,
suppressed assign enqueues nothing.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(issues): leave a display-only handoff record on the timeline

When an assign/promote with a handoff note starts a run, write one
type='handoff' timeline record via TaskService.RecordHandoff — a direct
Queries.CreateComment + timeline event that bypasses Handler.CreateComment, so
it never reaches triggerTasksForComment and cannot start a second run
(MUL-3375 §6.2, the must-not-retrigger invariant). Author is the actor who
handed off; body is the note. Migration 123 admits the 'handoff' comment type.
Recorded only on a real run start: suppress_run or a parked write writes
nothing. enqueueSquadLeaderTask now reports whether it enqueued so the trace
is gated on an actual dispatch.

Test: exactly one handoff record on assign-with-note, exactly one task (no
re-trigger), and no record when suppressed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(issues): frontend plumbing for issue-trigger preview + handoff (core)

Add api.previewIssueTrigger + IssueTriggerPreviewSchema (zod parseWithFallback),
the use-issue-trigger-preview hook, issueKeys.issueTriggerPreview(+All) with WS
queue-state invalidation, suppress_run/handoff_note on UpdateIssueRequest, the
'handoff' CommentType, and stripping of the control fields from optimistic
update/batch cache patches (MUL-3375 §9).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(issues): exclude handoff records from new-comment counting

type='handoff' is a display-only timeline record, not conversation. Exclude it
from CountNewCommentsSince so a handoff note never inflates the count of
"new comments to catch up on" fed to a claiming agent (MUL-3375 §12). Analytics
already excludes it (RecordHandoff is a direct write that emits no analytics
event), and the comment-trigger path is already bypassed.

Test: a handoff record does not bump the new-comment count; a real comment does.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(issues): pre-trigger preview UI, handoff note, timeline card (web/desktop)

Wire the §9 frontend onto the preview endpoint + handoff fields:
- Delete the backlog blocking dialog (backlog-agent-hint*) and its modal type;
  the over-eager nag is gone. Backlog awareness is now a passive label.
- RunConfirmModal: single assign + batch assign/status route here. Shows the
  backend predicate's verdict ("将启动 @X" / "将启动 N 个" / parked), an optional
  handoff note (assign only, soft-gated by handoff_supported), and 暂不启动 —
  then applies via update/batch. No frontend guessing.
- create modal: passive CreateRunHint ("将启动 @X" / backlog parked).
- single status change stays a direct apply (unchanged).
- timeline: render type='handoff' as a distinct, non-interactive handoff card.
- i18n run_confirm + handoff_card across en/ja/ko/zh-Hans; drop backlog action
  keys; locale parity green.

Tests: use-issue-actions (assign → run-confirm modal, member → direct),
create-issue + comment-card suites updated/green; views typecheck + lint clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* test(issues): use a valid anchor in the handoff count-exclusion test

CountNewCommentsSince filters id <> @anchor_id; SQL id <> NULL is NULL and
excludes every row, so an empty anchor made the control assertion read 0. The
production caller always passes a real anchor — mirror that with a non-matching
sentinel uuid.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* test(issues): RunConfirmModal apply logic (start/suppress/note-gate/batch)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* test(core): preview schema malformed/missing/null fallback coverage

Cover IssueTriggerPreviewSchema via parseWithFallback (MUL-3375): well-formed
parse, top-level + item default fills (empty/older backend), and fallback to
{ triggers: [], total_count: 0 } for malformed shapes, a dropped required
issue_id, a wrong-typed total_count, and null/non-object bodies — so the four
entry points degrade to "nothing will start" instead of throwing.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* refactor(issues): remove display-only handoff timeline record (留痕)

The handoff "留痕" timeline record (type='handoff' comment written on run
start) was judged superfluous and dropped per product call. This removes
only the display-only trace; the handoff NOTE injection into the run's
opening prompt + issue_context.md is untouched.

- backend: drop RecordHandoff + its call in dispatchIssueRun
- db: drop the `type <> 'handoff'` exclusion in CountNewCommentsSince and
  migration 123 (comment_type_check reverts to the 4-type set from 001);
  no production data exists for this unreleased feature
- frontend: drop the "handoff" CommentType, HandoffCard, and handoff_card
  i18n (all locales)
- tests: drop handoff_count_test.go and the record-write assertions in
  issue_trigger_preview_test.go (note-injection tests retained)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(issues): dismissable run-confirm modal + team-handoff copy

Two fixes to the pre-trigger confirm modal (MUL-3375).

1. Dismissable: switch RunConfirmModal from AlertDialog to the standard
   shadcn Dialog so it has the close (X) button + Esc + click-outside.
   Previously the only choices were "start" / "don't start now" with no
   way to abort the action entirely; dismissing now cancels with no write.

2. Copy: rework the action-surface wording away from the backend term
   "run" toward team-handoff voice — 指派 / 开始 / 交接 (run stays only on
   record surfaces). Unifies the note's three names to "交接说明", and
   parallels the rewrite across en/ja/ko.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* chore(agent): bump handoff note min CLI version to 0.3.28

The daemon release that renders handoff notes ships in 0.3.28 (0.3.27
was the prior tag), so move the soft-gate threshold up. Below this the
note is silently dropped and the frontend grays the note box — assignment
is never blocked.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(issues): skip run-confirm when batch-moving issues to backlog

A move into backlog never starts a run (service/issue_trigger.go), so the
pre-trigger confirm modal degenerated to an empty "won't start" box with a
single Apply button — pure friction. Apply directly instead, matching the
single-issue status path. Other target statuses still route through the
modal.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(issues): refine pre-trigger preview hint and copy

- Move the create-issue run hint to a reveal band (grid 0fr→1fr) above the
  property toolbar. It was sharing the footer button row and, lacking a
  width constraint, reflowed the submit buttons whenever it appeared.
  Restyle to a borderless, comment-style avatar+caption that is purely a
  caption (non-interactive avatar).
- Distinguish squad from agent in the pre-trigger copy: a squad's leader
  evaluates and delegates rather than "starting work" itself. Add
  will_start_named_squad / will_start_squad / create_will_start_squad across
  en/zh/ja/ko (reusing the squad_leader_* evaluate→arrange vocabulary) and
  branch run-confirm + the create hint on squad assignees.
- Bold the assignee name in the run-confirm headline via a language-safe
  sentinel split (no per-language prefix/suffix keys).
- Align zh "开始处理" → "开始工作" on the single-assign copy.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(issues): stub ActorAvatar in create-issue suite

CreateRunHint now renders an ActorAvatar for agent/squad assignees, which
pulls in getActorInitials/getActorAvatarUrl + the workspace/presence/navigation
hook tree. This form-focused suite only stubbed getActorName, so the
squad-forwarding test crashed with "getActorInitials is not a function". Stub
the avatar inert — its own behavior is covered elsewhere.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Walt <walt@multica.ai>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>
2026-06-23 13:17:13 +08:00

279 lines
10 KiB
Go

package handler
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// seededReadyAgentID returns a workspace agent that has a runtime bound (the
// fixture's first agent), so WillEnqueueRun treats it as ready.
func seededReadyAgentID(t *testing.T) string {
t.Helper()
var id string
if err := testPool.QueryRow(context.Background(), `
SELECT id FROM agent WHERE workspace_id = $1 AND runtime_id IS NOT NULL
ORDER BY created_at ASC LIMIT 1
`, testWorkspaceID).Scan(&id); err != nil {
t.Fatalf("load ready agent: %v", err)
}
return id
}
func previewIssueTrigger(t *testing.T, body map[string]any) IssueTriggerPreviewResponse {
t.Helper()
w := httptest.NewRecorder()
req := newRequest("POST", "/api/issues/preview-trigger?workspace_id="+testWorkspaceID, body)
testHandler.PreviewIssueTrigger(w, req)
if w.Code != http.StatusOK {
t.Fatalf("PreviewIssueTrigger: expected 200, got %d: %s", w.Code, w.Body.String())
}
var resp IssueTriggerPreviewResponse
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
t.Fatalf("decode preview: %v", err)
}
return resp
}
func createIssueForTest(t *testing.T, body map[string]any) IssueResponse {
t.Helper()
w := httptest.NewRecorder()
req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, body)
testHandler.CreateIssue(w, req)
if w.Code != http.StatusCreated {
t.Fatalf("CreateIssue: expected 201, got %d: %s", w.Code, w.Body.String())
}
var created IssueResponse
if err := json.NewDecoder(w.Body).Decode(&created); err != nil {
t.Fatalf("decode issue: %v", err)
}
t.Cleanup(func() {
r := withURLParam(newRequest("DELETE", "/api/issues/"+created.ID, nil), "id", created.ID)
testHandler.DeleteIssue(httptest.NewRecorder(), r)
})
return created
}
func taskCountFor(t *testing.T, issueID, agentID string) int {
t.Helper()
var n int
if err := testPool.QueryRow(context.Background(), `
SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2
`, issueID, agentID).Scan(&n); err != nil {
t.Fatalf("count tasks: %v", err)
}
return n
}
// TestPreviewIssueTrigger_CreateAgentVsBacklog covers the create entry point:
// an active status with an agent assignee previews one run; the same assignee
// parked in backlog previews none.
func TestPreviewIssueTrigger_CreateAgentVsBacklog(t *testing.T) {
agentID := seededReadyAgentID(t)
active := previewIssueTrigger(t, map[string]any{
"is_create": true,
"assignee_type": "agent",
"assignee_id": agentID,
"status": "todo",
})
if active.TotalCount != 1 || len(active.Triggers) != 1 {
t.Fatalf("active create: expected 1 trigger, got %+v", active)
}
if active.Triggers[0].AgentID != agentID || active.Triggers[0].Source != "assign" {
t.Fatalf("active create: wrong trigger %+v", active.Triggers[0])
}
backlog := previewIssueTrigger(t, map[string]any{
"is_create": true,
"assignee_type": "agent",
"assignee_id": agentID,
"status": "backlog",
})
if backlog.TotalCount != 0 {
t.Fatalf("backlog create: expected 0 triggers, got %+v", backlog)
}
}
// TestPreviewIssueTrigger_MemberNoTrigger verifies a member assignee never
// previews a run.
func TestPreviewIssueTrigger_MemberNoTrigger(t *testing.T) {
resp := previewIssueTrigger(t, map[string]any{
"is_create": true,
"assignee_type": "member",
"assignee_id": testUserID,
"status": "todo",
})
if resp.TotalCount != 0 {
t.Fatalf("member assignee: expected 0 triggers, got %+v", resp)
}
}
// TestPreviewIssueTrigger_BatchAggregates verifies the batch shape: two
// agent-assigned issues moving out of backlog preview two distinct runs.
func TestPreviewIssueTrigger_BatchAggregates(t *testing.T) {
agentID := seededReadyAgentID(t)
i1 := createIssueForTest(t, map[string]any{"title": "batch preview 1", "status": "backlog", "assignee_type": "agent", "assignee_id": agentID})
i2 := createIssueForTest(t, map[string]any{"title": "batch preview 2", "status": "backlog", "assignee_type": "agent", "assignee_id": agentID})
resp := previewIssueTrigger(t, map[string]any{
"issue_ids": []string{i1.ID, i2.ID},
"status": "todo",
})
if resp.TotalCount != 2 {
t.Fatalf("batch promote: expected total_count 2, got %+v", resp)
}
seen := map[string]bool{}
for _, tr := range resp.Triggers {
if tr.Source != "status" {
t.Fatalf("batch promote: expected source=status, got %q", tr.Source)
}
seen[tr.IssueID] = true
}
if !seen[i1.ID] || !seen[i2.ID] {
t.Fatalf("batch promote: missing an issue in %+v", resp.Triggers)
}
}
// TestPreviewIssueTrigger_MatchesWritePath is the core invariant: when preview
// says a run will start, the real write path enqueues it; when preview says it
// won't, the write path enqueues nothing.
func TestPreviewIssueTrigger_MatchesWritePath(t *testing.T) {
agentID := seededReadyAgentID(t)
// Case 1: preview says assign will start → write path enqueues.
issue := createIssueForTest(t, map[string]any{"title": "match write 1", "status": "todo"})
pv := previewIssueTrigger(t, map[string]any{
"issue_ids": []string{issue.ID},
"assignee_type": "agent",
"assignee_id": agentID,
})
if pv.TotalCount != 1 {
t.Fatalf("preview assign: expected 1, got %+v", pv)
}
w := httptest.NewRecorder()
req := withURLParam(newRequest("PUT", "/api/issues/"+issue.ID, map[string]any{"assignee_type": "agent", "assignee_id": agentID}), "id", issue.ID)
testHandler.UpdateIssue(w, req)
if w.Code != http.StatusOK {
t.Fatalf("UpdateIssue assign: %d %s", w.Code, w.Body.String())
}
if got := taskCountFor(t, issue.ID, agentID); got == 0 {
t.Fatalf("preview promised a run but write path enqueued none")
}
// Case 2: preview says backlog assign will NOT start → write enqueues none.
issue2 := createIssueForTest(t, map[string]any{"title": "match write 2", "status": "backlog"})
pv2 := previewIssueTrigger(t, map[string]any{
"issue_ids": []string{issue2.ID},
"assignee_type": "agent",
"assignee_id": agentID,
"status": "backlog",
})
if pv2.TotalCount != 0 {
t.Fatalf("preview backlog assign: expected 0, got %+v", pv2)
}
w2 := httptest.NewRecorder()
req2 := withURLParam(newRequest("PUT", "/api/issues/"+issue2.ID, map[string]any{"assignee_type": "agent", "assignee_id": agentID}), "id", issue2.ID)
testHandler.UpdateIssue(w2, req2)
if w2.Code != http.StatusOK {
t.Fatalf("UpdateIssue backlog assign: %d %s", w2.Code, w2.Body.String())
}
if got := taskCountFor(t, issue2.ID, agentID); got != 0 {
t.Fatalf("preview said no run for backlog assign but write path enqueued %d", got)
}
}
// TestUpdateIssueSuppressRunSkipsEnqueue verifies suppress_run applies the
// assignee change but starts no run, while the same write without it does.
func TestUpdateIssueSuppressRunSkipsEnqueue(t *testing.T) {
agentID := seededReadyAgentID(t)
// Suppressed assign: assignee set, no task.
suppressed := createIssueForTest(t, map[string]any{"title": "suppress on", "status": "todo"})
w := httptest.NewRecorder()
req := withURLParam(newRequest("PUT", "/api/issues/"+suppressed.ID, map[string]any{
"assignee_type": "agent", "assignee_id": agentID, "suppress_run": true,
}), "id", suppressed.ID)
testHandler.UpdateIssue(w, req)
if w.Code != http.StatusOK {
t.Fatalf("UpdateIssue suppressed: %d %s", w.Code, w.Body.String())
}
if got := taskCountFor(t, suppressed.ID, agentID); got != 0 {
t.Fatalf("suppress_run=true should not enqueue, got %d tasks", got)
}
// Control: same write without suppress_run enqueues.
control := createIssueForTest(t, map[string]any{"title": "suppress off", "status": "todo"})
w2 := httptest.NewRecorder()
req2 := withURLParam(newRequest("PUT", "/api/issues/"+control.ID, map[string]any{
"assignee_type": "agent", "assignee_id": agentID,
}), "id", control.ID)
testHandler.UpdateIssue(w2, req2)
if w2.Code != http.StatusOK {
t.Fatalf("UpdateIssue control: %d %s", w2.Code, w2.Body.String())
}
if got := taskCountFor(t, control.ID, agentID); got == 0 {
t.Fatalf("control (no suppress_run) should enqueue, got 0 tasks")
}
}
// TestUpdateIssueHandoffNotePersistsOnTask verifies an assign carrying a
// handoff_note writes that note onto the enqueued task (the daemon then renders
// it), while a suppressed assign with a note enqueues nothing at all.
func TestUpdateIssueHandoffNotePersistsOnTask(t *testing.T) {
agentID := seededReadyAgentID(t)
note := "Only touch the login flow."
issue := createIssueForTest(t, map[string]any{"title": "handoff persist", "status": "todo"})
w := httptest.NewRecorder()
req := withURLParam(newRequest("PUT", "/api/issues/"+issue.ID, map[string]any{
"assignee_type": "agent", "assignee_id": agentID, "handoff_note": note,
}), "id", issue.ID)
testHandler.UpdateIssue(w, req)
if w.Code != http.StatusOK {
t.Fatalf("UpdateIssue with handoff: %d %s", w.Code, w.Body.String())
}
var stored string
if err := testPool.QueryRow(context.Background(), `
SELECT COALESCE(handoff_note, '') FROM agent_task_queue
WHERE issue_id = $1 AND agent_id = $2 ORDER BY created_at DESC LIMIT 1
`, issue.ID, agentID).Scan(&stored); err != nil {
t.Fatalf("read task handoff_note: %v", err)
}
if stored != note {
t.Fatalf("expected task handoff_note %q, got %q", note, stored)
}
// Suppressed assign with a note: no task at all (no run to inject into).
suppressed := createIssueForTest(t, map[string]any{"title": "handoff suppressed", "status": "todo"})
w2 := httptest.NewRecorder()
req2 := withURLParam(newRequest("PUT", "/api/issues/"+suppressed.ID, map[string]any{
"assignee_type": "agent", "assignee_id": agentID, "handoff_note": note, "suppress_run": true,
}), "id", suppressed.ID)
testHandler.UpdateIssue(w2, req2)
if w2.Code != http.StatusOK {
t.Fatalf("UpdateIssue suppressed handoff: %d %s", w2.Code, w2.Body.String())
}
if got := taskCountFor(t, suppressed.ID, agentID); got != 0 {
t.Fatalf("suppressed handoff should enqueue no task, got %d", got)
}
}
// TestPreviewIssueTrigger_MalformedBody verifies the endpoint rejects a
// malformed body with 400 rather than a 500 or a silent empty result.
func TestPreviewIssueTrigger_MalformedBody(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/api/issues/preview-trigger?workspace_id="+testWorkspaceID, strings.NewReader("{not json"))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-User-ID", testUserID)
req.Header.Set("X-Workspace-ID", testWorkspaceID)
testHandler.PreviewIssueTrigger(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("malformed body: expected 400, got %d: %s", w.Code, w.Body.String())
}
}