Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

feat(goals): keep thread goals visible (#5961)

vincent05540c4eb768
diff --git a/server/message-db-goals.ts b/server/message-db-goals.ts
new file mode 100644
index 0000000000..ea603171a3
--- /dev/null
+++ b/server/message-db-goals.ts
@@ -0,0 +1,34 @@
+import { prepared } from "./message-db.ts";
+import type { Message } from "./store.ts";
+
+const STARTED_AT = "COALESCE(json_extract(json, '$.goalRun.startedAt'), at)";
+const THREAD_GOALS = "FROM messages INDEXED BY messages_thread_goals WHERE thread_id = ? AND kind = 'goal.run'";
+const ORDER = `ORDER BY ${STARTED_AT} DESC, at DESC, id DESC LIMIT ?`;
+
+export const GOAL_MESSAGE_INDEXES_SQL = `
+ CREATE INDEX IF NOT EXISTS messages_thread_goals ON messages(thread_id, ${STARTED_AT}, at, id) WHERE kind = 'goal.run';
+ CREATE INDEX IF NOT EXISTS messages_goal_run ON messages(at) WHERE kind = 'goal.run';`;
+
+export function threadGoalPage(threadId: string, limit: number, before: string | null): { messages: Message[]; nextBefore: string | null } | null {
+ let rows: Array<{ json: string }>;
+ if (before === null) {
+ rows = prepared(`SELECT json ${THREAD_GOALS} ${ORDER}`).all(threadId, limit + 1) as typeof rows;
+ } else {
+ const pivot = prepared(
+ `SELECT ${STARTED_AT} AS startedAt, at FROM messages WHERE thread_id = ? AND id = ? AND kind = 'goal.run'`,
+ ).get(threadId, before) as { startedAt: number; at: number } | undefined;
+ if (!pivot) return null;
+ // SQLite can seek by the scalar expression bound even when it leaves the tuple comparison as a filter.
+ rows = prepared(`SELECT json ${THREAD_GOALS} AND ${STARTED_AT} <= ? AND (${STARTED_AT}, at, id) < (?, ?, ?) ${ORDER}`)
+ .all(threadId, pivot.startedAt, pivot.startedAt, pivot.at, before, limit + 1) as typeof rows;
+ }
+ const messages = rows.slice(0, limit).map((row) => JSON.parse(row.json) as Message);
+ return { messages, nextBefore: rows.length > limit ? messages.at(-1)!.id : null };
+}
+
+export function workingGoalRunMessages(): Array<{ threadId: string; message: Message }> {
+ const rows = prepared(
+ "SELECT thread_id, json FROM messages WHERE kind = 'goal.run' AND json_extract(json, '$.goalRun.status') = 'working'",
+ ).all() as Array<{ thread_id: string; json: string }>;
+ return rows.map((row) => ({ threadId: row.thread_id, message: JSON.parse(row.json) as Message }));
+}
diff --git a/server/message-db.ts b/server/message-db.ts
index f896d3633d..91bfacd79b 100644
--- a/server/message-db.ts
+++ b/server/message-db.ts
@@ -9,6 +9,7 @@ import type { ResolvedSender, SteerQueueReason } from "../shared/wire.ts";
import type { Message } from "./store.ts";
import type { UsageTrigger } from "./usage-ledger.ts";
import { BOT_TEXT_MESSAGE_INDEXES_SQL } from "./message-db-bot-text-indexes.ts";
+import { GOAL_MESSAGE_INDEXES_SQL } from "./message-db-goals.ts";
import { ensureMemoryIndex } from "./message-db-memory-index.ts"; import { createAttachmentNameIndex, STORED_UPLOAD_NAME } from "./message-db-attachment-names.ts";
import { cjkSearchText, cjkTokenParts, ensureSearchIndex, ftsPhrase, hasCjk, withoutSearchMarks } from "./cjk-search.ts";
import { attentionSelect } from "./message-db-attention.ts";
@@ -16,6 +17,7 @@ import { MessageSearchWorker } from "./message-search-worker.ts"; import { messa
import { searchMessagesInDatabase, type SearchHit } from "./message-search-query.ts";
import type { Notification, NotificationLogEntry } from "../shared/notification.ts";
export type { SearchHit } from "./message-search-query.ts";
+export { workingGoalRunMessages } from "./message-db-goals.ts";
const DB_FILE = () => join(DATA_DIR, "messages.db");
/** The rows the Today page reads, and among them the failed tool calls. JSON.stringify escapes every quote inside a
@@ -68,8 +70,8 @@ function open(): DatabaseSync {
CREATE INDEX IF NOT EXISTS messages_work_at ON messages(kind, at) WHERE ${WORK_KINDS};
CREATE INDEX IF NOT EXISTS messages_cards_at ON messages(kind, at) WHERE ${CARD_KINDS};
CREATE INDEX IF NOT EXISTS messages_failed_at ON messages(at) WHERE ${FAILED_CALL};
+ ${GOAL_MESSAGE_INDEXES_SQL}
-- For the periodic scans, whose WHERE clauses no index above repeats.
- CREATE INDEX IF NOT EXISTS messages_goal_run ON messages(at) WHERE kind = 'goal.run';
CREATE INDEX IF NOT EXISTS messages_app ON messages(at) WHERE kind = 'app';
CREATE INDEX IF NOT EXISTS messages_open_rescue ON messages(at) WHERE kind = 'activity' AND json_extract(json, '$.tool.rescue') IS NOT NULL AND json_extract(json, '$.tool.rescue.settled') IS NULL AND json_extract(json, '$.tool.rescue.over') IS NULL;
CREATE TABLE IF NOT EXISTS thread_state (
@@ -469,16 +471,6 @@ export function updateMessage(threadId: string, message: Message): void {
const json = JSON.stringify(message); prepared("UPDATE messages SET at = ?, role = ?, kind = ?, text = ?, json = ?, search_text = ? WHERE thread_id = ? AND id = ?").run(message.at, message.role, message.kind, message.text ?? null, json, cjkSearchText(message.text), threadId, message.id); messageWritten(json); attachmentNameIndex.written(threadId, message.id, json);
}
-export function workingGoalRunMessages(): Array<{ threadId: string; message: Message }> {
- const rows = db()
- .prepare(
- "SELECT thread_id, json FROM messages " +
- "WHERE kind = 'goal.run' AND json_extract(json, '$.goalRun.status') = 'working'",
- )
- .all() as Array<{ thread_id: string; json: string }>;
- return rows.map((row) => ({ threadId: row.thread_id, message: JSON.parse(row.json) as Message }));
-}
-
/** First-reply rescue rows that never settled or ended: at boot, every one of them belongs to a turn that is gone. */
export function openRescueMessages(): Array<{ threadId: string; message: Message }> {
const rows = db()
diff --git a/server/places/place-proxy.test.ts b/server/places/place-proxy.test.ts
index 7f7f1117c1..9032124a85 100644
--- a/server/places/place-proxy.test.ts
+++ b/server/places/place-proxy.test.ts
@@ -95,7 +95,10 @@ describe("the conversation of a My Cloud bot, through this computer's server", (
expect((await ask("/api/bots/cloud:scout/messages", { method: "POST", body: JSON.stringify({ threadId: "cloud:t1", text: "cloud: hi", attachments: [{ path: "cloud--aa11-bb22.png" }] }) })).status).toBe(200);
expect((await ask("/api/bots/cloud:scout/interrupt", { method: "POST", body: JSON.stringify({ threadId: "cloud:t1" }) })).status).toBe(200);
expect((await ask("/api/threads/cloud%3At2/messages?limit=40&before=m1")).status).toBe(200);
- expect(seen.map(({ method, url }) => `${method} ${url}`)).toEqual(["POST /api/bots/scout/messages", "POST /api/bots/scout/interrupt", "GET /api/threads/t2/messages?limit=40&before=m1"]);
+ expect((await ask("/api/threads/cloud%3At2/goals?limit=1&before=m1")).status).toBe(200);
+ expect(seen.map(({ method, url }) => `${method} ${url}`)).toEqual([
+ "POST /api/bots/scout/messages", "POST /api/bots/scout/interrupt", "GET /api/threads/t2/messages?limit=40&before=m1", "GET /api/threads/t2/goals?limit=1&before=m1",
+ ]);
expect(JSON.parse(seen[0]!.body)).toEqual({ threadId: "t1", text: "cloud: hi", attachments: [{ path: "/data/attachments/aa11-bb22.png" }] });
expect(JSON.parse(seen[1]!.body)).toEqual({ threadId: "t1" });
});
diff --git a/server/places/place-proxy.ts b/server/places/place-proxy.ts
index 5e9c1aad8f..8f6beb53df 100644
--- a/server/places/place-proxy.ts
+++ b/server/places/place-proxy.ts
@@ -65,7 +65,7 @@ const ROUTES: ReadonlyArray<readonly [string, RegExp]> = [
["POST", /^\/api\/threads\/[\w-]+\/messages\/[\w-]+\/reactions$/],
["GET", /^\/api\/threads\/[\w-]+\/job$/],
["POST", /^\/api\/threads\/[\w-]+\/job\/[\w-]+\/stop$/],
- ["GET", /^\/api\/threads\/[\w-]+\/messages$/],
+ ["GET", /^\/api\/threads\/[\w-]+\/(?:messages|goals)$/],
["GET", /^\/api\/threads\/[\w-]+\/messages\/[\w-]+\/(?:image|file|tool)$/],
// A file a message names: its bytes, a folder's list, or a link a <video> or <audio> element can play (`?media=`).
["POST", /^\/api\/threads\/[\w-]+\/messages\/[\w-]+\/file$/],
diff --git a/server/routes/threads-page-leaf.test.ts b/server/routes/threads-page-leaf.test.ts
index 4643084130..0bb30fbfa4 100644
--- a/server/routes/threads-page-leaf.test.ts
+++ b/server/routes/threads-page-leaf.test.ts
@@ -3,6 +3,7 @@ import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { SEES_EVERYTHING, VisibleSet } from "../bot-visibility.ts";
import { DATA_DIR } from "../config.ts";
import type { ModelSelection } from "../contracts.ts";
import { json, readBody } from "../harness/http.ts";
@@ -21,8 +22,8 @@ afterEach(async () => {
await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));
});
-async function serve(store: Store) {
- const deps = { store, defaultPage: 50, pageSize, ...messagePages(store), viewerFor: () => ({}), visibleTo: () => ({ bot: () => true, group: () => true }), workspaceAccess: () => null,
+async function serve(store: Store, visible = new VisibleSet(store.bots, store.groups, SEES_EVERYTHING)) {
+ const deps = { store, defaultPage: 50, pageSize, ...messagePages(store), viewerFor: () => ({}), visibleTo: () => visible, workspaceAccess: () => null,
desktopMutationToken: () => undefined, companionMutationToken: () => undefined, cliOwnerToken: () => undefined } as unknown as ThreadRouteDeps;
const routes = [createThreadRoutes(deps)];
const server = createServer(async (req, res) => {
@@ -36,7 +37,7 @@ async function serve(store: Store) {
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
return async (path: string) => {
const res = await fetch(`${base}${path}`);
- return { status: res.status, body: await res.json() as { messages: Message[]; hasMore: boolean; activeLeafId: string | null } };
+ return { status: res.status, body: await res.json() as { messages: Message[]; hasMore: boolean; activeLeafId: string | null; nextBefore?: string | null } };
};
}
@@ -166,3 +167,60 @@ describe("GET /api/threads/:threadId/messages", () => {
}
});
});
+
+describe("GET /api/threads/:threadId/goals", () => {
+ it("pages goal cards newest first even when thousands of unrelated rows follow them", async () => {
+ const store = new Store(() => sonnet);
+ const bot = store.createBot({}, { seedMessages: false });
+ const { threadId } = bot;
+ const makeGoal = (id: string, status: "working" | "completed"): Message => row(id, {
+ kind: "goal.run", role: "bot", at: 10,
+ goalRun: { runId: id, goal: id, status, startedAt: 10, turnCount: 1, maxTurns: 20, coordinatorBotId: bot.id, coordinatorName: bot.name },
+ });
+ const older = makeGoal("m1", "completed");
+ const latest = makeGoal("m2", "working");
+ const tail = Array.from({ length: 2_400 }, (_, index) => row(`m${index + 3}`, { parentId: null }));
+ mdb.importThread(threadId, [latest, older, ...tail], tail.at(-1)!.id);
+ const otherThread = store.createGroup("Room", [bot.id]).threadId;
+ const otherGoal = makeGoal("m9999", "completed");
+ mdb.insertMessage(otherThread, otherGoal);
+ const emptyThread = store.createBot({}, { seedMessages: false }).threadId;
+ const get = await serve(store);
+ const route = `/api/threads/${threadId}/goals`;
+ const readTranscript = vi.spyOn(store, "messagesFor");
+ const readTail = vi.spyOn(store, "messagesTail");
+ try {
+ expect(await get(`${route}?limit=1`)).toEqual({ status: 200, body: { messages: [latest], nextBefore: latest.id } });
+ expect(await get(`${route}?before=${latest.id}&limit=1`)).toEqual({ status: 200, body: { messages: [older], nextBefore: null } });
+ expect(await get(`/api/threads/${otherThread}/goals`)).toEqual({ status: 200, body: { messages: [otherGoal], nextBefore: null } });
+ expect(await get(`/api/threads/${emptyThread}/goals?limit=1`)).toEqual({ status: 200, body: { messages: [], nextBefore: null } });
+ expect((await get(`${route}?before=${otherGoal.id}`)).status).toBe(404);
+ expect((await get(`${route}?before=${tail[0]!.id}`)).status).toBe(404);
+ expect((await get(`${route}?limit=0`)).status).toBe(400);
+ expect(readTranscript).not.toHaveBeenCalled();
+ expect(readTail).not.toHaveBeenCalled();
+ } finally {
+ readTranscript.mockRestore();
+ readTail.mockRestore();
+ }
+ });
+
+ it("hides a private conversation from another member and a team admin before reading goals", async () => {
+ const store = new Store(() => sonnet);
+ const { threadId } = store.createBot({}, { seedMessages: false });
+ const goal = row("m1", { kind: "goal.run", role: "bot", text: "Private goal" });
+ mdb.insertMessage(threadId, goal);
+ const audience = { of: (id: string) => id === threadId ? "member:alice" as const : undefined, person: "alice" };
+ const alice = new VisibleSet(store.bots, store.groups, { kind: "member", email: "[email protected]" }, undefined, audience);
+ const aliceGet = await serve(store, alice);
+ expect((await aliceGet(`/api/threads/${threadId}/goals`)).body.messages).toEqual([goal]);
+
+ for (const kind of ["member", "all"] as const) {
+ const bob = new VisibleSet(store.bots, store.groups, { kind, email: "[email protected]" }, undefined, { ...audience, person: "bob" });
+ const get = await serve(store, bob);
+ const expected = { status: 404, body: { error: "no such conversation" } };
+ expect(await get(`/api/threads/${threadId}/goals?limit=0&before=m1`)).toEqual(expected);
+ expect(await get("/api/threads/missing-thread/goals")).toEqual(expected);
+ }
+ });
+});
diff --git a/server/routes/threads.ts b/server/routes/threads.ts
index e863863fb2..e56f46b68f 100644
--- a/server/routes/threads.ts
+++ b/server/routes/threads.ts
@@ -19,6 +19,7 @@ import type { Coordinator } from "../coordinator.ts";
import type { WorkspaceAccess } from "../enterprise.ts";
import type { GroupUsageReader } from "../group-thread-usage.ts";
import { readMessage, searchMessagesAsync } from "../message-db.ts";
+import { threadGoalPage } from "../message-db-goals.ts";
import { cappedMediaRange, MessageMediaLinks, STREAMABLE_MEDIA_MIMES } from "../message-media-links.ts";
import {
canOpenOutsideWorkspaceMessageFile, listMessageFolder, MESSAGE_FILE_DOWNLOAD_MAX_BYTES, MESSAGE_FILE_MAX_BYTES, messageAttachmentName, messageFileDisposition, messageFileDownloadName, messageFolderEntryName,
@@ -150,6 +151,20 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {
return json(res, 200, { bot: shownBot(bot, visible, limit) });
}
+ m = path.match(/^\/api\/threads\/([\w-]+)\/goals$/);
+ if (m && method === "GET") {
+ const threadId = m[1]!;
+ res.setHeader("cache-control", "private, no-store");
+ if (!visible.thread(threadId) || (!store.botByThread(threadId) && !store.groupByThread(threadId))) {
+ return json(res, 404, { error: "no such conversation" });
+ }
+ if (backgroundWhileAsleep(path, req.headers)) return answerAsleep(res, json);
+ const limit = pageSize(url.searchParams.get("limit"));
+ if (limit === null || limit === 0) return json(res, 400, { error: "limit must be a positive whole number" });
+ const page = threadGoalPage(threadId, limit ?? DEFAULT_PAGE, url.searchParams.get("before"));
+ return page ? json(res, 200, page) : json(res, 404, { error: "no such goal" });
+ }
+
m = path.match(/^\/api\/threads\/([\w-]+)\/messages$/);
if (m && method === "GET") {
const threadId = m[1];
diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsx
index e65ab65517..f6658a054d 100644
--- a/src/components/ChatView.tsx
+++ b/src/components/ChatView.tsx
@@ -133,7 +133,7 @@ import { pendingApprovals } from "./PendingApproval";
import { TranscriptAnnouncer } from "./TranscriptAnnouncer";
import { JumpToLatestButton } from "./JumpToLatestButton";
import { BOT_BUBBLE_FINISH, isBotTextRow, joinedCorners, needsStamp, quietRow, simpleRowLayout, SIMPLE_BOT_BUBBLE, SIMPLE_BUBBLE_MAX, SIMPLE_BUBBLE_TEXT, SIMPLE_STACKED, SIMPLE_USER_BUBBLE, type BubbleJoin } from "./chat-bubble";
-
+import { ThreadGoals } from "./ThreadGoals";
const USER_COLLAPSE_CHARS = 600;
const USER_COLLAPSE_LINES = 8;
@@ -1044,7 +1044,7 @@ export const ChatView = memo(function ChatView({ bot: profile, inForkPanel = fal
<ChatNotice notice={state.notice} />
<UnreadContextOverlay messages={chatMessages} windowedMessages={windowedMessages} unreadMessageId={unreadDivider.messageId} scrollRef={scrollRef} visitKey={`${bot.id}:${bot.threadId}:${openedAt}`} onJump={(messageId) => dispatch({ type: "focusMessage", threadId: bot.threadId, messageId })} />
<PinnedSignInSlot cards={pinnedSignIns} />
-
+ <ThreadGoals key={bot.threadId} thread={bot} botId={bot.id} canSwitchVersion={canWrite === true} inForkPanel={inForkPanel} />
</GlassBar>
<div
diff --git a/src/components/GoalRunCard.tsx b/src/components/GoalRunCard.tsx
index 975c9ed03f..a979972793 100644
--- a/src/components/GoalRunCard.tsx
+++ b/src/components/GoalRunCard.tsx
@@ -30,6 +30,14 @@ const COPY = {
{ label: LocaleKey; tone: string; border: string }
>;
+export function goalRunStatus(run: GroupGoalRunCardData): string {
+ return t(COPY[run.status].label);
+}
+
+export function goalRunTurnCount(run: GroupGoalRunCardData): string {
+ return run.turnCount === 1 ? t("routines.goal.turnsOne") : t("routines.goal.turnsMany", { count: run.turnCount });
+}
+
function compact(value: string | undefined, limit: number): string {
const clean = value?.replace(/\s+/g, " ").trim() ?? "";
return clean.length > limit ? `${clean.slice(0, limit - 1).trimEnd()}…` : clean;
@@ -39,7 +47,7 @@ function StatusIcon({ status }: { status: GroupGoalRunCardData["status"] }) {
const className = "size-4 shrink-0";
switch (status) {
case "working":
- return <Loader2 aria-hidden="true" className={cn(className, "animate-spin text-accent")} />;
+ return <Loader2 aria-hidden="true" className={cn(className, "animate-spin text-accent motion-reduce:animate-none")} />;
case "completed":
return <CheckCircle2 aria-hidden="true" className={cn(className, "text-success")} />;
case "needs-input":
@@ -55,6 +63,29 @@ function StatusIcon({ status }: { status: GroupGoalRunCardData["status"] }) {
}
}
+function goalRunDisplay(run: GroupGoalRunCardData) {
+ return {
+ goal: compact(run.goal, 180) || t("routines.goal.groupGoal"),
+ detail: compact(routineLineText(run.detailCode, run.detail ?? "", run.detailParams), DETAIL_LIMIT),
+ status: goalRunStatus(run),
+ turns: run.status === "working"
+ ? t("routines.goal.turnOf", { turn: Math.min(run.turnCount + 1, run.maxTurns), max: run.maxTurns })
+ : goalRunTurnCount(run),
+ };
+}
+
+export function PinnedGoalSummary({ run }: { run: GroupGoalRunCardData }) {
+ const { goal, detail, status, turns } = goalRunDisplay(run);
+ return <>
+ <StatusIcon status={run.status} />
+ <div className="min-w-0 flex-1">
+ <h2 dir="auto" title={run.goal} className="truncate text-[13px] font-medium text-ink">{goal}</h2>
+ <p aria-live="polite" className="truncate text-[12px] tabular-nums text-ink-secondary">{status} · {turns}</p>
+ {detail && <p dir="auto" title={detail} className="truncate text-[12px] text-ink-secondary">{detail}</p>}
+ </div>
+ </>;
+}
+
/** `solo` is a one-on-one chat's run, where the bot works alone; `onStop` ends a working run from the card. */
export function GoalRunCard({ message, solo = false, onStop }: { message: Message; solo?: boolean; onStop?: () => void }) {
const run = message.goalRun;
@@ -68,15 +99,11 @@ export function GoalRunCard({ message, solo = false, onStop }: { message: Messag
}
const copy = COPY[run.status];
- const goal = compact(run.goal, 180);
- const detail = compact(routineLineText(run.detailCode, run.detail ?? "", run.detailParams), DETAIL_LIMIT);
- const turns = run.status === "working"
- ? t("routines.goal.turnOf", { turn: Math.min(run.turnCount + 1, run.maxTurns), max: run.maxTurns })
- : run.turnCount === 1 ? t("routines.goal.turnsOne") : t("routines.goal.turnsMany", { count: run.turnCount });
+ const { goal, detail, status, turns } = goalRunDisplay(run);
return (
<section
- aria-label={t("routines.goal.runLabel", { status: t(copy.label) })}
+ aria-label={t("routines.goal.runLabel", { status })}
className={cn("w-full max-w-[680px] rounded-2xl border bg-card px-3.5 py-3 shadow-sm", copy.border)}
>
<div className="flex items-start gap-3">
@@ -85,9 +112,9 @@ export function GoalRunCard({ message, solo = false, onStop }: { message: Messag
</div>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
- <h3 className="truncate text-[14px] font-semibold text-ink">{goal || t("routines.goal.groupGoal")}</h3>
+ <h3 className="truncate text-[14px] font-semibold text-ink">{goal}</h3>
<span aria-live="polite" className={cn("text-[12px] font-medium", copy.tone)}>
- {t(copy.label)}
+ {status}
</span>
</div>
{detail && <p className="mt-1 line-clamp-2 text-[13px] leading-relaxed text-ink-secondary">{detail}</p>}
diff --git a/src/components/GroupView.tsx b/src/components/GroupView.tsx
index c6032fad6d..54fd531bca 100644
--- a/src/components/GroupView.tsx
+++ b/src/components/GroupView.tsx
@@ -47,6 +47,7 @@ import { SignInRequestCard } from "./SignInRequestCard";
import { isPinnedSignIn, NO_PINNED_SIGN_INS, PinnedSignInSlot } from "./PinnedSignInSlot";
import { hasRoutineExecutionTask, RoutineRunCard } from "./RoutineRunCard";
import { GoalRunCard } from "./GoalRunCard";
+import { ThreadGoals } from "./ThreadGoals";
import { OptionCard } from "./OptionCard";
import { GroupCallOverlay } from "./GroupCallView";
@@ -491,6 +492,7 @@ export function GroupView({ group, inForkPanel = false, bare = false }: { group:
</div>
)}
<PinnedSignInSlot cards={pinnedSignIns} />
+ <ThreadGoals key={group.threadId} thread={group} inForkPanel={inForkPanel} />
</GlassBar>
diff --git a/src/components/ThreadGoals.dom.test.ts b/src/components/ThreadGoals.dom.test.ts
new file mode 100644
index 0000000000..35a834dcd5
--- /dev/null
+++ b/src/components/ThreadGoals.dom.test.ts
@@ -0,0 +1,171 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { publishLiveFrame } from "@/lib/live-events";
+import { ApiError } from "@/state/api";
+import type { Action, AppState, Bot, Group, Message } from "@/state/store";
+import { StoreRefContext } from "@/state/store-ref-context";
+import { ThreadGoals } from "./ThreadGoals";
+
+const fixture = vi.hoisted(() => ({ api: vi.fn(), viewer: "[email protected]" }));
+vi.mock("@/state/store", async (original) => ({
+ ...await original<typeof import("@/state/store")>(),
+ api: (...args: unknown[]) => fixture.api(...args),
+}));
+vi.mock("@/lib/default-bot", () => ({ useViewerEmail: () => fixture.viewer }));
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+let root: Root | undefined;
+beforeEach(() => {
+ localStorage.clear();
+ fixture.api.mockReset();
+ fixture.viewer = "[email protected]";
+});
+afterEach(() => {
+ act(() => root?.unmount());
+ root = undefined;
+ document.body.replaceChildren();
+});
+
+const row = (id: string, at: number, parentId?: string): Message => ({ id, at, parentId, role: "bot", kind: "text", text: id });
+const goal = (id: string, at: number, status: NonNullable<Message["goalRun"]>["status"], parentId?: string): Message => ({
+ ...row(id, at, parentId),
+ kind: "goal.run",
+ goalRun: { runId: id, goal: id, status, turnCount: 2, maxTurns: 10, coordinatorBotId: "bot", coordinatorName: "Scout", startedAt: at,
+ ...(status !== "working" ? { finishedAt: at + 50 } : {}) },
+});
+const button = (name: string) => [...document.querySelectorAll("button")].find((element) => (element.getAttribute("aria-label") ?? element.textContent) === name)!;
+const click = (name: string) => act(async () => { button(name).click(); });
+const latestTitle = () => document.querySelector("[aria-label=Goals] h2")?.textContent;
+const listedGoals = () => [...document.querySelectorAll("[role=dialog] li h3")].map((heading) => heading.textContent);
+const cursor = (path: string) => new URL(path, "http://test").searchParams.get("before");
+
+async function mount(thread: Pick<Bot, "threadId" | "messages" | "hasMore"> & { activeLeafId?: string }, botId?: string, canSwitchVersion = false) {
+ const state = { bots: botId ? [thread as Bot] : [], groups: botId ? [] : [thread as Group], transcriptGeneration: { [thread.threadId]: 3 } } as AppState;
+ const dispatch = vi.fn((action: Action) => {
+ if (action.type === "olderMessages") thread.messages = [...action.messages, ...thread.messages];
+ });
+ const mounted = root ??= createRoot(document.body.appendChild(document.createElement("div")));
+ const render = () => act(async () => mounted.render(createElement(StoreRefContext.Provider, {
+ value: { dispatch, state: () => state },
+ }, createElement(ThreadGoals, { key: thread.threadId, thread, botId, canSwitchVersion }))));
+ await render();
+ return { dispatch, render };
+}
+
+it("pins a far-back goal before the panel opens and pages only goals until the reader requests a jump", async () => {
+ const latest = goal("Newest goal", 30, "working");
+ const oldest = goal("Oldest goal", 10, "paused");
+ const pages: Record<string, { messages: Message[]; hasMore: boolean }> = {
+ tail: { messages: [row("p2", 4_000)], hasMore: true },
+ p2: { messages: [row("p1", 20), latest], hasMore: true },
+ p1: { messages: [oldest], hasMore: false },
+ };
+ fixture.api.mockImplementation(async (path: string) => {
+ if (path === "/api/threads/room-thread/goals?limit=1") return { messages: [latest], nextBefore: latest.id };
+ if (path === "/api/threads/room-thread/goals?before=Newest+goal") return { messages: [oldest], nextBefore: null };
+ return pages[cursor(path)!];
+ });
+ const thread = { threadId: "room-thread", messages: [row("tail", 5_000)], hasMore: true };
+ const { dispatch } = await mount(thread);
+ expect(latestTitle()).toBe("Newest goal");
+ expect(document.querySelector("[role=dialog]")).toBeNull();
+ expect(fixture.api).toHaveBeenCalledExactlyOnceWith("/api/threads/room-thread/goals?limit=1", expect.objectContaining({ background: true }));
+ expect(thread.messages.map((message) => message.id)).toEqual(["tail"]);
+
+ await click("Goals");
+ expect(fixture.api.mock.calls.map(([path]) => path)).toEqual([
+ "/api/threads/room-thread/goals?limit=1", "/api/threads/room-thread/goals?before=Newest+goal",
+ ]);
+ expect(latestTitle()).toBe("Newest goal");
+ expect(listedGoals()).toEqual(["Newest goal", "Oldest goal"]);
+ expect(button("Dismiss goal card for Newest goal")).toBeUndefined();
+
+ const completed = { ...latest, goalRun: { ...latest.goalRun!, status: "completed" as const, finishedAt: 75 } };
+ await act(async () => publishLiveFrame({ kind: "message.patch", threadId: thread.threadId, message: completed }));
+ expect(document.querySelector("[aria-label=Goals]")?.textContent).toContain("Completed");
+ expect(document.querySelector("[role=dialog] li")?.textContent).toMatch(/Completed · 2 turns.*Started .*Ended /);
+ expect(document.querySelector("[role=dialog] li:last-child")?.textContent).toContain("Paused");
+
+ await click("Jump to message for Oldest goal");
+ expect(fixture.api.mock.calls.slice(2).map(([path]) => cursor(path))).toEqual(["tail", "p2", "p1"]);
+ expect(dispatch.mock.calls.map(([action]) => action.type)).toEqual(["olderMessages", "focusMessage"]);
+ expect(dispatch).toHaveBeenLastCalledWith({ type: "focusMessage", threadId: "room-thread", messageId: "Oldest goal" });
+ expect(document.querySelector("[role=dialog]")).toBeNull();
+});
+
+it("does no more history work for a long thread without goals", async () => {
+ fixture.api.mockResolvedValue({ messages: [], nextBefore: null });
+ await mount({ threadId: "room-thread", messages: [row("tail", 5_000)], hasMore: true });
+ expect(fixture.api).toHaveBeenCalledExactlyOnceWith("/api/threads/room-thread/goals?limit=1", expect.anything());
+ expect(button("Goals")).toBeUndefined();
+});
+
+it("dismisses each inactive panel entry for this viewer and thread while retaining all messages", async () => {
+ const messages = [goal("Finished goal", 5, "completed"), goal("Working goal", 10, "working"), goal("Paused goal", 15, "paused")];
+ const thread = { threadId: "thread", messages };
+ const { dispatch } = await mount(thread);
+ await click("Goals");
+ expect(listedGoals()).toEqual(["Paused goal", "Working goal", "Finished goal"]);
+ expect(button("Dismiss goal card for Working goal")).toBeUndefined();
+ await click("Dismiss goal card for Finished goal");
+ expect(listedGoals()).toEqual(["Paused goal", "Working goal"]);
+ expect(latestTitle()).toBe("Paused goal");
+ await click("Dismiss goal card for Paused goal");
+ expect(listedGoals()).toEqual(["Working goal"]);
+ expect(latestTitle()).toBeUndefined();
+ expect(dispatch).not.toHaveBeenCalled();
+ expect(fixture.api).not.toHaveBeenCalled();
+ expect(thread.messages).toBe(messages);
+
+ await mount({ ...thread, threadId: "another-thread" });
+ await click("Goals");
+ expect(listedGoals()).toEqual(["Paused goal", "Working goal", "Finished goal"]);
+ fixture.viewer = "[email protected]";
+ const { render } = await mount(thread);
+ await click("Goals");
+ expect(listedGoals()).toEqual(["Paused goal", "Working goal", "Finished goal"]);
+ fixture.viewer = "[email protected]";
+ await render();
+ expect(listedGoals()).toEqual(["Working goal"]);
+ expect(latestTitle()).toBeUndefined();
+ await click("Restore dismissed goals");
+ expect(listedGoals()).toEqual(["Paused goal", "Working goal", "Finished goal"]);
+ expect(latestTitle()).toBe("Paused goal");
+});
+
+it("honors a refused history read and shows a different version's card without changing a read-only chat", async () => {
+ const working = goal("Current goal", 20, "working");
+ const other = goal("Other version", 10, "stopped");
+ const thread = { threadId: "thread", messages: [other, working], activeLeafId: working.id, hasMore: true };
+ fixture.api.mockRejectedValue(new ApiError("no such conversation", 404));
+ const { dispatch } = await mount(thread, "bot");
+ await click("Goals");
+ expect(document.querySelector("[role=alert]")?.textContent).toBe("Couldn't load earlier goals.");
+ expect(fixture.api).toHaveBeenCalledOnce();
+ await click("Jump to message for Other version");
+ expect(document.querySelector("[role=dialog] [aria-label='Goal run: Stopped']")).not.toBeNull();
+ expect(fixture.api).toHaveBeenCalledOnce();
+ expect(dispatch).not.toHaveBeenCalled();
+ expect(thread.activeLeafId).toBe(working.id);
+});
+
+it("waits for the existing branch permission check before focusing a goal on another version", async () => {
+ const working = goal("Current goal", 20, "working");
+ const other = goal("Other version", 10, "stopped");
+ const thread = { threadId: "thread", messages: [other, working], activeLeafId: working.id };
+ fixture.api.mockRejectedValueOnce(new ApiError("view only", 403)).mockResolvedValueOnce({ activeLeafId: other.id });
+ const { dispatch } = await mount(thread, "bot", true);
+ await click("Goals");
+ await click("Jump to message for Other version");
+ expect(fixture.api).toHaveBeenCalledWith("/api/bots/bot/active-branch", expect.objectContaining({
+ method: "POST", body: JSON.stringify({ messageId: other.id, threadId: thread.threadId }),
+ }));
+ expect(dispatch).not.toHaveBeenCalled();
+ expect(document.querySelector("[role=alert]")?.textContent).toContain("Couldn't open that goal message.");
+
+ await click("Jump to message for Other version");
+ expect(dispatch.mock.calls.map(([action]) => action.type)).toEqual(["threadActive", "focusMessage"]);
+ expect(dispatch).toHaveBeenLastCalledWith({ type: "focusMessage", threadId: "thread", messageId: other.id });
+});
diff --git a/src/components/ThreadGoals.tsx b/src/components/ThreadGoals.tsx
new file mode 100644
index 0000000000..7a96b2c5f3
--- /dev/null
+++ b/src/components/ThreadGoals.tsx
@@ -0,0 +1,282 @@
+import { useEffect, useId, useMemo, useRef, useState } from "react";
+import { createPortal } from "react-dom";
+import { X } from "lucide-react";
+import { useModalDialog } from "@/hooks/use-modal-dialog";
+import { cn } from "@/lib/cn";
+import { useViewerEmail } from "@/lib/default-bot";
+import { loadThroughMessage } from "@/lib/focus-message";
+import { intlLocale, t } from "@/lib/i18n";
+import { listenLiveFrames } from "@/lib/live-events";
+import { useActiveLocale } from "@/lib/use-active-locale";
+import { ApiError } from "@/state/api";
+import { visibleMessages } from "@/state/snapshot-navigation";
+import { api, type Bot, type Message } from "@/state/store";
+import { useStoreRef } from "@/state/store-ref";
+import { GoalRunCard, PinnedGoalSummary, goalRunStatus, goalRunTurnCount } from "./GoalRunCard";
+
+type GoalMessage = Message & { kind: "goal.run" };
+type Thread = Pick<Bot, "threadId" | "messages" | "hasMore">;
+type GoalPage = { messages: Message[]; nextBefore: string | null };
+type History = { goals: GoalMessage[]; before?: string | null; failed?: boolean };
+const emptyHistory: History = { goals: [] };
+const noDismissals = new Set<string>();
+
+function readDismissals(key: string): ReadonlySet<string> {
+ try {
+ const saved: unknown = JSON.parse(localStorage.getItem(key) ?? "null");
+ if (Array.isArray(saved)) return new Set(saved.filter((id): id is string => typeof id === "string"));
+ } catch {}
+ return noDismissals;
+}
+
+function isInactiveGoal(message: GoalMessage): boolean {
+ return Boolean(message.goalRun && message.goalRun.status !== "working");
+}
+
+function isGoal(message: Message): message is GoalMessage {
+ return message.kind === "goal.run";
+}
+
+function goalTitle(message: GoalMessage): string {
+ return (message.goalRun?.goal ?? message.text)?.trim() || t("routines.goal.groupGoal");
+}
+
+function useGoalHistory({ threadId, messages, hasMore }: Thread, open: boolean) {
+ const [history, setHistory] = useState(emptyHistory);
+ const [readGeneration, setReadGeneration] = useState(0);
+ const [live, setLive] = useState<ReadonlyMap<string, GoalMessage>>(() => new Map());
+ const held = useMemo(() => messages.filter(isGoal), [messages]);
+ const { before, failed } = history;
+ const readPage = Boolean(hasMore && !failed && (before === undefined || (open && before !== null)));
+
+ useEffect(() => listenLiveFrames({
+ onFrame(frame) {
+ if ((frame.kind !== "message" && frame.kind !== "message.patch") || frame.threadId !== threadId) return;
+ const message = frame.message as Message;
+ if (isGoal(message)) setLive((current) => new Map(current).set(message.id, message));
+ },
+ onMissedFrames() {
+ setHistory(emptyHistory);
+ setLive(new Map());
+ setReadGeneration((generation) => generation + 1);
+ },
+ }), [threadId]);
+
+ useEffect(() => {
+ if (!readPage) return;
+ const controller = new AbortController();
+ const query = new URLSearchParams(open ? undefined : { limit: "1" });
+ if (before !== undefined && before !== null) query.set("before", before);
+ const path = `/api/threads/${encodeURIComponent(threadId)}/goals${query.size ? `?${query}` : ""}`;
+ void api<GoalPage>(path, { signal: controller.signal, background: !open }).then((page) => {
+ if (controller.signal.aborted) return;
+ if (!Array.isArray(page.messages) || (page.nextBefore !== null && (!page.nextBefore || page.nextBefore === before))) {
+ throw new Error("Invalid goal history page");
+ }
+ setHistory((current) => ({ goals: [...current.goals, ...page.messages.filter(isGoal)], before: page.nextBefore }));
+ }).catch((error: unknown) => {
+ if (controller.signal.aborted) return;
+ if (error instanceof ApiError && [401, 403, 404].includes(error.status)) {
+ setHistory({ goals: [], failed: true });
+ setLive(new Map());
+ } else {
+ setHistory((current) => ({ ...current, failed: true }));
+ }
+ });
+ return () => controller.abort();
+ }, [before, open, readGeneration, readPage, threadId]);
+
+ const goals = useMemo(() => {
+ const byId = new Map<string, GoalMessage>();
+ for (const message of held.toReversed()) byId.set(message.id, live.get(message.id) ?? message);
+ if (hasMore) {
+ for (const message of history.goals) if (!byId.has(message.id)) byId.set(message.id, live.get(message.id) ?? message);
+ for (const message of live.values()) if (!byId.has(message.id)) byId.set(message.id, message);
+ }
+ return [...byId.values()].sort((a, b) => {
+ const started = (b.goalRun?.startedAt ?? b.at) - (a.goalRun?.startedAt ?? a.at);
+ return started || b.at - a.at || Number(a.id < b.id) - Number(a.id > b.id);
+ });
+ }, [hasMore, held, history.goals, live]);
+ return { goals, loading: readPage, failed: Boolean(hasMore && failed), retry: () => setHistory((current) => ({ ...current, failed: false })) };
+}
+
+export function ThreadGoals({ thread, botId, canSwitchVersion, inForkPanel }: {
+ thread: Thread;
+ botId?: string;
+ canSwitchVersion?: boolean;
+ inForkPanel?: boolean;
+}) {
+ const [open, setOpen] = useState(false);
+ const { goals, loading, failed, retry } = useGoalHistory(thread, open);
+ const { threadId } = thread;
+ const store = useStoreRef();
+ const viewer = useViewerEmail();
+ useActiveLocale();
+ const panelId = useId();
+ const trigger = useRef<HTMLButtonElement>(null);
+ const latest = goals[0];
+ const storageKey = viewer === undefined ? null : `omb.dismissedGoals:${JSON.stringify([viewer, threadId])}`;
+ const [dismissals, setDismissals] = useState<{ key: string; ids: ReadonlySet<string> }>();
+ const saved = useMemo(() => storageKey === null ? noDismissals : readDismissals(storageKey), [storageKey]);
+ const dismissedIds = dismissals?.key === storageKey ? dismissals.ids : saved;
+ const isDismissed = (message: GoalMessage) => dismissedIds.has(message.id) && isInactiveGoal(message);
+ const shownGoals = goals.filter((message) => !isDismissed(message));
+ const pinned = latest && !isDismissed(latest) ? latest : undefined;
+ const rememberDismissals = (ids: ReadonlySet<string>) => {
+ if (storageKey === null) return;
+ setDismissals({ key: storageKey, ids });
+ try {
+ if (ids.size) localStorage.setItem(storageKey, JSON.stringify([...ids]));
+ else localStorage.removeItem(storageKey);
+ } catch {}
+ };
+ const dismiss = storageKey === null ? undefined : (message: GoalMessage) => {
+ if (isInactiveGoal(message)) rememberDismissals(new Set(dismissedIds).add(message.id));
+ };
+ const restore = shownGoals.length < goals.length ? () => rememberDismissals(noDismissals) : undefined;
+
+ const jump = async (message: GoalMessage, signal: AbortSignal): Promise<boolean> => {
+ const currentThread = () => {
+ const state = store.state();
+ return inForkPanel
+ ? state.forkPanel?.threadId === threadId ? state.forkPanel : undefined
+ : (botId ? state.bots : state.groups).find((owner) => owner.threadId === threadId);
+ };
+ const current = currentThread();
+ if (!current) throw new Error(t("chat.conversationGone"));
+ const generation = store.state().transcriptGeneration[threadId] ?? 0;
+ await loadThroughMessage(current, message.id, generation, store.dispatch, signal);
+ signal.throwIfAborted();
+ let loaded = currentThread();
+ if (loaded && "hasMore" in loaded && loaded.hasMore && loaded.messages[0]?.id !== current.messages[0]?.id && !loaded.messages.some((row) => row.id === message.id)) {
+ await loadThroughMessage(loaded, message.id, store.state().transcriptGeneration[threadId] ?? 0, store.dispatch, signal);
+ signal.throwIfAborted();
+ loaded = currentThread();
+ }
+ if (!loaded?.messages.some((row) => row.id === message.id)) throw new Error(t("chat.goals.jumpFailed"));
+ if (botId && "activeLeafId" in loaded && !visibleMessages(loaded).some((row) => row.id === message.id)) {
+ if (!canSwitchVersion || ("yourAccess" in loaded && loaded.yourAccess === "view")) return false;
+ const result = await api<{ activeLeafId: string }>(`/api/bots/${encodeURIComponent(botId)}/active-branch`, {
+ method: "POST",
+ body: JSON.stringify({ messageId: message.id, threadId }),
+ signal,
+ });
+ signal.throwIfAborted();
+ store.dispatch({ type: inForkPanel ? "forkPanelActive" : "threadActive", threadId, activeLeafId: result.activeLeafId });
+ }
+ store.dispatch({ type: "focusMessage", threadId, messageId: message.id });
+ return true;
+ };
+
+ if (!latest && !failed && !open) return null;
+ return (
+ <div className="px-4 pb-2">
+ <section aria-label={t("chat.goals.title")} className={cn("chat-column flex min-w-0 items-center gap-2", pinned && "rounded-xl border border-hairline bg-card px-3 py-1")}>
+ {pinned?.goalRun ? <PinnedGoalSummary run={pinned.goalRun} /> : pinned && (
+ <h2 dir="auto" title={pinned.text} className="min-w-0 flex-1 truncate text-[13px] font-medium text-ink">{goalTitle(pinned)}</h2>
+ )}
+ <button ref={trigger} type="button" aria-haspopup="dialog" aria-expanded={open} aria-controls={open ? panelId : undefined} className="ui-button ui-button-sm shrink-0" onClick={() => setOpen(true)}>{t("chat.goals.title")}</button>
+ {pinned && dismiss && isInactiveGoal(pinned) && (
+ <button type="button" className="ui-icon-button shrink-0" aria-label={t("chat.goals.dismiss")} title={t("chat.goals.dismiss")} onClick={() => { dismiss(pinned); trigger.current?.focus(); }}><X size={16} aria-hidden="true" /></button>
+ )}
+ </section>
+ {open && <GoalsPanel id={panelId} goals={shownGoals} loading={loading} failed={failed} retry={retry} dismiss={dismiss} restore={restore} onClose={() => setOpen(false)} onJump={jump} solo={Boolean(botId)} />}
+ </div>
+ );
+}
+
+function GoalsPanel({ id, goals, loading, failed, retry, dismiss, restore, onClose, onJump, solo }: {
+ id: string;
+ goals: GoalMessage[];
+ loading: boolean;
+ failed: boolean;
+ retry: () => void;
+ dismiss?: (message: GoalMessage) => void;
+ restore?: () => void;
+ onClose: () => void;
+ onJump: (message: GoalMessage, signal: AbortSignal) => Promise<boolean>;
+ solo: boolean;
+}) {
+ const dialog = useRef<HTMLDivElement>(null);
+ const request = useRef<AbortController | null>(null);
+ const [jumping, setJumping] = useState(false);
+ const [jumpFailed, setJumpFailed] = useState(false);
+ const [previewId, setPreviewId] = useState<string>();
+ const preview = goals.find((message) => message.id === previewId);
+ const close = () => {
+ request.current?.abort();
+ onClose();
+ };
+ useModalDialog(dialog, close);
+ useEffect(() => () => request.current?.abort(), []);
+ const locale = intlLocale();
+ const time = useMemo(() => new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeStyle: "short" }), [locale]);
+ const jump = async (message: GoalMessage) => {
+ if (request.current) return;
+ const controller = new AbortController();
+ request.current = controller;
+ dialog.current?.focus();
+ setJumping(true);
+ setJumpFailed(false);
+ setPreviewId(undefined);
+ try {
+ if (await onJump(message, controller.signal)) close();
+ else if (!controller.signal.aborted) setPreviewId(message.id);
+ } catch {
+ if (!controller.signal.aborted) setJumpFailed(true);
+ } finally {
+ request.current = null;
+ if (!controller.signal.aborted) setJumping(false);
+ }
+ };
+
+ return createPortal(
+ <div className="ui-scrim fixed inset-0 z-[60] flex items-center justify-center p-4" onMouseDown={(event) => { if (event.target === event.currentTarget) close(); }}>
+ <div ref={dialog} role="dialog" aria-modal="true" aria-labelledby={`${id}-title`} id={id} tabIndex={-1} className="ui-modal flex max-h-[min(40rem,calc(100dvh-2rem))] w-full max-w-lg flex-col text-ink">
+ <header className="flex items-center justify-between gap-2 px-4 py-3">
+ <h2 id={`${id}-title`} className="text-[17px] font-semibold">{t("chat.goals.title")}</h2>
+ <button type="button" className="ui-icon-button shrink-0" aria-label={t("common.close")} onClick={close}><X size={16} aria-hidden="true" /></button>
+ </header>
+ <div className="min-h-0 overflow-y-auto overscroll-contain px-4 pb-4">
+ {restore && <button type="button" className="ui-button ui-button-sm mb-2" onClick={() => { restore(); dialog.current?.focus({ preventScroll: true }); }}>{t("chat.goals.restoreDismissed")}</button>}
+ {jumping && <p role="status" className="mb-2 text-[13px] text-ink-secondary">{t("chat.goals.opening")}</p>}
+ {jumpFailed && <p role="alert" className="mb-2 text-[13px] text-danger">{t("chat.goals.jumpFailed")}</p>}
+ {preview && <div className="mb-3 space-y-2">
+ <p role="status" className="text-[13px] text-ink-secondary">{t("chat.goals.otherVersion")}</p>
+ <GoalRunCard message={preview} solo={solo} />
+ </div>}
+ <ol className="divide-y divide-hairline" aria-busy={loading || undefined}>
+ {goals.map((message) => {
+ const run = message.goalRun;
+ const title = goalTitle(message);
+ return <li key={message.id} className="flex flex-wrap items-center justify-between gap-2 py-3">
+ <div className="min-w-0 flex-1 basis-48">
+ <h3 dir="auto" title={title} className="truncate text-[13px] font-medium">{title}</h3>
+ {run && <>
+ <p className="text-[12px] tabular-nums text-ink-secondary">{goalRunStatus(run)} · {goalRunTurnCount(run)}</p>
+ <p className="text-[12px] text-ink-secondary">{t("chat.goals.started", { time: time.format(run.startedAt) })}</p>
+ {run.finishedAt !== undefined && <p className="text-[12px] text-ink-secondary">{t("chat.goals.ended", { time: time.format(run.finishedAt) })}</p>}
+ </>}
+ </div>
+ <div className="flex items-center gap-1">
+ <button type="button" className="ui-button ui-button-sm" disabled={jumping} aria-label={t("chat.goals.jumpTo", { goal: title })} onClick={() => void jump(message)}>{t("chat.goals.jump")}</button>
+ {dismiss && isInactiveGoal(message) && (
+ <button type="button" className="ui-icon-button shrink-0" disabled={jumping} aria-label={t("chat.goals.dismissGoal", { goal: title })} title={t("chat.goals.dismiss")} onClick={() => { dismiss(message); dialog.current?.focus({ preventScroll: true }); }}><X size={16} aria-hidden="true" /></button>
+ )}
+ </div>
+ </li>;
+ })}
+ </ol>
+ {loading && <p role="status" className="py-2 text-[13px] text-ink-secondary">{t("chat.goals.loading")}</p>}
+ {failed && <div className="flex flex-wrap items-center gap-2 py-2 text-[13px]">
+ <p role="alert" className="text-ink-secondary">{t("chat.goals.loadFailed")}</p>
+ <button type="button" className="ui-button ui-button-sm" onClick={retry}>{t("common.tryAgain")}</button>
+ </div>}
+ {!loading && !failed && !goals.length && <p className="py-2 text-[13px] text-ink-secondary">{t(restore ? "chat.goals.allDismissed" : "chat.goals.empty")}</p>}
+ </div>
+ </div>
+ </div>,
+ document.body,
+ );
+}
diff --git a/src/lib/focus-message.ts b/src/lib/focus-message.ts
index 545e27ad72..17a3db9e67 100644
--- a/src/lib/focus-message.ts
+++ b/src/lib/focus-message.ts
@@ -7,11 +7,12 @@ import { t } from "@/lib/i18n";
const FLASH_CLASSES = ["ring-2", "ring-accent/70", "rounded-2xl", "transition-shadow"];
-async function loadThroughMessage(
+export async function loadThroughMessage(
owner: { threadId: string; messages: Message[]; hasMore?: boolean },
messageId: string,
generation: number,
dispatch: React.Dispatch<Action>,
+ signal?: AbortSignal,
): Promise<void> {
if (!owner.hasMore || owner.messages.some((message) => message.id === messageId)) return;
const older: Message[] = [];
@@ -21,13 +22,16 @@ async function loadThroughMessage(
let found = false;
while (before && hasMore && !found) {
const page = await api<{ messages?: Message[]; hasMore?: boolean }>(
- `/api/threads/${owner.threadId}/messages?limit=${MESSAGE_PAGE_SIZE}&before=${encodeURIComponent(before)}`,
+ `/api/threads/${encodeURIComponent(owner.threadId)}/messages?limit=${MESSAGE_PAGE_SIZE}&before=${encodeURIComponent(before)}`,
+ signal ? { signal } : undefined,
);
+ signal?.throwIfAborted();
const messages = page.messages ?? [];
older.unshift(...messages);
found = messages.some((message) => message.id === messageId);
- hasMore = Boolean(page.hasMore) && messages.length > 0;
- before = messages[0]?.id;
+ const next = messages[0]?.id;
+ hasMore = Boolean(page.hasMore) && next !== undefined && next !== before;
+ before = next;
}
if (older.length) dispatch({ type: "olderMessages", threadId: owner.threadId, generation, before: heldFrom, messages: older, hasMore });
}
diff --git a/src/locales/en.json b/src/locales/en.json
index cf38252006..09da601f2e 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -2912,6 +2912,21 @@
"chat.showEarlier": "Show earlier messages ({count} more)",
"chat.loadEarlier": "Load earlier messages",
"chat.loadingEarlier": "Loading earlier messages…",
+ "chat.goals.title": "Goals",
+ "chat.goals.dismiss": "Dismiss goal card",
+ "chat.goals.dismissGoal": "Dismiss goal card for {goal}",
+ "chat.goals.restoreDismissed": "Restore dismissed goals",
+ "chat.goals.allDismissed": "All goals are dismissed.",
+ "chat.goals.started": "Started {time}",
+ "chat.goals.ended": "Ended {time}",
+ "chat.goals.jump": "Jump to message",
+ "chat.goals.jumpTo": "Jump to message for {goal}",
+ "chat.goals.opening": "Opening goal message…",
+ "chat.goals.jumpFailed": "Couldn't open that goal message. Try again.",
+ "chat.goals.otherVersion": "This goal message is from another version of the conversation.",
+ "chat.goals.loading": "Loading earlier goals…",
+ "chat.goals.loadFailed": "Couldn't load earlier goals.",
+ "chat.goals.empty": "No goals in this conversation.",
"chat.showLater": "Show later messages ({count} more)",
"chat.provisioning": "Setting up this bot's desktop…",
"chat.computerStarting": "Starting {name}'s cloud desktop. The first start takes about a minute.",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 0dd3959498..2f075debad 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -2694,6 +2694,21 @@
"chat.showEarlier": "Ver mensagens anteriores (mais {count})",
"chat.loadEarlier": "Carregar mensagens anteriores",
"chat.loadingEarlier": "Carregando mensagens anteriores…",
+ "chat.goals.title": "Objetivos",
+ "chat.goals.dismiss": "Ocultar cartão do objetivo",
+ "chat.goals.dismissGoal": "Ocultar o cartão do objetivo “{goal}”",
+ "chat.goals.restoreDismissed": "Restaurar objetivos ocultos",
+ "chat.goals.allDismissed": "Todos os objetivos estão ocultos.",
+ "chat.goals.started": "Começou em {time}",
+ "chat.goals.ended": "Terminou em {time}",
+ "chat.goals.jump": "Ir para a mensagem",
+ "chat.goals.jumpTo": "Ir para a mensagem do objetivo “{goal}”",
+ "chat.goals.opening": "Abrindo a mensagem do objetivo…",
+ "chat.goals.jumpFailed": "Não foi possível abrir a mensagem do objetivo. Tente novamente.",
+ "chat.goals.otherVersion": "A mensagem deste objetivo está em outra versão da conversa.",
+ "chat.goals.loading": "Carregando objetivos anteriores…",
+ "chat.goals.loadFailed": "Não foi possível carregar os objetivos anteriores.",
+ "chat.goals.empty": "Nenhum objetivo nesta conversa.",
"chat.showLater": "Ver mensagens seguintes (mais {count})",
"chat.provisioning": "Preparando o desktop deste bot…",
"chat.computerStarting": "Iniciando o desktop na nuvem de {name}. Na primeira vez, isso leva cerca de um minuto.",