mirror of
https://github.com/multica-ai/multica.git
synced 2026-07-24 02:39:42 +02:00
* 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>
418 lines
15 KiB
TypeScript
418 lines
15 KiB
TypeScript
import { describe, expect, it } from "vitest";
|
||
import {
|
||
AppConfigSchema,
|
||
DashboardAgentRunTimeListSchema,
|
||
DashboardUsageByAgentListSchema,
|
||
DashboardUsageDailyListSchema,
|
||
DuplicateIssueErrorBodySchema,
|
||
EMPTY_USER,
|
||
IssueTriggerPreviewSchema,
|
||
ListIssuesResponseSchema,
|
||
RuntimeHourlyActivityListSchema,
|
||
RuntimeUsageByAgentListSchema,
|
||
RuntimeUsageByHourListSchema,
|
||
RuntimeUsageListSchema,
|
||
SquadListSchema,
|
||
SquadSchema,
|
||
TimelineEntriesSchema,
|
||
UserSchema,
|
||
} from "./schemas";
|
||
import { parseWithFallback } from "./schema";
|
||
|
||
const baseIssue = {
|
||
id: "11111111-1111-1111-1111-111111111111",
|
||
workspace_id: "ws-1",
|
||
number: 1,
|
||
identifier: "MUL-1",
|
||
title: "Test",
|
||
description: null,
|
||
status: "todo",
|
||
priority: "medium",
|
||
assignee_type: null,
|
||
assignee_id: null,
|
||
creator_type: "member",
|
||
creator_id: "user-1",
|
||
parent_issue_id: null,
|
||
project_id: null,
|
||
position: 0,
|
||
stage: null,
|
||
start_date: null,
|
||
due_date: null,
|
||
metadata: {},
|
||
created_at: "2026-01-01T00:00:00Z",
|
||
updated_at: "2026-01-01T00:00:00Z",
|
||
};
|
||
|
||
describe("IssueSchema (via ListIssuesResponseSchema)", () => {
|
||
it("accepts a primitive metadata KV map", () => {
|
||
const payload = {
|
||
issues: [
|
||
{
|
||
...baseIssue,
|
||
metadata: { pipeline_status: "waiting", pr_number: 3, is_blocked: true },
|
||
},
|
||
],
|
||
total: 1,
|
||
};
|
||
const parsed = ListIssuesResponseSchema.parse(payload);
|
||
expect(parsed.issues[0]?.metadata).toEqual({
|
||
pipeline_status: "waiting",
|
||
pr_number: 3,
|
||
is_blocked: true,
|
||
});
|
||
});
|
||
|
||
it("defaults metadata to {} when the server omits it (older backend)", () => {
|
||
const { metadata: _omit, ...issueWithoutMetadata } = baseIssue;
|
||
const payload = { issues: [issueWithoutMetadata], total: 1 };
|
||
const parsed = ListIssuesResponseSchema.parse(payload);
|
||
expect(parsed.issues[0]?.metadata).toEqual({});
|
||
});
|
||
|
||
it("rejects metadata with non-primitive values (nested object)", () => {
|
||
const payload = {
|
||
issues: [{ ...baseIssue, metadata: { nested: { x: 1 } } }],
|
||
total: 1,
|
||
};
|
||
expect(ListIssuesResponseSchema.safeParse(payload).success).toBe(false);
|
||
});
|
||
|
||
it("accepts a numeric stage", () => {
|
||
const payload = { issues: [{ ...baseIssue, stage: 2 }], total: 1 };
|
||
const parsed = ListIssuesResponseSchema.parse(payload);
|
||
expect(parsed.issues[0]?.stage).toBe(2);
|
||
});
|
||
|
||
it("defaults stage to null when the server omits it (older backend)", () => {
|
||
const { stage: _omit, ...issueWithoutStage } = baseIssue;
|
||
const payload = { issues: [issueWithoutStage], total: 1 };
|
||
const parsed = ListIssuesResponseSchema.parse(payload);
|
||
expect(parsed.issues[0]?.stage).toBeNull();
|
||
});
|
||
});
|
||
|
||
// POST /api/issues/preview-trigger feeds this schema through parseWithFallback
|
||
// in client.previewIssueTrigger with fallback { triggers: [], total_count: 0 }
|
||
// (MUL-3375). The four entry points read it to decide "will this start a run",
|
||
// so malformed / missing / null drift must degrade to "nothing will start"
|
||
// rather than throw into the picker/modal.
|
||
const PREVIEW_FALLBACK = { triggers: [], total_count: 0 };
|
||
const PREVIEW_ENDPOINT = { endpoint: "POST /api/issues/preview-trigger" };
|
||
|
||
describe("IssueTriggerPreviewSchema", () => {
|
||
it("parses a well-formed response", () => {
|
||
const parsed = IssueTriggerPreviewSchema.parse({
|
||
triggers: [
|
||
{ issue_id: "i1", agent_id: "a1", source: "assign", handoff_supported: true },
|
||
{ issue_id: "i2", agent_id: "a2", source: "status", handoff_supported: false },
|
||
],
|
||
total_count: 2,
|
||
});
|
||
expect(parsed.total_count).toBe(2);
|
||
expect(parsed.triggers).toHaveLength(2);
|
||
expect(parsed.triggers[0]).toMatchObject({ issue_id: "i1", agent_id: "a1", source: "assign", handoff_supported: true });
|
||
});
|
||
|
||
it("defaults missing top-level fields (empty / older backend)", () => {
|
||
const parsed = IssueTriggerPreviewSchema.parse({});
|
||
expect(parsed.triggers).toEqual([]);
|
||
expect(parsed.total_count).toBe(0);
|
||
});
|
||
|
||
it("defaults missing optional item fields, keeping required issue_id", () => {
|
||
const parsed = IssueTriggerPreviewSchema.parse({ triggers: [{ issue_id: "i1" }], total_count: 1 });
|
||
expect(parsed.triggers[0]).toEqual({
|
||
issue_id: "i1",
|
||
agent_id: "",
|
||
source: "",
|
||
handoff_supported: false,
|
||
});
|
||
});
|
||
|
||
it("parseWithFallback returns the fallback for a malformed shape (triggers not an array)", () => {
|
||
const parsed = parseWithFallback(
|
||
{ triggers: "nope", total_count: 1 },
|
||
IssueTriggerPreviewSchema,
|
||
PREVIEW_FALLBACK,
|
||
PREVIEW_ENDPOINT,
|
||
);
|
||
expect(parsed).toEqual(PREVIEW_FALLBACK);
|
||
});
|
||
|
||
it("parseWithFallback returns the fallback when an item drops the required issue_id", () => {
|
||
const parsed = parseWithFallback(
|
||
{ triggers: [{ agent_id: "a1", source: "assign" }], total_count: 1 },
|
||
IssueTriggerPreviewSchema,
|
||
PREVIEW_FALLBACK,
|
||
PREVIEW_ENDPOINT,
|
||
);
|
||
expect(parsed).toEqual(PREVIEW_FALLBACK);
|
||
});
|
||
|
||
it("parseWithFallback returns the fallback for a wrong-typed total_count", () => {
|
||
const parsed = parseWithFallback(
|
||
{ triggers: [], total_count: "5" },
|
||
IssueTriggerPreviewSchema,
|
||
PREVIEW_FALLBACK,
|
||
PREVIEW_ENDPOINT,
|
||
);
|
||
expect(parsed).toEqual(PREVIEW_FALLBACK);
|
||
});
|
||
|
||
it("parseWithFallback returns the fallback for null / non-object bodies", () => {
|
||
expect(parseWithFallback(null, IssueTriggerPreviewSchema, PREVIEW_FALLBACK, PREVIEW_ENDPOINT)).toEqual(PREVIEW_FALLBACK);
|
||
expect(parseWithFallback("oops", IssueTriggerPreviewSchema, PREVIEW_FALLBACK, PREVIEW_ENDPOINT)).toEqual(PREVIEW_FALLBACK);
|
||
});
|
||
});
|
||
|
||
describe("TimelineEntriesSchema", () => {
|
||
it("preserves source_task_id for agent failure comments", () => {
|
||
const parsed = TimelineEntriesSchema.parse([
|
||
{
|
||
type: "comment",
|
||
id: "comment-1",
|
||
actor_type: "agent",
|
||
actor_id: "agent-1",
|
||
created_at: "2026-01-01T00:00:00Z",
|
||
content: "API Error: 500 Internal server error",
|
||
comment_type: "system",
|
||
source_task_id: "task-1",
|
||
},
|
||
]);
|
||
|
||
expect(parsed[0]?.source_task_id).toBe("task-1");
|
||
});
|
||
});
|
||
|
||
// The duplicate-issue branch in create-issue.tsx feeds ApiError.body
|
||
// (typed as `unknown`) through this schema. Any future server drift that
|
||
// loses the contract MUST fail the parse so the UI falls back to a normal
|
||
// error toast instead of rendering an empty / partial duplicate card.
|
||
describe("DuplicateIssueErrorBodySchema", () => {
|
||
const valid = {
|
||
code: "active_duplicate_issue",
|
||
error: "An active issue with this title already exists: MUL-12 – Login bug",
|
||
issue: {
|
||
id: "11111111-1111-1111-1111-111111111111",
|
||
identifier: "MUL-12",
|
||
title: "Login bug",
|
||
},
|
||
};
|
||
|
||
it("accepts a well-formed body", () => {
|
||
expect(DuplicateIssueErrorBodySchema.safeParse(valid).success).toBe(true);
|
||
});
|
||
|
||
it("accepts unknown extra fields via .loose()", () => {
|
||
const forwardCompat = {
|
||
...valid,
|
||
hint: "Try a different title",
|
||
issue: { ...valid.issue, workspace_id: "ws-1", status: "todo" },
|
||
};
|
||
expect(DuplicateIssueErrorBodySchema.safeParse(forwardCompat).success).toBe(true);
|
||
});
|
||
|
||
it("rejects a renamed code (so renames degrade to the generic toast)", () => {
|
||
const renamed = { ...valid, code: "duplicate_issue" };
|
||
expect(DuplicateIssueErrorBodySchema.safeParse(renamed).success).toBe(false);
|
||
});
|
||
|
||
it("rejects a missing issue object", () => {
|
||
const { issue: _omit, ...without } = valid;
|
||
expect(DuplicateIssueErrorBodySchema.safeParse(without).success).toBe(false);
|
||
});
|
||
|
||
it("rejects a non-string issue.id", () => {
|
||
const broken = { ...valid, issue: { ...valid.issue, id: 42 } };
|
||
expect(DuplicateIssueErrorBodySchema.safeParse(broken).success).toBe(false);
|
||
});
|
||
|
||
it("accepts a missing error field (it is optional)", () => {
|
||
const { error: _omit, ...without } = valid;
|
||
expect(DuplicateIssueErrorBodySchema.safeParse(without).success).toBe(true);
|
||
});
|
||
});
|
||
|
||
// `user.timezone` (Viewing tz) was added in the timezone-architecture RFC.
|
||
// A desktop build older than the server — or a server predating the
|
||
// `user.timezone` migration — will return a `/api/me` body with no
|
||
// `timezone` key. The schema must not fail closed on that: the field
|
||
// defaults to `null`, which the frontend resolves to the browser-detected
|
||
// tz at render time.
|
||
describe("UserSchema timezone drift", () => {
|
||
const base = {
|
||
id: "11111111-1111-1111-1111-111111111111",
|
||
name: "Ada",
|
||
email: "ada@example.com",
|
||
};
|
||
|
||
it("defaults timezone to null when the field is absent", () => {
|
||
const parsed = UserSchema.parse(base);
|
||
expect(parsed.timezone).toBe(null);
|
||
});
|
||
|
||
it("preserves an explicit IANA timezone", () => {
|
||
const parsed = UserSchema.parse({ ...base, timezone: "Asia/Tokyo" });
|
||
expect(parsed.timezone).toBe("Asia/Tokyo");
|
||
});
|
||
|
||
it("accepts an explicit null timezone", () => {
|
||
const parsed = UserSchema.parse({ ...base, timezone: null });
|
||
expect(parsed.timezone).toBe(null);
|
||
});
|
||
|
||
// Wrong-type drift: a future server bug sending `timezone` as a number
|
||
// must not throw into the UI. parseWithFallback degrades the whole user
|
||
// object to the explicit fallback (EMPTY_USER) so /api/me callers keep a
|
||
// valid shape instead of white-screening.
|
||
it("falls back to EMPTY_USER when timezone is the wrong type", () => {
|
||
const parsed = parseWithFallback(
|
||
{ ...base, timezone: 42 },
|
||
UserSchema,
|
||
EMPTY_USER,
|
||
{ endpoint: "GET /api/me" },
|
||
);
|
||
expect(parsed).toBe(EMPTY_USER);
|
||
});
|
||
});
|
||
|
||
describe("SquadListSchema member preview drift", () => {
|
||
const baseSquad = {
|
||
id: "squad-1",
|
||
workspace_id: "ws-1",
|
||
name: "Frontend Squad",
|
||
description: "",
|
||
instructions: "",
|
||
avatar_url: null,
|
||
leader_id: "agent-1",
|
||
creator_id: "user-1",
|
||
created_at: "2026-05-01T00:00:00Z",
|
||
updated_at: "2026-05-01T00:00:00Z",
|
||
archived_at: null,
|
||
archived_by: null,
|
||
};
|
||
|
||
it("defaults preview fields when an older backend omits them", () => {
|
||
const parsed = SquadListSchema.parse([baseSquad]);
|
||
expect(parsed[0]?.member_count).toBe(0);
|
||
expect(parsed[0]?.member_preview).toEqual([]);
|
||
});
|
||
|
||
it("defaults preview fields on a single squad response", () => {
|
||
const parsed = SquadSchema.parse(baseSquad);
|
||
expect(parsed.member_count).toBe(0);
|
||
expect(parsed.member_preview).toEqual([]);
|
||
});
|
||
|
||
it("preserves lightweight member preview rows", () => {
|
||
const parsed = SquadListSchema.parse([
|
||
{
|
||
...baseSquad,
|
||
member_count: 2,
|
||
member_preview: [
|
||
{ member_type: "agent", member_id: "agent-1", role: "leader" },
|
||
{ member_type: "member", member_id: "user-2", role: "member" },
|
||
],
|
||
},
|
||
]);
|
||
expect(parsed[0]?.member_count).toBe(2);
|
||
expect(parsed[0]?.member_preview).toHaveLength(2);
|
||
expect(parsed[0]?.member_preview?.[0]?.role).toBe("leader");
|
||
});
|
||
});
|
||
|
||
// The workspace dashboard and runtime-detail pages were re-pointed at the
|
||
// unified `task_usage_hourly` rollup. Every numeric field drives chart /
|
||
// KPI math, and string keys (date / agent_id / model) bucket the series.
|
||
// The contract these schemas must hold: a row missing a field degrades
|
||
// that field to a sane default rather than dropping the WHOLE array to
|
||
// the `[]` fallback — one drifted row must not blank the entire chart.
|
||
describe("dashboard + runtime usage schema drift", () => {
|
||
it("coerces a missing numeric field to 0 instead of dropping the array", () => {
|
||
const parsed = DashboardUsageDailyListSchema.parse([
|
||
{ date: "2026-05-19", model: "claude-opus-4-7", input_tokens: 100 },
|
||
]);
|
||
expect(parsed).toHaveLength(1);
|
||
expect(parsed[0]?.output_tokens).toBe(0);
|
||
expect(parsed[0]?.cache_read_tokens).toBe(0);
|
||
expect(parsed[0]?.cache_write_tokens).toBe(0);
|
||
});
|
||
|
||
it("coerces a missing date key to \"\" so the rest of the series survives", () => {
|
||
const parsed = DashboardUsageDailyListSchema.parse([
|
||
{ model: "claude-opus-4-7", input_tokens: 5 },
|
||
]);
|
||
expect(parsed).toHaveLength(1);
|
||
expect(parsed[0]?.date).toBe("");
|
||
});
|
||
|
||
it("coerces a missing agent_id key to \"\" for the agent-runtime panel", () => {
|
||
const parsed = DashboardAgentRunTimeListSchema.parse([
|
||
{ total_seconds: 42, task_count: 3, failed_count: 0 },
|
||
]);
|
||
expect(parsed).toHaveLength(1);
|
||
expect(parsed[0]?.agent_id).toBe("");
|
||
});
|
||
|
||
it("coerces a missing agent_id key to \"\" for the usage-by-agent panel", () => {
|
||
const parsed = DashboardUsageByAgentListSchema.parse([
|
||
{ model: "claude-opus-4-7", input_tokens: 7 },
|
||
]);
|
||
expect(parsed[0]?.agent_id).toBe("");
|
||
});
|
||
|
||
it("coerces missing fields on every runtime usage schema", () => {
|
||
expect(RuntimeUsageListSchema.parse([{ date: "2026-05-19" }])[0]?.input_tokens).toBe(0);
|
||
expect(RuntimeHourlyActivityListSchema.parse([{ hour: 9 }])[0]?.count).toBe(0);
|
||
expect(RuntimeUsageByAgentListSchema.parse([{ model: "x" }])[0]?.agent_id).toBe("");
|
||
expect(RuntimeUsageByHourListSchema.parse([{ hour: 9 }])[0]?.model).toBe("");
|
||
});
|
||
|
||
it("defaults a missing provider to \"\" so an older server's rows still price by bare model", () => {
|
||
// provider was added for cross-provider model disambiguation; a server
|
||
// predating it omits the field. The schema must fill "" (→ bare-model
|
||
// pricing lookup) rather than drop the row.
|
||
expect(
|
||
DashboardUsageDailyListSchema.parse([{ date: "2026-05-19", model: "claude-opus-4-7" }])[0]
|
||
?.provider,
|
||
).toBe("");
|
||
expect(
|
||
DashboardUsageByAgentListSchema.parse([{ model: "claude-opus-4-7" }])[0]?.provider,
|
||
).toBe("");
|
||
expect(RuntimeUsageByAgentListSchema.parse([{ model: "x" }])[0]?.provider).toBe("");
|
||
});
|
||
|
||
it("rejects a non-array body so parseWithFallback can return its fallback", () => {
|
||
expect(DashboardUsageDailyListSchema.safeParse(null).success).toBe(false);
|
||
expect(RuntimeUsageListSchema.safeParse({ rows: [] }).success).toBe(false);
|
||
});
|
||
|
||
it("keeps unknown server-side fields via .loose()", () => {
|
||
const parsed = RuntimeUsageListSchema.parse([
|
||
{ date: "2026-05-19", region: "us-east" },
|
||
]);
|
||
expect((parsed[0] as Record<string, unknown>).region).toBe("us-east");
|
||
});
|
||
});
|
||
|
||
describe("AppConfigSchema cdn_signed drift", () => {
|
||
it("defaults cdn_signed to false when the server omits it (pre-MUL-3254 servers)", () => {
|
||
const parsed = AppConfigSchema.parse({ cdn_domain: "cdn.example.com" });
|
||
expect(parsed.cdn_signed).toBe(false);
|
||
});
|
||
|
||
it("coerces a malformed cdn_signed to false instead of failing the whole config", () => {
|
||
const parsed = AppConfigSchema.parse({
|
||
cdn_domain: "cdn.example.com",
|
||
cdn_signed: "yes",
|
||
});
|
||
expect(parsed.cdn_signed).toBe(false);
|
||
expect(parsed.cdn_domain).toBe("cdn.example.com");
|
||
});
|
||
|
||
it("keeps cdn_signed=true from a signing-enabled server", () => {
|
||
const parsed = AppConfigSchema.parse({ cdn_signed: true });
|
||
expect(parsed.cdn_signed).toBe(true);
|
||
});
|
||
});
|