Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

feat: show opening messages in assistant history (#3858)

Amruth Pillaib67c8db2480a
diff --git a/apps/mobile/scripts/assistant-history.test.mjs b/apps/mobile/scripts/assistant-history.test.mjs
new file mode 100644
index 000000000..e5510c9c3
--- /dev/null
+++ b/apps/mobile/scripts/assistant-history.test.mjs
@@ -0,0 +1,142 @@
+import assert from "node:assert/strict";
+import { createRequire } from "node:module";
+import { test } from "node:test";
+import { fileURLToPath } from "node:url";
+
+const root = fileURLToPath(new URL("../../..", import.meta.url));
+const serverRequire = createRequire(`${root}/apps/server/package.json`);
+const { buildSync } = createRequire(serverRequire.resolve("tsx"))("esbuild");
+const jsx = (type, props) => ({ type, props });
+const dependencies = {
+ "react/jsx-runtime": { jsx, jsxs: jsx },
+ react: { useState: (value) => [value, () => {}] },
+ "react-native": { ScrollView: "ScrollView", View: "View" },
+ "@lingui/core/macro": { plural: (_count, options) => options.other.replace("#", "2") },
+ "@lingui/react/macro": {
+ Trans: "Trans",
+ useLingui: () => ({
+ t: (pieces, ...values) => pieces.reduce((text, part, index) => text + part + (values[index] ?? ""), ""),
+ i18n: { locale: "en-US" },
+ }),
+ },
+ "@tanstack/react-query": { useQueryClient: () => ({}) },
+ "./chat": { refreshThreads: () => {} },
+ "@/api/client": { client: {} },
+ "@/auth/session": { getAccountScope: () => "fixture-account" },
+ "@/ui": {
+ ConfirmDialog: "ConfirmDialog",
+ IconButton: "IconButton",
+ ListRow: "ListRow",
+ Text: "Text",
+ showToast: () => {},
+ useTheme: () => ({ space: {} }),
+ },
+};
+function load(file, dependencies) {
+ const code = buildSync({
+ entryPoints: [`${root}/apps/mobile/src/${file}`],
+ bundle: true,
+ platform: "node",
+ format: "cjs",
+ write: false,
+ jsx: "automatic",
+ external: Object.keys(dependencies),
+ }).outputFiles[0].text;
+ const module = { exports: {} };
+ new Function("require", "module", "exports", code)(
+ (name) => {
+ assert.ok(name in dependencies, `Unexpected dependency ${name}`);
+ return dependencies[name];
+ },
+ module,
+ module.exports,
+ );
+ return module.exports;
+}
+const { PastConversations } = load("features/assistant/threads.tsx", dependencies);
+
+test("native history retains task title, original-message subtitle and open action, including old servers", () => {
+ const thread = {
+ id: "history-thread",
+ title: "Tailor summary to payments roles",
+ firstMessage: "I'm applying for payments roles. Please tailor my summary.",
+ lastMessageAt: "2026-11-02T12:00:00Z",
+ editsProposed: 2,
+ editsAccepted: 1,
+ };
+ for (const firstMessage of [thread.firstMessage, "Long opening message ".repeat(8).slice(0, 160), null, undefined]) {
+ const opened = [];
+ const tree = PastConversations({
+ threads: [{ ...thread, firstMessage }],
+ isMine: () => true,
+ currentId: thread.id,
+ onOpen: (value) => opened.push(value.id),
+ onDeleted: () => {},
+ });
+ const section = tree.props.children[0];
+ const row = section.props.children[0];
+ assert.equal(row.props.title, thread.title);
+ assert.equal(typeof row.props.subtitle, "object", "preview and metadata need separate native Text nodes");
+ const parts = row.props.subtitle.props.children.filter(Boolean);
+ const metadata = parts.at(-1);
+ assert.ok(metadata.props.children.includes("1 of 2 edits accepted"));
+ assert.equal(metadata.props.numberOfLines, undefined, "preview truncation must not hide metadata");
+ assert.equal(parts.length, firstMessage ? 2 : 1);
+ if (firstMessage) {
+ assert.equal(parts[0].props.children, firstMessage);
+ assert.equal(parts[0].props.numberOfLines, 1);
+ assert.equal(parts[0].props.ellipsizeMode, "tail");
+ }
+ assert.equal(row.props.selected, true);
+ row.props.onPress();
+ assert.deepEqual(opened, [thread.id]);
+ }
+});
+
+test("ListRow preserves separately bounded preview elements and existing string subtitles at larger fonts", () => {
+ let fontScale = 1;
+ const { ListRow } = load("ui/layout.tsx", {
+ ...dependencies,
+ "react-native": {
+ Platform: { OS: "ios" },
+ Pressable: "Pressable",
+ StyleSheet: { hairlineWidth: 1 },
+ View: "View",
+ useWindowDimensions: () => ({ fontScale }),
+ },
+ "expo-image": {},
+ "react-native-reanimated": {},
+ "@reactive-resume/utils/string": {},
+ "./button": {},
+ "./icon": { Icon: "Icon" },
+ "./motion": {},
+ "./pressable": {},
+ "./text": { Text: "Text" },
+ "./theme": {
+ useTheme: () => ({ colors: {}, size: { row: 48, icon: {} }, space: { s1: 4, s2: 8, s3: 12, s4: 16 } }),
+ },
+ });
+ const nodes = (tree) =>
+ Array.isArray(tree)
+ ? tree.flatMap(nodes)
+ : tree && typeof tree === "object"
+ ? [tree, ...nodes(tree.props?.children)]
+ : [];
+ const preview = jsx("Text", { children: "Long opening message", numberOfLines: 1, ellipsizeMode: "tail" });
+ const metadata = jsx("Text", { children: "Today · no edits" });
+ const richSubtitle = jsx("View", { children: [preview, metadata] });
+ for (fontScale of [1, 2]) {
+ for (const subtitle of [richSubtitle, "Existing subtitle", "", undefined]) {
+ const tree = ListRow({ title: "Task", subtitle });
+ const text = nodes(tree).filter((node) => node.type === "Text");
+ assert.deepEqual(
+ text.map((node) => node.props.children),
+ subtitle === richSubtitle
+ ? ["Task", preview.props.children, metadata.props.children]
+ : subtitle
+ ? ["Task", subtitle]
+ : ["Task"],
+ );
+ }
+ }
+});
diff --git a/apps/mobile/src/features/assistant/threads.tsx b/apps/mobile/src/features/assistant/threads.tsx
index fb6dd8b95..0daafd765 100644
--- a/apps/mobile/src/features/assistant/threads.tsx
+++ b/apps/mobile/src/features/assistant/threads.tsx
@@ -86,13 +86,24 @@ export function PastConversations({ threads, isMine, currentId, onOpen, onDelete
<ListRow
key={thread.id}
title={title(thread)}
- subtitle={[
- time(thread.lastMessageAt),
- outcome(thread),
- ...(other ? [thread.coverLetterName ?? thread.resumeName ?? ""] : []),
- ]
- .filter(Boolean)
- .join(" · ")}
+ subtitle={
+ <View style={{ gap: 1 }}>
+ {thread.firstMessage ? (
+ <Text variant="callout" color="ink2" numberOfLines={1} ellipsizeMode="tail">
+ {thread.firstMessage}
+ </Text>
+ ) : null}
+ <Text variant="callout" color={thread.id === currentId ? "ink2" : "ink3"}>
+ {[
+ time(thread.lastMessageAt),
+ outcome(thread),
+ ...(other ? [thread.coverLetterName ?? thread.resumeName ?? ""] : []),
+ ]
+ .filter(Boolean)
+ .join(" · ")}
+ </Text>
+ </View>
+ }
selected={thread.id === currentId}
onPress={() => onOpen(thread)}
trailing={<IconButton icon="dots-three" label={t`Delete ${title(thread)}`} onPress={() => remove.ask(thread)} />}
diff --git a/apps/mobile/src/ui/layout.tsx b/apps/mobile/src/ui/layout.tsx
index a3cd56511..56cd0b339 100644
--- a/apps/mobile/src/ui/layout.tsx
+++ b/apps/mobile/src/ui/layout.tsx
@@ -30,7 +30,8 @@ const android = Platform.OS === "android";
export type ListRowProps = {
title: string;
- subtitle?: string | undefined;
+ /** Strings use standard subtitle styling; an element owns its text layout. */
+ subtitle?: string | ReactElement | undefined;
/** An icon name, or any element (avatar, checkbox, thumbnail). */
leading?: IconName | ReactNode;
/** A value, switch or badge at the end. */
@@ -53,6 +54,7 @@ export type ListRowProps = {
divider?: boolean | undefined;
};
+/** Strings share row typography; elements retain their own layout and truncation. */
export function ListRow({
title,
subtitle,
@@ -164,9 +166,13 @@ export function ListRow({
{title}
</Text>
{subtitle ? (
- <Text variant="callout" color={quiet}>
- {subtitle}
- </Text>
+ typeof subtitle === "string" ? (
+ <Text variant="callout" color={quiet}>
+ {subtitle}
+ </Text>
+ ) : (
+ subtitle
+ )
) : null}
{stacked && (value || trailing) ? (
<View style={{ alignItems: "flex-start", gap: space.s1, paddingTop: space.s1 }}>{accessory}</View>
diff --git a/apps/web/src/features/assistant/assistant-panel.test.tsx b/apps/web/src/features/assistant/assistant-panel.test.tsx
index 552f8c381..401129ae4 100644
--- a/apps/web/src/features/assistant/assistant-panel.test.tsx
+++ b/apps/web/src/features/assistant/assistant-panel.test.tsx
@@ -4,6 +4,7 @@ import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/re
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
import { i18n } from "@lingui/core";
import { I18nProvider } from "@lingui/react";
+import { ConfirmDialogProvider } from "@/hooks/use-confirm";
const mocks = vi.hoisted(() => ({
selected: null as string | null,
@@ -75,6 +76,39 @@ beforeEach(() => {
});
afterEach(cleanup);
+it("keeps task titles and shows the original message in history, with old-server fallback", () => {
+ mocks.selected = "new";
+ const thread = {
+ id: "history-thread",
+ workingResumeId: document.id,
+ coverLetterId: null,
+ aiProviderId: "provider-1",
+ title: "Tailor summary to payments roles",
+ firstMessage: "I'm applying for payments roles. Please tailor my summary.",
+ lastMessageAt: new Date("2026-11-02T12:00:00Z"),
+ editsProposed: 2,
+ editsAccepted: 1,
+ };
+ mocks.threads = [thread];
+ const panel = () => (
+ <I18nProvider i18n={i18n}>
+ <ConfirmDialogProvider>
+ <AssistantPanel document={document} onClose={() => {}} />
+ </ConfirmDialogProvider>
+ </I18nProvider>
+ );
+ const { rerender } = render(panel());
+ fireEvent.click(screen.getByRole("button", { name: "Past conversations" }));
+ const row = screen.getByRole("button", { name: /Tailor summary to payments roles.*I'm applying/ });
+ expect(row.textContent).toContain(thread.firstMessage);
+ expect(row.textContent).toContain("1 of 2 edits accepted");
+ expect(mocks.start).not.toHaveBeenCalled();
+ mocks.threads = [{ ...thread, firstMessage: undefined }];
+ rerender(panel());
+ expect(screen.queryByText(thread.firstMessage)).toBeNull();
+ expect(screen.getByText(thread.title)).toBeDefined();
+});
+
it("states resume scope before sending and routes Open Write to this resume", () => {
const onClose = vi.fn();
render(
diff --git a/apps/web/src/features/assistant/assistant-panel.tsx b/apps/web/src/features/assistant/assistant-panel.tsx
index f9964557a..d5aa98e3d 100644
--- a/apps/web/src/features/assistant/assistant-panel.tsx
+++ b/apps/web/src/features/assistant/assistant-panel.tsx
@@ -706,6 +706,7 @@ type ConversationRowProps = {
onDelete: () => void;
};
+/** A request remains recognizable even when its proposed edits give the conversation a new title. */
function ConversationRow({ thread, current, detail, index, onOpen, onDelete }: ConversationRowProps) {
return (
<li
@@ -727,6 +728,7 @@ function ConversationRow({ thread, current, detail, index, onOpen, onDelete }: C
)}
>
<span className="truncate text-sm font-medium">{thread.title}</span>
+ {thread.firstMessage && <span className="truncate text-sm text-ink-2">{thread.firstMessage}</span>}
<span className="truncate text-xs text-ink-3">{detail}</span>
</button>
<IconButton
diff --git a/docs/guides/using-the-assistant.mdx b/docs/guides/using-the-assistant.mdx
index 52a44dd32..648138a01 100644
--- a/docs/guides/using-the-assistant.mdx
+++ b/docs/guides/using-the-assistant.mdx
@@ -237,12 +237,12 @@ Each conversation belongs to one document. Opening the assistant continues that
<Frame caption="Reopen a saved conversation">
<img
- src="/images/guides/using-the-assistant/past-conversations.webp"
- alt="Assistant past conversations list with the fictional resume conversations"
+ src="/images/guides/using-the-assistant/past-conversations.png"
+ alt="Assistant history with a task title, the fictional opening message beneath it, and edit counts"
/>
</Frame>
-Conversations are titled by the first set of edits the assistant proposed ("Tailor summary to payments roles"), or by your first message until there is one, and show how many edits you accepted. While a conversation is open, its address is in the page's URL, so reloading the page reopens it. Conversations about your other documents appear under **Other documents**; opening one takes you to that document. To delete a conversation, hover over it, select **×**, then confirm. Its messages and attachments are deleted, but edits you accepted stay in your document.
+Conversations are titled by the first set of edits the assistant proposed ("Tailor summary to payments roles"), or by your first message until there is one. A one-line preview of your original first message appears below the title on web and mobile, followed by the time and how many edits you accepted. This uses the saved message, without another AI request. An attachment-only opening has no message preview. While a conversation is open, its address is in the page's URL, so reloading the page reopens it. Conversations about your other documents appear under **Other documents**; opening one takes you to that document. To delete a conversation, hover over it, select **×**, then confirm. Its messages and attachments are deleted, but edits you accepted stay in your document.
On a locked document the assistant still answers questions and writes drafts, such as a follow-up email or interview notes, but proposes no edits. The note above the message box offers **Unlock**. A deleted document keeps its conversation read-only, and an old link to a deleted conversation opens Documents with a note saying so. If a provider is off, broken or deleted, history and pending edits stay readable. You can accept saved edits and undo document changes while sending pauses. Repair the connection through **Set up AI**, or choose another model and approve its destination. The app never moves a conversation automatically.
diff --git a/docs/images/guides/using-the-assistant/past-conversations.png b/docs/images/guides/using-the-assistant/past-conversations.png
new file mode 100644
index 000000000..d80350ad6
Binary files /dev/null and b/docs/images/guides/using-the-assistant/past-conversations.png differ
diff --git a/docs/images/guides/using-the-assistant/past-conversations.webp b/docs/images/guides/using-the-assistant/past-conversations.webp
deleted file mode 100644
index 72b921494..000000000
Binary files a/docs/images/guides/using-the-assistant/past-conversations.webp and /dev/null differ
diff --git a/docs/spec.json b/docs/spec.json
index 2185c8f77..29ce335ec 100644
--- a/docs/spec.json
+++ b/docs/spec.json
@@ -13951,6 +13951,16 @@
"title": {
"type": "string"
},
+ "firstMessage": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"status": {
"type": "string"
},
@@ -14253,6 +14263,16 @@
"title": {
"type": "string"
},
+ "firstMessage": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"status": {
"type": "string"
},
@@ -14512,6 +14532,16 @@
"title": {
"type": "string"
},
+ "firstMessage": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"status": {
"type": "string"
},
@@ -14956,6 +14986,16 @@
"title": {
"type": "string"
},
+ "firstMessage": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"status": {
"type": "string"
},
diff --git a/packages/api/src/dto/agent.ts b/packages/api/src/dto/agent.ts
index 6c0c66540..c22db3db1 100644
--- a/packages/api/src/dto/agent.ts
+++ b/packages/api/src/dto/agent.ts
@@ -13,6 +13,8 @@ export const uiMessageSchema = z.object({
export const agentThreadSchema = z.object({
id: z.string(),
title: z.string(),
+ /** Opening-message preview in history; older servers and non-list responses may omit it. */
+ firstMessage: z.string().nullable().optional(),
status: z.string(),
scope: z.enum(["document", "application", "career"]),
applicationId: z.string().nullable(),
diff --git a/packages/api/src/features/agent/review.integration.test.ts b/packages/api/src/features/agent/review.integration.test.ts
index c5b72c0ef..1d74e5091 100644
--- a/packages/api/src/features/agent/review.integration.test.ts
+++ b/packages/api/src/features/agent/review.integration.test.ts
@@ -1,6 +1,7 @@
import type { ProposeEditsOutput } from "@reactive-resume/ai/tools/agent-tool-contracts";
import type { Proposal } from "@reactive-resume/resume/proposals";
import type { UIMessage } from "ai";
+import type { QueryConfig } from "pg";
import { randomUUID } from "node:crypto";
import { existsSync } from "node:fs";
import { readdir, readFile } from "node:fs/promises";
@@ -214,6 +215,132 @@ describe.skipIf(!databaseUrl)("document assistant review on PostgreSQL", () => {
return proposalOf((await send(threadId, {})).messages);
}
+ it("lists the original owned opening message beneath the task title without generating a subtitle", async () => {
+ const db = fixture.db;
+ if (!db) throw new Error("Missing fixture database");
+ const thread = await agent.threads.start({ userId, resumeId: copyId });
+ const attachmentOnly = await agent.threads.start({ userId, resumeId: copyId });
+ const empty = await agent.threads.start({ userId, resumeId: copyId });
+ await pool.query("UPDATE agent_threads SET title = $1 WHERE id = $2", [
+ "Tailor summary to payments roles",
+ thread.id,
+ ]);
+ await db.insert(tables.user).values({
+ id: "history-stranger",
+ name: "Other Fictional User",
+ email: "[email protected]",
+ username: `${schemaName}-other`,
+ displayUsername: `${schemaName}-other`,
+ });
+ await db.insert(tables.agentThread).values({ id: "foreign-history", userId: "history-stranger", title: "Private" });
+ await db.insert(tables.agentMessage).values([
+ {
+ userId,
+ threadId: thread.id,
+ role: "assistant",
+ sequence: 0,
+ uiMessage: { role: "assistant", parts: [{ type: "text", text: "Not the opener" }] },
+ },
+ {
+ userId: "history-stranger",
+ threadId: thread.id,
+ role: "user",
+ sequence: 1,
+ uiMessage: { role: "user", parts: [{ type: "text", text: "FOREIGN_MESSAGE_MUST_STAY_PRIVATE" }] },
+ },
+ {
+ userId,
+ threadId: thread.id,
+ role: "user",
+ sequence: 2,
+ uiMessage: {
+ role: "user",
+ parts: [
+ { type: "text", text: "I'm applying for payments roles.\n" },
+ { type: "file", url: "agent-attachment:posting", mediaType: "text/plain" },
+ { type: "text", text: "Please tailor my summary." },
+ ],
+ },
+ },
+ {
+ userId,
+ threadId: thread.id,
+ role: "user",
+ sequence: 3,
+ uiMessage: { role: "user", parts: [{ type: "text", text: "Later follow-up" }] },
+ },
+ {
+ userId,
+ threadId: attachmentOnly.id,
+ role: "user",
+ sequence: 0,
+ uiMessage: { role: "user", parts: [{ type: "file", url: "agent-attachment:notes", mediaType: "text/plain" }] },
+ },
+ {
+ userId,
+ threadId: attachmentOnly.id,
+ role: "user",
+ sequence: 1,
+ uiMessage: { role: "user", parts: [{ type: "text", text: "Do not substitute this follow-up" }] },
+ },
+ ]);
+ const calls = fixture.prompts.length;
+ const summaries = await agent.threads.list({ userId });
+ expect(summaries.find((row) => row.id === thread.id)).toMatchObject({
+ title: "Tailor summary to payments roles",
+ firstMessage: "I'm applying for payments roles. Please tailor my summary.",
+ });
+ expect(summaries.find((row) => row.id === attachmentOnly.id)?.firstMessage).toBeNull();
+ expect(summaries.find((row) => row.id === empty.id)?.firstMessage).toBeNull();
+ expect(summaries.some((row) => row.id === "foreign-history")).toBe(false);
+ expect(JSON.stringify(summaries)).not.toContain("FOREIGN_MESSAGE_MUST_STAY_PRIVATE");
+ await db.insert(tables.agentMessage).values({
+ userId,
+ threadId: empty.id,
+ role: "user",
+ sequence: 0,
+ uiMessage: {
+ role: "user",
+ parts: [{ type: "text", text: "Research roles and prepare my summary. ".repeat(10_000) }],
+ },
+ });
+ // Observe actual PostgreSQL result bytes before the service formats its preview.
+ let databaseBytes = 0;
+ const query: (config: string | QueryConfig, values?: unknown[]) => Promise<{ rows: unknown[] }> =
+ pool.query.bind(pool);
+ const capture = vi.spyOn(pool, "query").mockImplementation((...args) => {
+ const result: ReturnType<typeof query> = Reflect.apply(query, pool, args);
+ return result.then((result) => {
+ databaseBytes += Buffer.byteLength(JSON.stringify(result.rows));
+ return result;
+ });
+ });
+ let preview: string | null | undefined;
+ try {
+ preview = (await agent.threads.list({ userId })).find((row) => row.id === empty.id)?.firstMessage;
+ } finally {
+ capture.mockRestore();
+ }
+ expect(databaseBytes).toBeGreaterThan(0);
+ expect(databaseBytes).toBeLessThan(10_000);
+ expect(preview).toMatch(/^Research roles.*…$/);
+ expect(preview?.length).toBeLessThanOrEqual(160);
+ expect(fixture.prompts).toHaveLength(calls);
+ });
+
+ it("keeps emoji intact at both the initial task-title and history-preview cutoffs", async () => {
+ const thread = await agent.threads.start({ userId, resumeId: copyId });
+ const text = `${"a".repeat(58)}😀${"b".repeat(98)}😀tail`;
+ fixture.plan.push({ text: "Done." });
+ await send(thread.id, {}, { id: randomUUID(), role: "user", parts: [{ type: "text", text }] });
+ const summary = (await agent.threads.list({ userId })).find((row) => row.id === thread.id);
+ expect.soft(summary?.title.isWellFormed()).toBe(true);
+ expect.soft(summary?.firstMessage?.isWellFormed()).toBe(true);
+ expect(summary?.title).not.toContain("\uFFFD");
+ expect(summary?.title.length).toBeLessThanOrEqual(60);
+ expect(summary?.firstMessage?.length).toBeLessThanOrEqual(160);
+ });
+
it("never sends or shows a Knowledge reply once sharing is off or the fact is forgotten", async () => {
const { id: threadId } = await agent.threads.start({ userId, resumeId: copyId });
const passage = (await loadDocument(userId, { kind: "resume", id: copyId })).passages[0];
diff --git a/packages/api/src/features/agent/service.ts b/packages/api/src/features/agent/service.ts
index 95eab70d1..48bfabb46 100644
--- a/packages/api/src/features/agent/service.ts
+++ b/packages/api/src/features/agent/service.ts
@@ -177,15 +177,20 @@ type AttachmentModelInput = {
};
type ThreadSummaryRow = AgentThreadRecord & {
+ firstMessage?: string | null;
resumeName?: string | null;
coverLetterName?: string | null;
providerLabel?: string | null;
};
+/** The original request stays discoverable after a proposed task retitles the conversation. */
function toThreadSummary(row: ThreadSummaryRow) {
return {
id: row.id,
title: row.title,
+ ...(row.firstMessage !== undefined
+ ? { firstMessage: row.firstMessage ? buildThreadTitle(row.firstMessage, "", 160) || null : null }
+ : {}),
status: row.status,
scope: (row.scope ?? "document") as "document" | "application" | "career",
applicationId: row.applicationId ?? null,
@@ -719,15 +724,16 @@ function messageText(message: UIMessage) {
return textParts.join(" ").trim();
}
-/** The first message names the conversation: up to 57 characters, or 44 in the career coach's list. */
-function buildThreadTitle(message: UIMessage, fallback: string, max = 60) {
- const text = messageText(message).replace(/\s+/g, " ").trim();
+/** Opening text names new conversations; history uses a longer preview of that same request. */
+function buildThreadTitle(input: string, fallback: string, max = 60) {
+ const text = input.replace(/\s+/g, " ").trim();
if (!text) return fallback;
if (text.length <= max) return text;
// Cut at a word, with one ellipsis character, so the list doesn't add a second.
const cut = text.slice(0, max - 1);
const space = cut.lastIndexOf(" ");
- return `${(space > max / 2 ? cut.slice(0, space) : cut).trimEnd()}…`;
+ const bounded = (space > max / 2 ? cut.slice(0, space) : cut).trimEnd();
+ return `${bounded.replace(/[\uD800-\uDBFF]$/u, "")}…`;
}
/**
@@ -1117,6 +1123,21 @@ function createAgent(input: {
const threadSummarySelection = {
...getColumns(schema.agentThread),
+ // One extra character preserves truncation detection; full messages stay in PostgreSQL.
+ firstMessage: sql<string | null>`(
+ select left(btrim(regexp_replace(coalesce((
+ select string_agg(part.value ->> 'text', ' ' order by part.position)
+ from jsonb_array_elements(opening.message -> 'parts') with ordinality as part(value, position)
+ where part.value ->> 'type' = 'text'
+ ), ''), '[[:space:]]+', ' ', 'g')), 161)
+ from (
+ select ${schema.agentMessage.uiMessage} as message from ${schema.agentMessage}
+ where ${schema.agentMessage.threadId} = ${schema.agentThread.id}
+ and ${schema.agentMessage.userId} = ${schema.agentThread.userId}
+ and ${schema.agentMessage.role} = 'user'
+ order by ${schema.agentMessage.sequence} asc limit 1
+ ) opening
+ )`,
resumeName: schema.resume.name,
coverLetterName: schema.coverLetter.name,
providerLabel: schema.aiProvider.label,
@@ -1553,7 +1574,7 @@ export const agentService = {
if ((messageCount?.total ?? 0) === 1) {
await db
.update(schema.agentThread)
- .set({ title: buildThreadTitle(userMessage, thread.title, isCareer ? 47 : 60) })
+ .set({ title: buildThreadTitle(messageText(userMessage), thread.title, isCareer ? 47 : 60) })
.where(and(eq(schema.agentThread.id, input.threadId), eq(schema.agentThread.userId, input.userId)));
}
}
diff --git a/tests/e2e/specs/assistant.spec.ts b/tests/e2e/specs/assistant.spec.ts
index af44b0ead..3d7381d14 100644
--- a/tests/e2e/specs/assistant.spec.ts
+++ b/tests/e2e/specs/assistant.spec.ts
@@ -49,6 +49,39 @@ async function send(page: Page, text: string) {
}).toPass({ timeout: 20_000 });
}
+test("history keeps the original opening message beneath its task title without more AI calls", async ({
+ authPage: page,
+}, testInfo) => {
+ test.setTimeout(90_000);
+ await createSampleResumeFromDashboard(page, testInfo);
+ const resumeId = resumeIdOf(page);
+ await page.getByRole("button", { name: "Assistant", exact: true }).click();
+ await connectStub(page);
+ const opening = "I'm applying for payments roles. Please tighten my summary.";
+ await send(page, opening);
+ await expect(page.getByRole("list", { name: "Proposed edits" })).toBeVisible({ timeout: 20_000 });
+ await expect(page.getByRole("button", { name: "Stop", exact: true })).toBeHidden();
+ const calls = stub.requests.length;
+ const response = await page.request.get("/api/openapi/agent/threads");
+ await expect(response).toBeOK();
+ const threads = (await response.json()) as Array<{ workingResumeId: string; title: string; firstMessage: string }>;
+ expect(threads.find((thread) => thread.workingResumeId === resumeId)).toMatchObject({
+ title: "Tighten the first passage",
+ firstMessage: opening,
+ });
+ await page.getByRole("button", { name: "Past conversations", exact: true }).click();
+ const row = page.getByRole("button", { name: /^Tighten the first passage/ });
+ await expect(row).toContainText(opening);
+ await expect(row).toContainText("0 of 1 edits accepted");
+ await page
+ .getByRole("region", { name: "Assistant" })
+ .screenshot({ path: testInfo.outputPath("past-conversations.png") });
+ await page.reload();
+ await page.getByRole("button", { name: "Past conversations", exact: true }).click();
+ await expect(row).toContainText(opening);
+ expect(stub.requests).toHaveLength(calls);
+});
+
test("proposes edits that change nothing until accepted, asks before assuming, and stops", async ({
authPage: page,
}, testInfo) => {