@vellumai/assistant 0.11.3-dev.202608172212.668422c → 0.11.3-dev.202608172253.65bf2a2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/openapi.yaml CHANGED
@@ -6596,6 +6596,18 @@ paths:
6596
6596
  "system:all" for conversations in no group, "system:pinned" for the Pinned section, or a custom group id. A
6597
6597
  group-scoped request is recency-ordered like every list read (COALESCE(last_message_at, updated_at)
6598
6598
  descending) and never has pinned rows appended to it. Omit to span every group.
6599
+ - name: needsAttention
6600
+ in: query
6601
+ required: false
6602
+ schema:
6603
+ type: string
6604
+ enum:
6605
+ - "true"
6606
+ description:
6607
+ 'Pass "true" to return only conversations whose latest assistant message the user has not seen: the same
6608
+ predicate behind the unread count and the section index, so a client that keeps no complete conversation
6609
+ list can ask for exactly the rows its attention surfaces need. Composes with every other filter. Any value
6610
+ other than "true" is rejected. Omit to span every conversation.'
6599
6611
  responses:
6600
6612
  "200":
6601
6613
  description: Successful response
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.11.3-dev.202608172212.668422c",
3
+ "version": "0.11.3-dev.202608172253.65bf2a2",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -1,6 +1,14 @@
1
1
  import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
2
2
 
3
- import { readFileSync } from "fs";
3
+ import {
4
+ mkdtempSync,
5
+ readdirSync,
6
+ readFileSync,
7
+ rmSync,
8
+ symlinkSync,
9
+ writeFileSync,
10
+ } from "fs";
11
+ import { tmpdir } from "os";
4
12
  import { dirname, join } from "path";
5
13
 
6
14
  import { __resetRegistryForTesting, getTool } from "../tools/registry.js";
@@ -97,8 +105,23 @@ import { run } from "../config/bundled-skills/image-studio/tools/media-generate-
97
105
  // Clean up after this file to prevent contamination of later test files.
98
106
  afterAll(() => {
99
107
  __resetRegistryForTesting();
108
+ for (const dir of tempWorkingDirs) {
109
+ rmSync(dir, { recursive: true, force: true });
110
+ }
100
111
  });
101
112
 
113
+ const tempWorkingDirs: string[] = [];
114
+
115
+ /** Build a ToolContext with a fresh temp working directory. */
116
+ function makeContext(): ToolContext {
117
+ const workingDir = mkdtempSync(join(tmpdir(), "media-gen-test-"));
118
+ tempWorkingDirs.push(workingDir);
119
+ return {
120
+ conversationId: "conv-123",
121
+ workingDir,
122
+ } as unknown as ToolContext;
123
+ }
124
+
102
125
  const CONFIG_DIR = join(
103
126
  dirname(import.meta.dirname!),
104
127
  "config",
@@ -128,12 +151,10 @@ beforeEach(() => {
128
151
  platformBaseUrl: "",
129
152
  assistantApiKey: "",
130
153
  };
154
+ fakeContext = makeContext();
131
155
  });
132
156
 
133
- const fakeContext = {
134
- conversationId: "conv-123",
135
- workingDir: "/tmp",
136
- } as unknown as ToolContext;
157
+ let fakeContext: ToolContext;
137
158
 
138
159
  describe("image-studio skill script wrapper", () => {
139
160
  test("exports a run function without registering media_generate_image in the tool registry", async () => {
@@ -431,28 +452,117 @@ describe("image-studio skill script wrapper", () => {
431
452
  });
432
453
 
433
454
  test("reads source images from file paths on disk", async () => {
434
- // Write a temp image file inside the workspace (fakeContext.workingDir = /tmp)
435
- const tmpPath = join("/tmp", "test-source-image.png");
455
+ // Write a temp image file inside the workspace
456
+ const tmpPath = join(fakeContext.workingDir, "test-source-image.png");
436
457
  const pngBytes = Buffer.from(
437
458
  "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==",
438
459
  "base64",
439
460
  );
440
461
  await Bun.write(tmpPath, pngBytes);
441
462
 
442
- try {
443
- const result = await run(
444
- { prompt: "edit this", mode: "edit", source_paths: [tmpPath] },
445
- fakeContext,
446
- );
447
-
448
- expect(result.isError).toBe(false);
449
- expect(result.content).toContain("Generated 1 image");
450
- } finally {
451
- const { unlink } = await import("fs/promises");
452
- if (await Bun.file(tmpPath).exists()) {
453
- await unlink(tmpPath);
454
- }
455
- }
463
+ const result = await run(
464
+ { prompt: "edit this", mode: "edit", source_paths: [tmpPath] },
465
+ fakeContext,
466
+ );
467
+
468
+ expect(result.isError).toBe(false);
469
+ expect(result.content).toContain("Generated 1 image");
470
+ });
471
+
472
+ test("saves the image into media/generated and returns the embed instruction", async () => {
473
+ const result = await run({ prompt: "a sunset" }, fakeContext);
474
+
475
+ expect(result.isError).toBe(false);
476
+ expect(result.content).toContain("Saved to media/generated/a-sunset.png");
477
+ expect(result.content).toContain(
478
+ "![description](vellum://workspace/media/generated/a-sunset.png)",
479
+ );
480
+ const saved = Bun.file(
481
+ join(fakeContext.workingDir, "media/generated/a-sunset.png"),
482
+ );
483
+ expect(await saved.exists()).toBe(true);
484
+ const bytes = Buffer.from(await saved.arrayBuffer());
485
+ expect(bytes.equals(Buffer.from("generated-data", "base64"))).toBe(true);
486
+ });
487
+
488
+ test("uses the image title for the filename when present", async () => {
489
+ mockGenerateResult = {
490
+ images: [
491
+ {
492
+ mimeType: "image/png",
493
+ dataBase64: "img1",
494
+ title: "Twilight Gremlin!",
495
+ } as never,
496
+ ],
497
+ text: "",
498
+ resolvedModel: "gemini-3.1-flash-image-preview",
499
+ };
500
+
501
+ const result = await run({ prompt: "a pond creature" }, fakeContext);
502
+
503
+ expect(result.isError).toBe(false);
504
+ expect(result.content).toContain(
505
+ "Saved to media/generated/twilight-gremlin.png",
506
+ );
507
+ });
508
+
509
+ test("gives each variant a distinct filename", async () => {
510
+ mockGenerateResult = {
511
+ images: [
512
+ { mimeType: "image/png", dataBase64: "img1" },
513
+ { mimeType: "image/png", dataBase64: "img2" },
514
+ ],
515
+ text: undefined as unknown as string,
516
+ resolvedModel: "gemini-3.1-flash-image-preview",
517
+ };
518
+
519
+ const result = await run({ prompt: "a robot", variants: 2 }, fakeContext);
520
+
521
+ expect(result.isError).toBe(false);
522
+ expect(result.content).toContain("- media/generated/a-robot.png");
523
+ expect(result.content).toContain("- media/generated/a-robot-2.png");
524
+ expect(
525
+ await Bun.file(
526
+ join(fakeContext.workingDir, "media/generated/a-robot-2.png"),
527
+ ).exists(),
528
+ ).toBe(true);
529
+ });
530
+
531
+ test("suffixes the filename when a previous generation already used it", async () => {
532
+ const first = await run({ prompt: "a fox" }, fakeContext);
533
+ expect(first.content).toContain("Saved to media/generated/a-fox.png");
534
+
535
+ const second = await run({ prompt: "a fox" }, fakeContext);
536
+ expect(second.content).toContain("Saved to media/generated/a-fox-2.png");
537
+ });
538
+
539
+ test("refuses to write through a symlink that escapes the workspace", async () => {
540
+ const outside = mkdtempSync(join(tmpdir(), "media-gen-outside-"));
541
+ tempWorkingDirs.push(outside);
542
+ symlinkSync(outside, join(fakeContext.workingDir, "media"));
543
+
544
+ const result = await run({ prompt: "a cat" }, fakeContext);
545
+
546
+ expect(result.isError).toBe(false);
547
+ expect(result.content).toContain("Could not save to the workspace");
548
+ expect(result.content).not.toContain("vellum://workspace/");
549
+ expect(readdirSync(outside)).toEqual([]);
550
+ });
551
+
552
+ test("falls back to inline-only when the workspace write fails", async () => {
553
+ // Occupy the media path with a regular file so the directory creation
554
+ // under it fails.
555
+ writeFileSync(join(fakeContext.workingDir, "media"), "not a directory");
556
+
557
+ const result = await run({ prompt: "a cat" }, fakeContext);
558
+
559
+ expect(result.isError).toBe(false);
560
+ expect(result.content).toContain("Could not save to the workspace");
561
+ expect(result.content).toContain(
562
+ "will be attached to your reply automatically",
563
+ );
564
+ expect(result.content).not.toContain("vellum://workspace/");
565
+ expect(result.contentBlocks).toHaveLength(1);
456
566
  });
457
567
 
458
568
  test("returns error when all source_paths are invalid", async () => {
@@ -69,10 +69,11 @@ Edits on large photos are slow (1 to 2 minutes). If the tool reports a timeout (
69
69
 
70
70
  ## Output handling
71
71
 
72
- Images return as inline content blocks in the tool result; they are not written to disk automatically.
72
+ Each generated image is saved into the workspace under `media/generated/` and the tool result lists the saved paths. The images also come back as inline content blocks so you can judge the result before presenting it.
73
73
 
74
- - If the user just wants to see the image, the inline result is enough.
75
- - If the user wants a file or you need to iterate on the result, save it to disk and deliver it through the conversation's attachment mechanism.
74
+ - Present an image to the user by embedding its saved path in your reply: `![short description](vellum://workspace/media/generated/<file>.png)`. The app renders it inline where your text refers to it, and chat channels (Slack, Telegram, WhatsApp) deliver it as a native image upload.
75
+ - If you do not embed it, the image is still auto-attached to your reply as a file, so it is never lost. Prefer embedding: an attachment chip at the end of the message is a worse presentation than the image inline.
76
+ - To iterate on a result, pass its saved path via `source_paths` with `mode: "edit"`.
76
77
 
77
78
  ## Error handling
78
79
 
@@ -88,4 +89,4 @@ Do NOT rephrase the prompt and retry on the same model, even if the error sugges
88
89
 
89
90
  ## Complete when
90
91
 
91
- The tool has returned at least one image and the user can see it: either the inline result in chat or an attached saved file. An error report counts as complete only after the retry path in Error handling has been exhausted.
92
+ The tool has returned at least one image and your reply presents it to the user, preferably as an inline `![description](vellum://workspace/...)` embed of the saved path. An error report counts as complete only after the retry path in Error handling has been exhausted.
@@ -3,7 +3,7 @@
3
3
  "tools": [
4
4
  {
5
5
  "name": "media_generate_image",
6
- "description": "Generate or edit images using AI. Supports text-to-image generation and image editing with source images.",
6
+ "description": "Generate or edit images using AI. Supports text-to-image generation and image editing with source images. Saves results into the workspace and returns their file paths; present a result to the user by embedding its path in your reply as ![description](vellum://workspace/<path>).",
7
7
  "category": "media",
8
8
  "risk": "low",
9
9
  "input_schema": {
@@ -1,3 +1,6 @@
1
+ import { mkdirSync, writeFileSync } from "fs";
2
+ import { dirname, join } from "path";
3
+
1
4
  import {
2
5
  resolveImageGenCredentials,
3
6
  resolveImageGenRouting,
@@ -19,6 +22,87 @@ import type {
19
22
  } from "../../../../tools/types.js";
20
23
  import { getConfig } from "../../../loader.js";
21
24
 
25
+ /** Workspace-relative directory where generated images are saved. */
26
+ const GENERATED_MEDIA_DIR = "media/generated";
27
+
28
+ /**
29
+ * Derive a filesystem-safe base name for a generated image from its title
30
+ * (when the provider returns one) or the generation prompt.
31
+ */
32
+ function imageFileSlug(title: string | undefined, prompt: string): string {
33
+ const base = (title?.trim() || prompt)
34
+ .toLowerCase()
35
+ .replace(/[^a-z0-9]+/g, "-")
36
+ .replace(/^-+/, "")
37
+ .slice(0, 48)
38
+ .replace(/-+$/, "");
39
+ return base || "image";
40
+ }
41
+
42
+ /** Upper bound on filename-collision retries per image. */
43
+ const MAX_FILENAME_ATTEMPTS = 1000;
44
+
45
+ /**
46
+ * Save generated images under `media/generated/` in the workspace so the
47
+ * model can reference them by path (inline embeds, edit-mode iteration).
48
+ * Each target path is validated through `sandboxPolicy` so a symlinked
49
+ * directory cannot redirect the write outside the workspace, and files are
50
+ * created exclusively (`wx`) so concurrent generations cannot claim the
51
+ * same filename. Returns workspace-relative paths for the images written
52
+ * before any failure; a failure stops the loop and is reported, not
53
+ * thrown, so the inline content blocks still reach the model.
54
+ */
55
+ function saveGeneratedImages(
56
+ images: Array<{ mimeType: string; dataBase64: string; title?: string }>,
57
+ prompt: string,
58
+ workingDir: string,
59
+ ): { savedPaths: string[]; saveError?: string } {
60
+ const savedPaths: string[] = [];
61
+ try {
62
+ for (const img of images) {
63
+ const ext = img.mimeType.split("/")[1] ?? "png";
64
+ const slug = imageFileSlug(img.title, prompt);
65
+ let written = false;
66
+ for (let attempt = 1; attempt <= MAX_FILENAME_ATTEMPTS; attempt++) {
67
+ const relPath =
68
+ attempt === 1
69
+ ? `${GENERATED_MEDIA_DIR}/${slug}.${ext}`
70
+ : `${GENERATED_MEDIA_DIR}/${slug}-${attempt}.${ext}`;
71
+ const pathCheck = sandboxPolicy(join(workingDir, relPath), workingDir, {
72
+ mustExist: false,
73
+ });
74
+ if (!pathCheck.ok) {
75
+ throw new Error(pathCheck.error);
76
+ }
77
+ mkdirSync(dirname(pathCheck.resolved), { recursive: true });
78
+ try {
79
+ writeFileSync(
80
+ pathCheck.resolved,
81
+ Buffer.from(img.dataBase64, "base64"),
82
+ { flag: "wx" },
83
+ );
84
+ } catch (error) {
85
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") {
86
+ continue;
87
+ }
88
+ throw error;
89
+ }
90
+ savedPaths.push(relPath);
91
+ written = true;
92
+ break;
93
+ }
94
+ if (!written) {
95
+ throw new Error(
96
+ `Could not find a free filename for "${slug}.${ext}" after ${MAX_FILENAME_ATTEMPTS} attempts.`,
97
+ );
98
+ }
99
+ }
100
+ } catch (error) {
101
+ return { savedPaths, saveError: (error as Error).message };
102
+ }
103
+ return { savedPaths };
104
+ }
105
+
22
106
  export async function run(
23
107
  input: Record<string, unknown>,
24
108
  context: ToolContext,
@@ -127,7 +211,24 @@ export async function run(
127
211
  });
128
212
 
129
213
  const imageCount = result.images.length;
214
+ const { savedPaths, saveError } = saveGeneratedImages(
215
+ result.images,
216
+ prompt,
217
+ context.workingDir,
218
+ );
219
+
130
220
  let content = `Generated ${imageCount} image${imageCount !== 1 ? "s" : ""} using ${result.resolvedModel}.`;
221
+ if (savedPaths.length === 1) {
222
+ content += ` Saved to ${savedPaths[0]}.`;
223
+ } else if (savedPaths.length > 1) {
224
+ content += ` Saved to:\n${savedPaths.map((p) => `- ${p}`).join("\n")}`;
225
+ }
226
+ if (savedPaths.length > 0) {
227
+ content += `\n\nShow the user an image by embedding it in your reply: ![description](vellum://workspace/${savedPaths[0]}). To iterate on a result, pass its saved path via source_paths with mode "edit".`;
228
+ }
229
+ if (saveError) {
230
+ content += `\n\nCould not save to the workspace (${saveError}); the image${imageCount !== 1 ? "s" : ""} will be attached to your reply automatically instead.`;
231
+ }
131
232
  if (result.text) {
132
233
  content += `\n\n${result.text}`;
133
234
  }
@@ -1,4 +1,14 @@
1
- import { and, count, desc, eq, isNull, lt, sql } from "drizzle-orm";
1
+ import {
2
+ and,
3
+ count,
4
+ desc,
5
+ eq,
6
+ getTableColumns,
7
+ isNull,
8
+ lt,
9
+ sql,
10
+ } from "drizzle-orm";
11
+ import type { SQLiteSelect } from "drizzle-orm/sqlite-core";
2
12
 
3
13
  import {
4
14
  parseExternalContentEnvelope,
@@ -263,6 +273,15 @@ export interface ConversationListFilter {
263
273
  * section, and a UUID one custom group. Omit to span every group.
264
274
  */
265
275
  groupId?: string;
276
+ /**
277
+ * Restrict to conversations whose latest assistant message the user has
278
+ * not seen: the same "unseen" predicate the unread count and the section
279
+ * index apply ({@link unseenAttentionStateConditions}), so every reader
280
+ * of "needs attention" agrees. Only `true` narrows; omit to span every
281
+ * conversation. A client that keeps no complete list can ask for exactly
282
+ * the rows its attention surfaces need instead of scanning for them.
283
+ */
284
+ needsAttention?: true;
266
285
  }
267
286
 
268
287
  export interface ConversationListQuery extends ConversationListFilter {
@@ -327,21 +346,55 @@ function originChannelClause(originChannel: string) {
327
346
  return eq(conversations.originChannel, originChannel);
328
347
  }
329
348
 
349
+ /**
350
+ * The join between a conversation and its attention projection, one row per
351
+ * conversation in `conversation_assistant_attention_state`. Every reader of
352
+ * "unseen" joins on this: the list and count filters, the unread count, and
353
+ * the section index.
354
+ */
355
+ const attentionJoin = eq(
356
+ conversationAssistantAttentionState.conversationId,
357
+ conversations.id,
358
+ );
359
+
330
360
  function conversationListWhere(filter: ConversationListFilter) {
331
361
  const {
332
362
  conversationType = "standard",
333
363
  archiveStatus = "active",
334
364
  originChannel,
335
365
  groupId,
366
+ needsAttention,
336
367
  } = filter;
337
368
  return and(
338
369
  conversationTypeClause(conversationType),
339
370
  archiveStatusClause(archiveStatus) ?? undefined,
340
371
  originChannel ? originChannelClause(originChannel) : undefined,
341
372
  groupId ? groupIdClause(groupId) : undefined,
373
+ ...(needsAttention ? unseenAttentionStateConditions() : []),
342
374
  );
343
375
  }
344
376
 
377
+ /**
378
+ * The joins {@link conversationListWhere}'s predicates need, applied to a
379
+ * list or count query over `conversations`. The attention predicate lives on
380
+ * `conversation_assistant_attention_state`, so `needsAttention` joins it.
381
+ * Inner, not left: a conversation with no
382
+ * attention row has no unseen message by definition. Joined only when the
383
+ * filter asks, so a query without the filter runs without the join and
384
+ * lists every conversation the predicates admit. One place for both
385
+ * {@link listConversations} and {@link countConversations}, so a page and
386
+ * its total always describe the same set.
387
+ */
388
+ function withListFilterJoins<T extends SQLiteSelect>(
389
+ query: T,
390
+ filter: ConversationListFilter,
391
+ ) {
392
+ if (!filter.needsAttention) {
393
+ return query;
394
+ }
395
+ return query.innerJoin(conversationAssistantAttentionState, attentionJoin);
396
+ }
397
+
345
398
  export function listConversations(
346
399
  query: ConversationListQuery = {},
347
400
  ): ConversationRow[] {
@@ -362,9 +415,13 @@ export function listConversations(
362
415
  // distinguish a total order from a lucky one. The guarantee becomes
363
416
  // observable, and gets its test, with the keyset pagination work.
364
417
  const tiebreak = desc(conversations.id);
365
- return db
366
- .select()
367
- .from(conversations)
418
+ // Selecting the conversation columns explicitly keeps the row shape
419
+ // `parseConversation` maps identical whether or not the attention join is
420
+ // present.
421
+ return withListFilterJoins(
422
+ db.select(getTableColumns(conversations)).from(conversations).$dynamic(),
423
+ filter,
424
+ )
368
425
  .where(conversationListWhere(filter))
369
426
  .orderBy(recency, tiebreak)
370
427
  .limit(limit ?? 100)
@@ -542,9 +599,10 @@ export function countConversations(
542
599
  ): number {
543
600
  ensureGroupMigration();
544
601
  const db = getDb();
545
- const [{ total }] = db
546
- .select({ total: count() })
547
- .from(conversations)
602
+ const [{ total }] = withListFilterJoins(
603
+ db.select({ total: count() }).from(conversations).$dynamic(),
604
+ filter,
605
+ )
548
606
  .where(conversationListWhere(filter))
549
607
  .all();
550
608
  return total;
@@ -582,10 +640,7 @@ export function countUnreadConversations(): number {
582
640
  const [{ total }] = db
583
641
  .select({ total: count() })
584
642
  .from(conversations)
585
- .innerJoin(
586
- conversationAssistantAttentionState,
587
- eq(conversationAssistantAttentionState.conversationId, conversations.id),
588
- )
643
+ .innerJoin(conversationAssistantAttentionState, attentionJoin)
589
644
  .where(
590
645
  and(
591
646
  conversationTypeClause("standard"),
@@ -647,11 +702,6 @@ export function countConversationSections(): ConversationSectionCounts {
647
702
  ...unseenAttentionStateConditions(),
648
703
  )} THEN 1 ELSE 0 END)`;
649
704
 
650
- const attentionJoin = eq(
651
- conversationAssistantAttentionState.conversationId,
652
- conversations.id,
653
- );
654
-
655
705
  const groups = db
656
706
  .select({
657
707
  groupId: sql<string>`group_id`,
@@ -514,6 +514,139 @@ describe("GET /v1/conversations with groupId", () => {
514
514
  });
515
515
  });
516
516
 
517
+ describe("GET /v1/conversations with needsAttention", () => {
518
+ function seedUnseen(conversationId: string): void {
519
+ projectAssistantMessage({
520
+ conversationId,
521
+ messageId: `msg-${conversationId}`,
522
+ messageAt: Date.now(),
523
+ });
524
+ }
525
+
526
+ function markSeen(conversationId: string): void {
527
+ recordConversationSeenSignal({
528
+ conversationId,
529
+ sourceChannel: "vellum",
530
+ signalType: "macos_conversation_opened",
531
+ confidence: "explicit",
532
+ source: "test",
533
+ });
534
+ }
535
+
536
+ beforeEach(() => {
537
+ getDb().delete(conversationAttentionEvents).run();
538
+ getDb().delete(conversationAssistantAttentionState).run();
539
+ clearConversations();
540
+ });
541
+
542
+ test("returns only conversations with an unseen latest assistant message", async () => {
543
+ const unseen = createConversation("needs-attention");
544
+ seedUnseen(unseen.id);
545
+ const seen = createConversation("already-seen");
546
+ seedUnseen(seen.id);
547
+ markSeen(seen.id);
548
+ // No attention projection at all: not unseen, so not returned. The
549
+ // filter's inner join is what excludes it; a left join would leak it.
550
+ createConversation("never-projected");
551
+
552
+ const result = await invoke({ needsAttention: "true" });
553
+
554
+ expect(result.conversations.map((c) => c.title)).toEqual([
555
+ "needs-attention",
556
+ ]);
557
+ });
558
+
559
+ test("omitting the filter leaves every list unchanged, join and all", async () => {
560
+ /* The sensitivity check for the conditional join: with the filter off,
561
+ rows with no attention row must still be listed. If the join were
562
+ applied unconditionally, "never-projected" would vanish from the
563
+ plain list, which is every list the app has today. */
564
+ const unseen = createConversation("has-attention-row");
565
+ seedUnseen(unseen.id);
566
+ createConversation("never-projected");
567
+
568
+ const result = await invoke();
569
+
570
+ expect(result.conversations.map((c) => c.title).sort()).toEqual([
571
+ "has-attention-row",
572
+ "never-projected",
573
+ ]);
574
+ });
575
+
576
+ test("hasMore and the total describe the filtered set, not the whole table", async () => {
577
+ /* countConversations reads through the same where AND the same join;
578
+ a page and its total have to agree or the client's hasMore lies. */
579
+ for (let i = 0; i < 3; i++) {
580
+ const c = createConversation(`unseen-${i}`);
581
+ seedUnseen(c.id);
582
+ }
583
+ for (let i = 0; i < 5; i++) {
584
+ createConversation(`quiet-${i}`);
585
+ }
586
+
587
+ const page = await invoke({ needsAttention: "true", limit: "2" });
588
+
589
+ expect(page.conversations).toHaveLength(2);
590
+ expect(page.hasMore).toBe(true);
591
+ const rest = await invoke({
592
+ needsAttention: "true",
593
+ limit: "2",
594
+ offset: "2",
595
+ });
596
+ expect(rest.conversations).toHaveLength(1);
597
+ expect(rest.hasMore).toBe(false);
598
+ });
599
+
600
+ test("an attention-scoped first page has no pinned rows appended to it", async () => {
601
+ /* Same rule as the group-scoped page: the pinned injection exists for
602
+ a client reading Pinned out of the unfiltered list, and a caller
603
+ that asked for the unseen subset is not that client. A seen pinned
604
+ row appended here would be a row outside the filter, on a page whose
605
+ hasMore was computed from the filtered count. */
606
+ const unseen = createConversation("unseen-only");
607
+ seedUnseen(unseen.id);
608
+ const pinnedSeen = createConversation("pinned-and-seen");
609
+ rawRun(
610
+ "test:pinConversation",
611
+ "UPDATE conversations SET is_pinned = 1, group_id = 'system:pinned' WHERE id = ?",
612
+ pinnedSeen.id,
613
+ );
614
+
615
+ const result = await invoke({ needsAttention: "true" });
616
+
617
+ expect(result.conversations.map((c) => c.title)).toEqual(["unseen-only"]);
618
+ });
619
+
620
+ test("composes with the other filters", async () => {
621
+ const group = createGroup("Work");
622
+ const inGroupUnseen = createConversation("in-group-unseen");
623
+ seedUnseen(inGroupUnseen.id);
624
+ rawRun(
625
+ "test:fileInGroup",
626
+ "UPDATE conversations SET group_id = ? WHERE id = ?",
627
+ group.id,
628
+ inGroupUnseen.id,
629
+ );
630
+ const outOfGroupUnseen = createConversation("out-of-group-unseen");
631
+ seedUnseen(outOfGroupUnseen.id);
632
+
633
+ const result = await invoke({ needsAttention: "true", groupId: group.id });
634
+
635
+ expect(result.conversations.map((c) => c.title)).toEqual([
636
+ "in-group-unseen",
637
+ ]);
638
+ });
639
+
640
+ test('any value other than "true" is rejected with a 400', () => {
641
+ /* Same posture as conversationType: silently reading a typo or a newer
642
+ client's value as "no filter" would hand back the full list where a
643
+ subset was asked for, and that skew is invisible to the client. */
644
+ for (const bad of ["false", "1", "yes", "TRUE"]) {
645
+ expect(() => invoke({ needsAttention: bad })).toThrow(BadRequestError);
646
+ }
647
+ });
648
+ });
649
+
517
650
  describe("GET /v1/conversations/unread-count", () => {
518
651
  const unreadCountHandler = findHandler(
519
652
  CONVERSATION_LIST_ROUTES,
@@ -209,28 +209,41 @@ function resolveOrThrow(rawId: string): string {
209
209
  // Handlers
210
210
  // ---------------------------------------------------------------------------
211
211
 
212
+ /**
213
+ * Read a query parameter that admits a closed set of values. Absent or empty
214
+ * reads as `undefined`; anything outside `accepted` is a 400. The strictness
215
+ * is the point: silently coercing a typo or a newer client's value to "no
216
+ * filter" would hand back the full list where a subset was asked for, and
217
+ * that skew is invisible to the client (it masks version skew too).
218
+ */
219
+ function parseEnumQueryParam<const T extends readonly string[]>(
220
+ queryParams: Record<string, string | undefined>,
221
+ name: string,
222
+ accepted: T,
223
+ ): T[number] | undefined {
224
+ const raw = queryParams[name];
225
+ if (raw === undefined || raw === "") {
226
+ return undefined;
227
+ }
228
+ if ((accepted as readonly string[]).includes(raw)) {
229
+ return raw as T[number];
230
+ }
231
+ throw new BadRequestError(
232
+ `Unknown ${name} "${raw}"; expected ${accepted.map((v) => `"${v}"`).join(" or ")}.`,
233
+ );
234
+ }
235
+
212
236
  function handleListConversations({ queryParams = {} }: RouteHandlerArgs) {
213
237
  const limit = Number(queryParams.limit ?? 50);
214
238
  const offset = Number(queryParams.offset ?? 0);
215
239
  // "background" is the back-compat umbrella (background + scheduled); newer
216
240
  // clients can pass "scheduled" to load only the Scheduled section. Absent
217
- // defaults to the standard foreground list. Any other value is rejected so
218
- // an unrecognized type surfaces as a 400 rather than being silently coerced
219
- // to the foreground list (which would mask client/daemon version skew).
220
- const rawConversationType = queryParams.conversationType;
221
- let conversationType: ConversationType = "standard";
222
- if (rawConversationType !== undefined && rawConversationType !== "") {
223
- if (
224
- rawConversationType === "background" ||
225
- rawConversationType === "scheduled"
226
- ) {
227
- conversationType = rawConversationType;
228
- } else {
229
- throw new BadRequestError(
230
- `Unknown conversationType "${rawConversationType}"; expected "background" or "scheduled".`,
231
- );
232
- }
233
- }
241
+ // defaults to the standard foreground list.
242
+ const conversationType: ConversationType =
243
+ parseEnumQueryParam(queryParams, "conversationType", [
244
+ "background",
245
+ "scheduled",
246
+ ]) ?? "standard";
234
247
  // Defaults to `active` so sidebar restores no longer pull archived rows.
235
248
  // The Archive page opts into `archived` to render only archived rows
236
249
  // without dragging the entire live history through pagination first.
@@ -251,11 +264,17 @@ function handleListConversations({ queryParams = {} }: RouteHandlerArgs) {
251
264
  ? queryParams.groupId
252
265
  : undefined;
253
266
 
267
+ const needsAttention =
268
+ parseEnumQueryParam(queryParams, "needsAttention", ["true"]) === "true"
269
+ ? true
270
+ : undefined;
271
+
254
272
  const filter: ConversationListFilter = {
255
273
  conversationType,
256
274
  archiveStatus,
257
275
  originChannel,
258
276
  groupId,
277
+ needsAttention,
259
278
  };
260
279
  let rows = listConversations({ ...filter, limit, offset });
261
280
  const totalCount = countConversations(filter);
@@ -270,15 +289,19 @@ function handleListConversations({ queryParams = {} }: RouteHandlerArgs) {
270
289
  // Skipped for group-scoped queries for the same reason: a caller asking
271
290
  // for one group gets that group, and a client that fetches the Pinned
272
291
  // section via `groupId=system:pinned` has no use for rows appended to
273
- // some other group's page. This is the compatibility shim for clients
274
- // that still read Pinned out of the unfiltered list; it goes away once
275
- // every section fetches its own group.
292
+ // some other group's page. Skipped for attention-scoped queries too: the
293
+ // caller asked for the unseen subset, and a seen pinned row appended to
294
+ // it would put a row outside the filter in the page while `hasMore` is
295
+ // computed from the filtered count. This is the compatibility shim for
296
+ // clients that still read Pinned out of the unfiltered list; it goes
297
+ // away once every section fetches its own group.
276
298
  if (
277
299
  offset === 0 &&
278
300
  conversationType === "standard" &&
279
301
  archiveStatus === "active" &&
280
302
  originChannel === undefined &&
281
- groupId === undefined
303
+ groupId === undefined &&
304
+ needsAttention === undefined
282
305
  ) {
283
306
  const pinned = listPinnedConversations(archiveStatus);
284
307
  const seen = new Set(rows.map((c) => c.id));
@@ -580,6 +603,14 @@ export const ROUTES: RouteDefinition[] = [
580
603
  description:
581
604
  'Filter to a single group, so each sidebar section can load independently of the paginated list. Pass "system:all" for conversations in no group, "system:pinned" for the Pinned section, or a custom group id. A group-scoped request is recency-ordered like every list read (COALESCE(last_message_at, updated_at) descending) and never has pinned rows appended to it. Omit to span every group.',
582
605
  },
606
+ {
607
+ name: "needsAttention",
608
+ type: "string",
609
+ required: false,
610
+ description:
611
+ 'Pass "true" to return only conversations whose latest assistant message the user has not seen: the same predicate behind the unread count and the section index, so a client that keeps no complete conversation list can ask for exactly the rows its attention surfaces need. Composes with every other filter. Any value other than "true" is rejected. Omit to span every conversation.',
612
+ schema: { type: "string", enum: ["true"] },
613
+ },
583
614
  ],
584
615
  responseBody: listConversationsResponseSchema,
585
616
  handler: handleListConversations,