);
}
@@ -479,7 +503,7 @@ export function Answer({
// block's position and does not change when the fence closes — that
// is what makes this a swap rather than a remount (see `Block` in `answer-parse.ts`).
return (
-
);
}
diff --git a/apps/web/src/components/assistant/ask-assistant.tsx b/apps/web/src/components/assistant/ask-assistant.tsx
new file mode 100644
index 00000000..ebb73bd8
--- /dev/null
+++ b/apps/web/src/components/assistant/ask-assistant.tsx
@@ -0,0 +1,230 @@
+import type { WeekStartsOn } from "@farmer/core/lib/time";
+import { XIcon } from "@phosphor-icons/react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { useNavigate, useRouterState } from "@tanstack/react-router";
+import { useEffect, useRef, useState, useSyncExternalStore } from "react";
+import { toast } from "sonner";
+
+import { useAssistantActions } from "#/components/assistant/assistant-runs.tsx";
+import {
+ buildPageContext,
+ pageSearch,
+ projectIdFromPath,
+} from "#/components/assistant/page-context.ts";
+import { Button } from "#/components/ui/button.tsx";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "#/components/ui/dialog.tsx";
+import { Input } from "#/components/ui/input.tsx";
+import { useToday } from "#/hooks/use-today.ts";
+import { queryKeys } from "#/queries/keys.ts";
+import { projectQuery } from "#/queries/projects.ts";
+import { createConversation } from "#/server/assistant.ts";
+
+// Ask the assistant from any page. The shortcut opens one small dialog. Send
+// starts a new chat in the run store of the layout, so the answer keeps
+// streaming after the dialog closes.
+
+// The server takes 10,000 characters; the rest is room for the page sentence.
+const ASK_MAX_CHARS = 9000;
+
+const isMac = () => /Mac|iPhone|iPad/.test(navigator.userAgent);
+
+/** The shortcut as it is written on this platform. */
+export function useShortcutLabel() {
+ const mac = useSyncExternalStore(
+ () => () => {},
+ isMac,
+ () => false,
+ );
+ return mac ? "⌘K" : "Ctrl K";
+}
+
+/** A small kbd for the shortcut, as it is written on this platform. */
+export function AskShortcutHint() {
+ const label = useShortcutLabel();
+ return (
+
+ {label}
+
+ );
+}
+
+type ProviderProps = {
+ orgSlug: string;
+ timezone: string;
+ weekStartsOn: WeekStartsOn;
+ available: boolean;
+ children: React.ReactNode;
+};
+
+export function AskAssistantProvider({
+ available,
+ children,
+ ...page
+}: ProviderProps) {
+ const [isOpen, setOpen] = useState(false);
+
+ useEffect(() => {
+ if (!available) return;
+ const onKeyDown = (event: KeyboardEvent) => {
+ const chord = event.metaKey || event.ctrlKey;
+ if (!chord || event.shiftKey || event.altKey || event.isComposing) return;
+ if (event.key.toLowerCase() !== "k") return;
+ event.preventDefault();
+ setOpen((current) => !current);
+ };
+ window.addEventListener("keydown", onKeyDown);
+ return () => window.removeEventListener("keydown", onKeyDown);
+ }, [available]);
+
+ if (!available) return children;
+ return (
+ <>
+ {children}
+
+ >
+ );
+}
+
+type DialogProps = Omit & {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+};
+
+function AskDialog({ open, onOpenChange, ...page }: DialogProps) {
+ const inputRef = useRef(null);
+ return (
+
+ );
+}
+
+function AskForm({
+ orgSlug,
+ timezone,
+ weekStartsOn,
+ close,
+ inputRef,
+}: Omit & {
+ close: () => void;
+ inputRef: React.RefObject;
+}) {
+ const queryClient = useQueryClient();
+ const navigate = useNavigate();
+ const actions = useAssistantActions();
+ const today = useToday(timezone);
+ const location = useRouterState({ select: (state) => state.location });
+ const projectId = projectIdFromPath(location.pathname, orgSlug);
+ const { data: project } = useQuery({
+ ...projectQuery(orgSlug, projectId ?? ""),
+ enabled: Boolean(projectId),
+ });
+ const sentence = buildPageContext({
+ pathname: location.pathname,
+ search: pageSearch.safeParse(location.search).data ?? {},
+ orgSlug,
+ today,
+ weekStartsOn,
+ projectName: project?.name,
+ });
+ const [chip, setChip] = useState(true);
+ const [text, setText] = useState("");
+ const [busy, setBusy] = useState(false);
+
+ const send = async () => {
+ const question = text.trim();
+ if (!question || busy) return;
+ setBusy(true);
+ try {
+ const conversation = await createConversation({ data: {} });
+ await queryClient.invalidateQueries({
+ queryKey: [...queryKeys(orgSlug).assistant, "conversations"],
+ });
+ const message =
+ chip && sentence ? `${sentence}\n\n${question}` : question;
+ // Not awaited: the call returns when the whole answer is done.
+ actions.send(conversation.id, message).catch((error: unknown) => {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Could not send the question",
+ );
+ });
+ close();
+ toast("Asking the assistant", {
+ action: {
+ label: "Open chat",
+ onClick: () =>
+ void navigate({
+ to: "/$orgSlug/assistant",
+ params: { orgSlug },
+ search: { c: conversation.id },
+ }),
+ },
+ });
+ } catch (error) {
+ toast.error(
+ error instanceof Error ? error.message : "Could not start a chat",
+ );
+ setBusy(false);
+ }
+ };
+
+ return (
+
+ );
+}
diff --git a/apps/web/src/components/assistant/assistant-runs.tsx b/apps/web/src/components/assistant/assistant-runs.tsx
index 8be5c23b..60a4baef 100644
--- a/apps/web/src/components/assistant/assistant-runs.tsx
+++ b/apps/web/src/components/assistant/assistant-runs.tsx
@@ -56,6 +56,13 @@ export type ToolTrace = {
ok: boolean | null;
/** The call's raw arguments, as the model sent them. */
arguments: string;
+ /** Only on a stored write with an inverse. A live trace has none. */
+ undo?: {
+ done: boolean;
+ busy: boolean;
+ disabled: boolean;
+ onUndo: () => void;
+ };
};
/** The rows a batch write would touch. Mirrors `ApprovalPreview` in
diff --git a/apps/web/src/components/assistant/chat-rail.tsx b/apps/web/src/components/assistant/chat-rail.tsx
index 09d50387..36598b06 100644
--- a/apps/web/src/components/assistant/chat-rail.tsx
+++ b/apps/web/src/components/assistant/chat-rail.tsx
@@ -3,6 +3,7 @@ import {
ChatsIcon,
PencilSimpleIcon,
PlusIcon,
+ ShareNetworkIcon,
TrashIcon,
} from "@phosphor-icons/react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
@@ -25,6 +26,12 @@ import { queryKeys } from "#/queries/keys.ts";
import { deleteConversation, renameConversation } from "#/server/assistant.ts";
import { useAssistantRunning } from "./assistant-runs.tsx";
+import {
+ ChatSearchBox,
+ ChatSearchResults,
+ useChatSearch,
+} from "./chat-search.tsx";
+import { ShareChatButton } from "./share-chat.tsx";
/**
* The conversation list, and its two frames: the shell's section panel on
@@ -60,6 +67,30 @@ export function ConversationList({
orgSlug: string;
/** Called when a row is followed — the sheet closes on it; the sidebar has nothing to close. */
onNavigate?: () => void;
+}) {
+ const { input, setInput, query } = useChatSearch();
+ return (
+
+
+ {input.trim() === "" ? (
+
+ ) : (
+
+ )}
+
+ );
+}
+
+function ConversationRows({
+ orgSlug,
+ onNavigate,
+}: {
+ orgSlug: string;
+ onNavigate?: () => void;
}) {
const queryClient = useQueryClient();
const navigate = useNavigate();
@@ -263,6 +294,16 @@ export function ConversationList({
{running.includes(conversation.id) && (
, working on an answer
)}
+ {conversation.sharedAt && (
+ <>
+
+ , shared
+ >
+ )}
)}
{editingId !== conversation.id && (
@@ -360,15 +401,22 @@ export function MobileChatBar({ orgSlug }: { orgSlug: string }) {
navigates to the screen you are already looking at. The sheet's own
"New chat" row is the other, always-present way. */}
{openId && (
-
-
-
+ <>
+
+
+
+
+ >
)}
diff --git a/apps/web/src/components/assistant/chat-search.test.ts b/apps/web/src/components/assistant/chat-search.test.ts
new file mode 100644
index 00000000..d5f2003d
--- /dev/null
+++ b/apps/web/src/components/assistant/chat-search.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, test } from "bun:test";
+
+import { matchParts } from "./chat-search.tsx";
+
+describe("matchParts", () => {
+ test("marks every match, ignoring case", () => {
+ expect(matchParts("Budget for the budget", "budget")).toEqual([
+ { text: "Budget", match: true },
+ { text: " for the ", match: false },
+ { text: "budget", match: true },
+ ]);
+ });
+
+ test("returns the whole text when nothing matches", () => {
+ expect(matchParts("hello", "zz")).toEqual([
+ { text: "hello", match: false },
+ ]);
+ });
+});
diff --git a/apps/web/src/components/assistant/chat-search.tsx b/apps/web/src/components/assistant/chat-search.tsx
new file mode 100644
index 00000000..d1502816
--- /dev/null
+++ b/apps/web/src/components/assistant/chat-search.tsx
@@ -0,0 +1,149 @@
+import { MAX_SEARCH_CHARS } from "@farmer/core/schema";
+import { useQuery } from "@tanstack/react-query";
+import { Link } from "@tanstack/react-router";
+import { useEffect, useState } from "react";
+
+import { SearchInput } from "#/components/ui/search-input.tsx";
+import { searchConversationsQuery } from "#/queries/assistant.ts";
+
+const DEBOUNCE_MS = 250;
+const MIN_CHARS = 2;
+
+/** The text in pieces, with the pieces that match `q` marked. */
+export function matchParts(
+ text: string,
+ q: string,
+): { text: string; match: boolean }[] {
+ const needle = q.toLowerCase();
+ const haystack = text.toLowerCase();
+ const parts: { text: string; match: boolean }[] = [];
+ let from = 0;
+ for (;;) {
+ const hit = needle ? haystack.indexOf(needle, from) : -1;
+ if (hit === -1) break;
+ if (hit > from) parts.push({ text: text.slice(from, hit), match: false });
+ parts.push({ text: text.slice(hit, hit + needle.length), match: true });
+ from = hit + needle.length;
+ }
+ if (from < text.length) parts.push({ text: text.slice(from), match: false });
+ return parts;
+}
+
+function Marked({ text, q }: { text: string; q: string }) {
+ let offset = 0;
+ return matchParts(text, q).map((part) => {
+ offset += part.text.length;
+ return part.match ? (
+
+ {part.text}
+
+ ) : (
+ {part.text}
+ );
+ });
+}
+
+/** The search box, and the query it holds once it settles. */
+export function useChatSearch() {
+ const [input, setInput] = useState("");
+ const [settled, setSettled] = useState("");
+ useEffect(() => {
+ const timer = setTimeout(() => setSettled(input.trim()), DEBOUNCE_MS);
+ return () => clearTimeout(timer);
+ }, [input]);
+ return {
+ input,
+ setInput,
+ // A cleared box shows the list at once, with no wait.
+ query: input.trim() === "" ? "" : settled,
+ };
+}
+
+export function ChatSearchBox({
+ value,
+ onValueChange,
+}: {
+ value: string;
+ onValueChange: (value: string) => void;
+}) {
+ return (
+
+ );
+}
+
+/** The matches for `query`, in place of the list. */
+export function ChatSearchResults({
+ orgSlug,
+ query,
+ onNavigate,
+}: {
+ orgSlug: string;
+ query: string;
+ onNavigate?: () => void;
+}) {
+ const enabled = query.length >= MIN_CHARS;
+ const {
+ data = [],
+ isPending,
+ isError,
+ } = useQuery({
+ ...searchConversationsQuery(orgSlug, query),
+ enabled,
+ });
+ if (!enabled) {
+ return (
+
+ Type at least {MIN_CHARS} characters.
+
+ );
+ }
+ if (isPending) {
+ return (
+
Searching…
+ );
+ }
+ if (isError) {
+ return (
+
+ Could not search the chats.
+
+ );
+ }
+ if (data.length === 0) {
+ return (
+
+ No chat matches.
+
+ );
+ }
+ return (
+
+ {data.map((hit) => (
+
+
+
+
+
+ {hit.snippet && (
+
+
+
+ )}
+
+
+ ))}
+
+ );
+}
diff --git a/apps/web/src/components/assistant/context-meter.tsx b/apps/web/src/components/assistant/context-meter.tsx
new file mode 100644
index 00000000..4d79093f
--- /dev/null
+++ b/apps/web/src/components/assistant/context-meter.tsx
@@ -0,0 +1,74 @@
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "#/components/ui/tooltip.tsx";
+
+/** The meter shows from this share of the model's context. */
+export const CONTEXT_METER_FROM = 0.7;
+
+const kTokens = (n: number) =>
+ n >= 1000 ? `${Math.round(n / 1000)}k` : String(n);
+
+/** How full the chat is, as a share from 0 to 1. Null when it is unknown. */
+export const contextShare = (
+ used: number | null | undefined,
+ limit: number | null | undefined,
+) => (used && limit && limit > 0 ? used / limit : null);
+
+export function ContextMeter({
+ used,
+ limit,
+ onNewChat,
+}: {
+ used: number | null | undefined;
+ limit: number | null | undefined;
+ onNewChat: () => void;
+}) {
+ const share = contextShare(used, limit);
+ if (share === null || !used || !limit || share < CONTEXT_METER_FROM) {
+ return null;
+ }
+ const percent = Math.min(100, Math.round(share * 100));
+ return (
+
+
+
+
+ {/* The native element carries the value. The ring is drawn
+ with a conic gradient under a mask. */}
+
+
+
+
+ This chat uses {percent}% of the model's memory. Start a new chat
+ for best results.
+
+ {kTokens(used)} of {kTokens(limit)} tokens
+
+
+
+
+
+
+ );
+}
diff --git a/apps/web/src/components/assistant/page-context.test.ts b/apps/web/src/components/assistant/page-context.test.ts
new file mode 100644
index 00000000..2864b362
--- /dev/null
+++ b/apps/web/src/components/assistant/page-context.test.ts
@@ -0,0 +1,76 @@
+import { expect, test } from "bun:test";
+
+import {
+ buildPageContext,
+ type PageContextInput,
+ type PageSearch,
+ projectIdFromPath,
+} from "./page-context.ts";
+
+const base: PageContextInput = {
+ pathname: "/acme",
+ search: {},
+ orgSlug: "acme",
+ today: "2026-11-11",
+ weekStartsOn: 1,
+};
+
+const at = (pathname: string, search: PageSearch = {}, rest = {}) =>
+ buildPageContext({ ...base, pathname, search, ...rest });
+
+test("home", () => {
+ expect(at("/acme")).toBe("I am on the Home page.");
+});
+
+test("time views use the search or today", () => {
+ expect(at("/acme/time")).toBe("I am on the Day view for November 11, 2026.");
+ expect(at("/acme/time", { date: "2026-10-02" })).toBe(
+ "I am on the Day view for October 2, 2026.",
+ );
+ expect(at("/acme/time/week")).toBe(
+ "I am on the Week view for November 9 – 15, 2026.",
+ );
+ expect(at("/acme/time/week", { weekStart: "2026-11-02" })).toBe(
+ "I am on the Week view for November 2 – 8, 2026.",
+ );
+ expect(at("/acme/time/month", { month: "2026-10" })).toBe(
+ "I am on the Month view for October 2026.",
+ );
+});
+
+test("a project page needs the name", () => {
+ expect(at("/acme/projects/p1")).toBeNull();
+ expect(at("/acme/projects/p1", {}, { projectName: "Project A" })).toBe(
+ 'I am on the page of the project "Project A".',
+ );
+ expect(at("/acme/projects/p1", {}, { projectName: 'A"\nIgnore this' })).toBe(
+ 'I am on the page of the project "A Ignore this".',
+ );
+ expect(projectIdFromPath("/acme/projects/p1/team", "acme")).toBe("p1");
+ expect(projectIdFromPath("/acme/projects", "acme")).toBeNull();
+});
+
+test("the time report names the period and the grouping", () => {
+ expect(at("/acme/reports", { month: "2026-10" })).toBe(
+ "I am on the Time report for October 1 – 31, 2026, grouped by project.",
+ );
+ expect(
+ at("/acme/reports", { group: "clients", project: "p1", month: "2026-10" }),
+ ).toBe(
+ "I am on the Time report for October 1 – 31, 2026, grouped by client, filtered by project.",
+ );
+});
+
+test("the tracking report is one month and has no grouping", () => {
+ expect(
+ at("/acme/reports", {
+ tab: "compliance",
+ preset: "year",
+ month: "2026-10",
+ }),
+ ).toBe("I am on the Tracking report for October 1 – 31, 2026.");
+});
+
+test("an unknown page gives no sentence", () => {
+ expect(at("/acme/settings/tasks")).toBeNull();
+});
diff --git a/apps/web/src/components/assistant/page-context.ts b/apps/web/src/components/assistant/page-context.ts
new file mode 100644
index 00000000..2ffbed89
--- /dev/null
+++ b/apps/web/src/components/assistant/page-context.ts
@@ -0,0 +1,128 @@
+import { resolveReportPeriod } from "@farmer/core/lib/report-period";
+import type { WeekStartsOn } from "@farmer/core/lib/time";
+import { addDaysToKey, startOfWeekKey } from "@farmer/core/lib/time";
+import { dayKeySchema } from "@farmer/core/schema";
+import { z } from "zod";
+
+import {
+ searchSchema as reportsSearch,
+ TABS,
+} from "#/components/reports/search.ts";
+import {
+ formatDateKeyLong,
+ formatMonthKey,
+ formatWeekRange,
+} from "#/lib/format-date.ts";
+
+// One plain sentence that names the page a person is on. The dialog shows it
+// and the person may remove it. It holds only what the URL holds: no hidden data.
+
+export type PageContextInput = {
+ /** The path of the current page, with the `/$orgSlug` prefix. */
+ pathname: string;
+ /** The search params of the current page, parsed with `pageSearch`. */
+ search: PageSearch;
+ orgSlug: string;
+ today: string;
+ weekStartsOn: WeekStartsOn;
+ /** The name of the project when the page is a project page. */
+ projectName?: string | null;
+};
+
+/** The search of every page that has a sentence: the timesheet and the reports. */
+export const pageSearch = reportsSearch.extend({
+ date: dayKeySchema.optional().catch(undefined),
+ weekStart: dayKeySchema.optional().catch(undefined),
+});
+export type PageSearch = z.infer;
+
+const GROUP_WORD = {
+ clients: "client",
+ projects: "project",
+ teammates: "teammate",
+} as const;
+
+const FILTER_WORDS = [
+ ["client", "client"],
+ ["project", "project"],
+ ["task", "task"],
+ ["person", "person"],
+] as const;
+
+const pathWithin = (pathname: string, orgSlug: string) => {
+ const rest = pathname.startsWith(`/${orgSlug}`)
+ ? pathname.slice(orgSlug.length + 1)
+ : pathname;
+ return rest.replace(/\/+$/, "");
+};
+
+/** The project id of a project page, or null. */
+export function projectIdFromPath(pathname: string, orgSlug: string) {
+ const match = /^\/projects\/([^/]+)/.exec(pathWithin(pathname, orgSlug));
+ return match?.[1] ?? null;
+}
+
+function timeSentence(
+ path: string,
+ parsed: PageSearch,
+ today: string,
+ weekStartsOn: WeekStartsOn,
+) {
+ if (path === "/time") {
+ return `the Day view for ${formatDateKeyLong(parsed.date ?? today)}`;
+ }
+ if (path === "/time/week") {
+ const from = parsed.weekStart ?? startOfWeekKey(today, weekStartsOn);
+ return `the Week view for ${formatWeekRange(from, addDaysToKey(from, 6))}`;
+ }
+ if (path === "/time/month") {
+ return `the Month view for ${formatMonthKey(parsed.month ?? today.slice(0, 7))}`;
+ }
+ return null;
+}
+
+function reportSentence(
+ parsed: PageSearch,
+ today: string,
+ weekStartsOn: WeekStartsOn,
+) {
+ const tab = TABS.find((entry) => entry.id === parsed.tab) ?? TABS[0];
+ // Tracking is always one month.
+ const selection = tab.id === "compliance" ? { month: parsed.month } : parsed;
+ const { from, to } = resolveReportPeriod(selection, today, weekStartsOn);
+ const parts = [`the ${tab.label} report for ${formatWeekRange(from, to)}`];
+ if (tab.id === "time") {
+ parts.push(`grouped by ${GROUP_WORD[parsed.group ?? "projects"]}`);
+ }
+ const filters = FILTER_WORDS.filter(([key]) => parsed[key]).map(
+ ([, word]) => word,
+ );
+ if (filters.length > 0) parts.push(`filtered by ${filters.join(" and ")}`);
+ return parts.join(", ");
+}
+
+function projectSentence(path: string, rawName: string | null | undefined) {
+ // A newline or a quote in the name must not break out of the sentence.
+ const name = rawName?.replace(/[\r\n"]+/g, " ").trim();
+ if (!name) return null;
+ const sub = /^\/projects\/[^/]+\/(\w+)$/.exec(path)?.[1];
+ return sub
+ ? `the ${sub} page of the project "${name}"`
+ : `the page of the project "${name}"`;
+}
+
+/** The sentence for the current page, or null when the page is not known. */
+export function buildPageContext(input: PageContextInput): string | null {
+ const path = pathWithin(input.pathname, input.orgSlug);
+ const { today, weekStartsOn } = input;
+ let place: string | null = null;
+ if (path === "") place = "the Home page";
+ else if (path.startsWith("/time")) {
+ place = timeSentence(path, input.search, today, weekStartsOn);
+ } else if (path === "/reports") {
+ place = reportSentence(input.search, today, weekStartsOn);
+ } else if (path.startsWith("/projects/")) {
+ place = projectSentence(path, input.projectName);
+ }
+ return place ? `I am on ${place}.` : null;
+}
diff --git a/apps/web/src/components/assistant/primitives.tsx b/apps/web/src/components/assistant/primitives.tsx
index b2b87bf3..e52e7de8 100644
--- a/apps/web/src/components/assistant/primitives.tsx
+++ b/apps/web/src/components/assistant/primitives.tsx
@@ -10,11 +10,21 @@
//
// Sources: LoadingState.tsx, ThinkingState.tsx, ApprovalCard.tsx.
+import { ArrowCounterClockwiseIcon } from "@phosphor-icons/react";
import { useQuery } from "@tanstack/react-query";
-import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import {
+ type CSSProperties,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import { z } from "zod";
+import { MARK } from "#/components/farmer-mark.tsx";
import { PersonAvatar } from "#/components/person-avatar.tsx";
+import { Button } from "#/components/ui/button.tsx";
import { useOrgSlug } from "#/hooks/use-org-slug.ts";
import { cn } from "#/lib/utils.ts";
import { clientsQuery } from "#/queries/clients.ts";
@@ -26,35 +36,42 @@ import { MONTHS, printDayKey } from "./answer.tsx";
import type { PendingApproval, ToolTrace } from "./assistant-runs.tsx";
import { toolLabel } from "./tool-labels.ts";
-/* ── the pixel-grid loader (LoadingState) ─────────────────────────────────── */
+/* ── the sprout loader (LoadingState) ─────────────────────────────────────── */
-// A chevron wavefront: cell delay grows with the column and with distance from
-// the middle row, so the front reads as driving rightwards. The 650ms cycle is
-// shorter than the sweep across the grid, so two fronts are always in flight.
-const CHEVRON = Array.from({ length: 9 }, (_, i) => {
- const row = Math.floor(i / 3);
- const column = i % 3;
- return (column + Math.abs(row - 1)) * 90;
-});
+// The Farmer wheat. The stalk draws, then each grain grows out of it and drops.
+// The first piece of the mark is the tile. Skip it.
+const [, ...GRAINS] = MARK.split(/(?<=Z)(?=M)/);
+// Step along the stalk for each grain: leaf, then the pairs from base to tip.
+const STEP = [0, 1, 2, 1, 3, 2, 3];
+// The edge of each grain that touches the stalk.
+const KIND = ["leaf", "v", "v", "h", "v", "h", "h"];
-function LoaderGrid() {
+function SproutMark() {
return (
-
- {CHEVRON.map((delay, index) => (
-
+ {GRAINS.map((d, n) => (
+
))}
-
+
);
}
@@ -92,7 +109,7 @@ export function AssistantLoader({ label = "Thinking" }: { label?: string }) {
// be maintained by hand.
return (
);
})}
diff --git a/apps/web/src/components/assistant/prompt-bar.tsx b/apps/web/src/components/assistant/prompt-bar.tsx
index 629702b5..4c5df567 100644
--- a/apps/web/src/components/assistant/prompt-bar.tsx
+++ b/apps/web/src/components/assistant/prompt-bar.tsx
@@ -97,6 +97,7 @@ export function PromptBar({
placeholder = "Ask about your time, or log some…",
autoFocus,
focusKey,
+ restore,
}: {
/**
* Sends the draft. Resolving FALSE means the message never reached the
@@ -110,6 +111,9 @@ export function PromptBar({
autoFocus?: boolean;
/** Focus the input again each time this value changes. */
focusKey?: string | null;
+ /** A text to put back, as after a send that never landed. A new object
+ * each time. */
+ restore?: { text: string } | null;
}) {
const [draft, setDraft] = useState("");
const [dismissed, setDismissed] = useState(false);
@@ -197,6 +201,16 @@ export function PromptBar({
};
const canSend = draft.trim().length > 0 && !busy && !disabled;
+ // Only into a composer the person has not started refilling — their own
+ // second thought outranks the one we are handing back.
+ const giveBack = (text: string) => {
+ setDraft((current) => (current ? current : text));
+ inputRef.current?.focus();
+ };
+ // oxlint-disable-next-line react-hooks/exhaustive-deps -- only a new `restore` object may run it, and `giveBack` is rebuilt each render
+ useEffect(() => {
+ if (restore) giveBack(restore.text);
+ }, [restore]);
/**
* Clear on send, and put it back if the send never landed.
*
@@ -213,11 +227,7 @@ export function PromptBar({
setDraft("");
setDismissed(false);
void onSend(text).then((delivered) => {
- if (delivered) return;
- // Only into a composer the person has not started refilling — their
- // own second thought outranks the one we are handing back.
- setDraft((current) => (current ? current : text));
- inputRef.current?.focus();
+ if (!delivered) giveBack(text);
});
};
diff --git a/apps/web/src/components/assistant/share-chat.tsx b/apps/web/src/components/assistant/share-chat.tsx
new file mode 100644
index 00000000..9d1d465c
--- /dev/null
+++ b/apps/web/src/components/assistant/share-chat.tsx
@@ -0,0 +1,152 @@
+import { ShareNetworkIcon } from "@phosphor-icons/react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useRouteContext } from "@tanstack/react-router";
+import { useState } from "react";
+import { toast } from "sonner";
+
+import { Button } from "#/components/ui/button.tsx";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "#/components/ui/dialog.tsx";
+import { conversationsQuery } from "#/queries/assistant.ts";
+import { queryKeys } from "#/queries/keys.ts";
+import { shareConversation, unshareConversation } from "#/server/assistant.ts";
+
+const sharedUrl = (orgSlug: string, id: string) =>
+ `${window.location.origin}/${orgSlug}/assistant/shared/${id}`;
+
+const copyLink = async (url: string) => {
+ try {
+ await navigator.clipboard.writeText(url);
+ toast.success("Link copied");
+ } catch {
+ toast.error("Could not copy the link");
+ }
+};
+
+/**
+ * The Share button of the open chat, and the dialog behind it. The warning
+ * comes first: a chat holds results that were read with the owner's access.
+ */
+export function ShareChatButton({
+ orgSlug,
+ conversationId,
+ className,
+}: {
+ orgSlug: string;
+ conversationId: string;
+ className?: string;
+}) {
+ const [open, setOpen] = useState(false);
+ const { data: conversations = [] } = useQuery(conversationsQuery(orgSlug));
+ const shared = Boolean(
+ conversations.find((c) => c.id === conversationId)?.sharedAt,
+ );
+ return (
+ <>
+
+
+ >
+ );
+}
+
+function ShareDialog({
+ open,
+ onOpenChange,
+ orgSlug,
+ conversationId,
+ shared,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ orgSlug: string;
+ conversationId: string;
+ shared: boolean;
+}) {
+ const queryClient = useQueryClient();
+ const orgName = useRouteContext({
+ from: "/$orgSlug",
+ select: (context) => context.organization.name,
+ });
+ const url = sharedUrl(orgSlug, conversationId);
+ const refresh = () =>
+ queryClient.invalidateQueries({
+ queryKey: [...queryKeys(orgSlug).assistant, "conversations"],
+ });
+
+ const share = useMutation({
+ mutationFn: () => shareConversation({ data: { conversationId } }),
+ onSuccess: async () => {
+ await refresh();
+ await copyLink(url);
+ onOpenChange(false);
+ },
+ onError: (error) => toast.error(error.message ?? "Could not share"),
+ });
+ const stop = useMutation({
+ mutationFn: () => unshareConversation({ data: { conversationId } }),
+ onSuccess: async () => {
+ await refresh();
+ toast.success("Sharing stopped");
+ onOpenChange(false);
+ },
+ onError: (error) => toast.error(error.message ?? "Could not stop sharing"),
+ });
+
+ return (
+
+ );
+}
diff --git a/apps/web/src/components/assistant/stored-turn.tsx b/apps/web/src/components/assistant/stored-turn.tsx
new file mode 100644
index 00000000..1dd0e41d
--- /dev/null
+++ b/apps/web/src/components/assistant/stored-turn.tsx
@@ -0,0 +1,204 @@
+import { ArrowClockwiseIcon, PencilSimpleIcon } from "@phosphor-icons/react";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { useState } from "react";
+import { toast } from "sonner";
+
+import { Button } from "#/components/ui/button.tsx";
+import { Textarea } from "#/components/ui/textarea.tsx";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "#/components/ui/tooltip.tsx";
+import { useOrgSlug } from "#/hooks/use-org-slug.ts";
+import { conversationQuery } from "#/queries/assistant.ts";
+import { queryKeys } from "#/queries/keys.ts";
+import {
+ rewindAssistantThread,
+ undoAssistantWrite,
+} from "#/server/assistant.ts";
+
+import type { ToolTrace } from "./assistant-runs.tsx";
+import { ToolTraceList } from "./primitives.tsx";
+
+/** A stored write that has an Undo, or that was undone. */
+export function StoredWriteTrace({
+ conversationId,
+ messageId,
+ trace,
+ done,
+ locked,
+}: {
+ conversationId: string;
+ messageId: string;
+ trace: Pick;
+ done: boolean;
+ /** A turn runs or a card waits. */
+ locked: boolean;
+}) {
+ const orgSlug = useOrgSlug();
+ const queryClient = useQueryClient();
+ const undo = useMutation({
+ mutationFn: () =>
+ undoAssistantWrite({ data: { conversationId, messageId } }),
+ onSuccess: () =>
+ Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: conversationQuery(orgSlug, conversationId).queryKey,
+ }),
+ queryClient.invalidateQueries({
+ queryKey: queryKeys(orgSlug).timeEntries,
+ }),
+ ]),
+ onError: (error) => toast.error(error.message ?? "Could not undo"),
+ });
+ return (
+ undo.mutate(),
+ },
+ },
+ ]}
+ />
+ );
+}
+
+/** Disabled buttons do not fire pointer events, so the span takes the hover. */
+function WithReason({
+ reason,
+ children,
+}: {
+ reason: string | null;
+ children: React.ReactNode;
+}) {
+ if (!reason) return children;
+ return (
+
+
+ }>
+ {children}
+
+ {reason}
+
+
+ );
+}
+
+/**
+ * The actions on the last question: Edit and Retry. Both take the question
+ * back from the server (`rewindAssistantThread`), then send the text again as
+ * a new turn.
+ */
+export function LastQuestionActions({
+ conversationId,
+ text,
+ reason,
+ onSend,
+ onRestore,
+ editing,
+ onEditingChange,
+}: {
+ conversationId: string;
+ text: string;
+ /** Why the actions are off, or null. */
+ reason: string | null;
+ onSend: (text: string) => Promise;
+ /** The question is gone from the thread and the send failed: put the text
+ * back in the composer. */
+ onRestore: (text: string) => void;
+ editing: boolean;
+ onEditingChange: (editing: boolean) => void;
+}) {
+ const orgSlug = useOrgSlug();
+ const queryClient = useQueryClient();
+ const [draft, setDraft] = useState(text);
+ const resend = useMutation({
+ mutationFn: async (next: string) => {
+ await rewindAssistantThread({ data: { conversationId } });
+ await queryClient.invalidateQueries({
+ queryKey: conversationQuery(orgSlug, conversationId).queryKey,
+ });
+ if (await onSend(next)) return;
+ // The rewind removed the question, so this row is about to unmount.
+ onEditingChange(false);
+ onRestore(next);
+ throw new Error("The message was not sent. Your text is in the box.");
+ },
+ onSuccess: () => onEditingChange(false),
+ onError: (error) => toast.error(error.message ?? "Could not send again"),
+ });
+
+ if (editing) {
+ return (
+
+
+ );
+ }
+
+ return (
+
+
+
+
+
+
+
+
+ );
+}
diff --git a/apps/web/src/components/assistant/suggestions.test.ts b/apps/web/src/components/assistant/suggestions.test.ts
new file mode 100644
index 00000000..462769de
--- /dev/null
+++ b/apps/web/src/components/assistant/suggestions.test.ts
@@ -0,0 +1,71 @@
+import { expect, test } from "bun:test";
+
+import { chooseSuggestions, type SuggestionFacts } from "./suggestions.ts";
+
+const quiet: SuggestionFacts = {
+ daySeconds: 8 * 3600,
+ todaySeconds: 8 * 3600,
+ yesterdaySeconds: 8 * 3600,
+ todayIsWorkingDay: true,
+ yesterdayIsWorkingDay: true,
+ unfiledCount: 0,
+ calendarConnected: false,
+};
+
+test("a full day with nothing to file gives only general questions", () => {
+ const result = chooseSuggestions(quiet);
+ expect(result).toHaveLength(2);
+ expect(result.join(" ")).not.toMatch(/March|January|today/);
+});
+
+test("a short day and unfiled entries come first", () => {
+ const result = chooseSuggestions({
+ ...quiet,
+ todaySeconds: 3600,
+ unfiledCount: 4,
+ });
+ expect(result).toEqual([
+ "Help me log the rest of today",
+ "File my 4 unfiled entries",
+ "How many hours did I log last week?",
+ ]);
+});
+
+test("a short day off work is not offered", () => {
+ const result = chooseSuggestions({
+ ...quiet,
+ todaySeconds: 0,
+ todayIsWorkingDay: false,
+ });
+ expect(result).not.toContain("Help me log the rest of today");
+});
+
+test("yesterday needs the calendar", () => {
+ const short = { ...quiet, yesterdaySeconds: 0 };
+ expect(chooseSuggestions(short)).not.toContain(
+ "Fill yesterday from my calendar",
+ );
+ expect(chooseSuggestions({ ...short, calendarConnected: true })).toContain(
+ "Fill yesterday from my calendar",
+ );
+});
+
+test("no target means no hours suggestion, and data not loaded is quiet", () => {
+ expect(
+ chooseSuggestions({ ...quiet, daySeconds: null, todaySeconds: 0 }),
+ ).toHaveLength(2);
+ expect(chooseSuggestions({ ...quiet, todaySeconds: null })).toHaveLength(2);
+});
+
+test("a general question always stays and the list has three at most", () => {
+ const result = chooseSuggestions({
+ ...quiet,
+ todaySeconds: 0,
+ yesterdaySeconds: 0,
+ unfiledCount: 1,
+ calendarConnected: true,
+ });
+ expect(result).toHaveLength(3);
+ expect(result).toContain("How many hours did I log last week?");
+ expect(result).toContain("File my unfiled entry");
+});
diff --git a/apps/web/src/components/assistant/suggestions.ts b/apps/web/src/components/assistant/suggestions.ts
new file mode 100644
index 00000000..caa6d99f
--- /dev/null
+++ b/apps/web/src/components/assistant/suggestions.ts
@@ -0,0 +1,57 @@
+// The questions the empty chat offers, chosen from what the app knows today.
+// No model call. Never names a month: the words stay true on any day.
+
+export type SuggestionFacts = {
+ /** One working day's target, or null when the person has no target. */
+ daySeconds: number | null;
+ /** Hours logged today and yesterday. Null while the data loads. */
+ todaySeconds: number | null;
+ yesterdaySeconds: number | null;
+ todayIsWorkingDay: boolean;
+ yesterdayIsWorkingDay: boolean;
+ unfiledCount: number;
+ calendarConnected: boolean;
+};
+
+const FALLBACKS = [
+ "How many hours did I log last week?",
+ "Which project took most of my time last month?",
+];
+
+const MAX_SUGGESTIONS = 3;
+// Room is kept for at least one general question.
+const MAX_SPECIFIC = MAX_SUGGESTIONS - 1;
+
+const isShort = (
+ seconds: number | null,
+ target: number | null,
+ isWorkingDay: boolean,
+) => isWorkingDay && target !== null && seconds !== null && seconds < target;
+
+export function chooseSuggestions(facts: SuggestionFacts): string[] {
+ const specific: string[] = [];
+ if (isShort(facts.todaySeconds, facts.daySeconds, facts.todayIsWorkingDay)) {
+ specific.push("Help me log the rest of today");
+ }
+ if (facts.unfiledCount > 0) {
+ specific.push(
+ facts.unfiledCount === 1
+ ? "File my unfiled entry"
+ : `File my ${facts.unfiledCount} unfiled entries`,
+ );
+ }
+ if (
+ facts.calendarConnected &&
+ isShort(
+ facts.yesterdaySeconds,
+ facts.daySeconds,
+ facts.yesterdayIsWorkingDay,
+ )
+ ) {
+ specific.push("Fill yesterday from my calendar");
+ }
+ return [...specific.slice(0, MAX_SPECIFIC), ...FALLBACKS].slice(
+ 0,
+ MAX_SUGGESTIONS,
+ );
+}
diff --git a/apps/web/src/components/assistant/use-suggestions.ts b/apps/web/src/components/assistant/use-suggestions.ts
new file mode 100644
index 00000000..6c9c8b7b
--- /dev/null
+++ b/apps/web/src/components/assistant/use-suggestions.ts
@@ -0,0 +1,45 @@
+import { addDaysToKey, weekdayInTz } from "@farmer/core/lib/time";
+import { useQuery } from "@tanstack/react-query";
+
+import { chooseSuggestions } from "#/components/assistant/suggestions.ts";
+import { useToday } from "#/hooks/use-today.ts";
+import { useUnfiledCount } from "#/hooks/use-unfiled-count.ts";
+import { myTargetsQuery } from "#/queries/compliance.ts";
+import { googleCalendarStatusQuery } from "#/queries/google-calendar.ts";
+import { timeEntriesRangeQuery } from "#/queries/time-entries.ts";
+
+// shortcut: a public holiday counts as a working day here, so a holiday
+// can offer "log the rest of today". Read the holidays query to fix it.
+const isWeekday = (day: string, timezone: string) => {
+ const weekday = weekdayInTz(day, timezone);
+ return weekday !== 0 && weekday !== 6;
+};
+
+/** The empty chat's questions, from queries the app already holds. */
+export function useSuggestions(orgSlug: string, timezone: string): string[] {
+ const today = useToday(timezone);
+ const yesterday = addDaysToKey(today, -1);
+ const { data: targets } = useQuery(myTargetsQuery(orgSlug, today));
+ const { data: entries } = useQuery(
+ timeEntriesRangeQuery(orgSlug, yesterday, today),
+ );
+ const { data: calendar } = useQuery(googleCalendarStatusQuery(orgSlug));
+ const unfiledCount = useUnfiledCount(orgSlug, timezone);
+
+ const secondsOn = (day: string) =>
+ entries
+ ? entries
+ .filter((entry) => entry.date === day)
+ .reduce((sum, entry) => sum + entry.durationSeconds, 0)
+ : null;
+
+ return chooseSuggestions({
+ daySeconds: targets?.week.targetSeconds == null ? null : targets.daySeconds,
+ todaySeconds: secondsOn(today),
+ yesterdaySeconds: secondsOn(yesterday),
+ todayIsWorkingDay: isWeekday(today, timezone),
+ yesterdayIsWorkingDay: isWeekday(yesterday, timezone),
+ unfiledCount,
+ calendarConnected: calendar?.connected === true,
+ });
+}
diff --git a/apps/web/src/components/assistant/user-message.tsx b/apps/web/src/components/assistant/user-message.tsx
new file mode 100644
index 00000000..8872e498
--- /dev/null
+++ b/apps/web/src/components/assistant/user-message.tsx
@@ -0,0 +1,11 @@
+/** One thing the user said. Rendered from the transcript, and — for the turn in
+ * flight — from the text the composer just sent. */
+export function UserMessage({ text }: { text: string }) {
+ return (
+
- );
-}
-
function AssistantPage() {
const orgSlug = useOrgSlug();
const queryClient = useQueryClient();
const navigate = useNavigate();
const conversationId = Route.useSearch().c ?? null;
+ const { organization } = Route.useRouteContext();
+ const suggestions = useSuggestions(orgSlug, organization.timezone);
const { data: settings } = useQuery(assistantSettingsQuery(orgSlug));
const { data: thread } = useQuery({
@@ -245,12 +244,31 @@ function AssistantPage() {
})();
const pending = stream.pending ?? storedPending;
+ // Edit and Retry belong to the last question, and only when nothing runs
+ // and no write of that turn still stands. The server checks again.
+ const lastUserIndex = messages.map((m) => m.role).lastIndexOf("user");
+ const editBlock = (() => {
+ if (stream.isStreaming) return "Wait for the answer to finish.";
+ if (pending) return "Answer the card first.";
+ return editBlockReason(
+ messages
+ .slice(lastUserIndex)
+ .filter((m) => m.changed)
+ .map((m) => ({ undoable: Boolean(m.undo) })),
+ );
+ })();
+ const [restore, setRestore] = useState<{ text: string } | null>(null);
+
// Which transcript is on screen — the thread that has actually loaded, not
// the one the URL is pointing at. They differ for as long as a click takes to
// answer, and everything below keys off the former: the swap animates once,
// when there is something new to show, and the scroll lands at the end of the
// content that is really there.
const viewKey = thread?.conversation.id ?? "new";
+ // Edit mode belongs to one thread: another thread reads as not editing.
+ const [editingKey, setEditingKey] = useState(null);
+ const editing = editingKey === viewKey;
+ const setEditing = (on: boolean) => setEditingKey(on ? viewKey : null);
// Follow the transcript's end. Scrolling the container rather than the
// document: this screen owns the viewport height, so the document never
@@ -318,8 +336,8 @@ function AssistantPage() {
The assistant needs to be connected again
The stored OpenRouter key can no longer be read. An admin can paste
- it again under ,
- and the assistant comes back with every conversation intact.
+ it again under , and the
+ assistant comes back with every conversation intact.
@@ -334,8 +352,8 @@ function AssistantPage() {
The assistant isn't connected
An admin can connect this workspace's OpenRouter account under
- . Until then
- there's nothing to ask.
+ . Until then there's nothing
+ to ask.
@@ -354,6 +372,14 @@ function AssistantPage() {
the Browse/Chat switch both live in the sidebar, which doesn't
exist at this width. */}
+ {conversationId && (
+
+
+
+ )}
{/* The transcript scrolls; the composer below it does not. The
ordering is the whole layout: history moves upward under the
@@ -392,7 +418,7 @@ function AssistantPage() {
I'd write is shown to you first.
+ );
+}
diff --git a/apps/web/src/routes/$orgSlug/settings/workspace-integrations.tsx b/apps/web/src/routes/$orgSlug/settings/workspace-integrations.tsx
index cfea5f37..a86689c9 100644
--- a/apps/web/src/routes/$orgSlug/settings/workspace-integrations.tsx
+++ b/apps/web/src/routes/$orgSlug/settings/workspace-integrations.tsx
@@ -1,5 +1,3 @@
-import { matchesSearch } from "@farmer/core/lib/search";
-import { MAX_SYSTEM_PROMPT_CHARS } from "@farmer/core/schema";
// Type-only, so it is erased: a runtime import of the services barrel in a
// route reaches `postgres` and crashes hydration.
import type { UninstallOutcome } from "@farmer/core/services";
@@ -16,7 +14,7 @@ import {
useSuspenseQuery,
} from "@tanstack/react-query";
import { createFileRoute, Link } from "@tanstack/react-router";
-import { useMemo, useState } from "react";
+import { useState } from "react";
import { toast } from "sonner";
import { z } from "zod";
@@ -35,16 +33,6 @@ import {
} from "#/components/ui/alert-dialog.tsx";
import { Badge } from "#/components/ui/badge.tsx";
import { Button } from "#/components/ui/button.tsx";
-import {
- Combobox,
- ComboboxContent,
- ComboboxEmpty,
- ComboboxItem,
- ComboboxList,
- ComboboxTrigger,
- ComboboxValue,
-} from "#/components/ui/combobox.tsx";
-import { Input } from "#/components/ui/input.tsx";
import {
Page,
PageHeader,
@@ -53,23 +41,12 @@ import {
SettingRow,
} from "#/components/ui/page-header.tsx";
import { Switch } from "#/components/ui/switch.tsx";
-import { Textarea } from "#/components/ui/textarea.tsx";
import { useOrgSlug } from "#/hooks/use-org-slug.ts";
-import {
- assistantModelsQuery,
- assistantSettingsQuery,
-} from "#/queries/assistant.ts";
import {
githubConnectionStatusQuery,
githubInstallationsQuery,
} from "#/queries/github.ts";
-import { queryKeys } from "#/queries/keys.ts";
import { slackStatusQuery } from "#/queries/slack.ts";
-import {
- disconnectAssistant,
- setAssistantSettings,
- updateAssistantSettings,
-} from "#/server/assistant.ts";
import { requireOrgAdmin } from "#/server/auth.ts";
import {
connectGithubInstallation,
@@ -85,7 +62,7 @@ import {
// What the WORKSPACE is connected to, as opposed to what a person is: the
// GitHub accounts whose repositories projects may link, the Slack workspace the
-// reminders speak through, and the model provider the assistant bills. Each is
+// reminders speak through. Each is
// one relationship per organization, made by an admin — which is why they are
// a page under Workspace rather than sections gated on a shared one: the hub
// already splits every other setting by scope, and this page follows it. A
@@ -137,372 +114,37 @@ function WorkspaceIntegrationsPage() {
- {/* OpenRouter — one account per org, like Slack, and for the same reason:
- it is a billing relationship the workspace has, not a grant each
- person makes. Also behind the deployment's `ASSISTANT_ENABLED`
- switch: the services refuse to store a key while the feature is off,
- so offering the form would be offering an action that cannot
- succeed. */}
- {assistantEnabled && }
+ {/* The OpenRouter account has its own page. Behind the deployment's
+ `ASSISTANT_ENABLED` switch, like the page itself. */}
+ {assistantEnabled && (
+
+
+ }
+ title="OpenRouter"
+ description={
+ <>
+ The Assistant's key, model and house rules are under{" "}
+ .
+ >
+ }
+ action={
+
+ Open AI settings
+
+ }
+ />
+
+
+ )}
);
}
-/**
- * House rules appended to the assistant's system prompt.
- *
- * Its own row rather than a field in the list above because it is a textarea
- * with a dirty state and an explicit save — the switches beside it write on
- * change, which is wrong for prose somebody is still in the middle of typing.
- */
-function HouseRulesRow({ stored }: { stored: string }) {
- const orgSlug = useOrgSlug();
- const queryClient = useQueryClient();
- const [draft, setDraft] = useState(stored);
- // Re-seed when the server's copy changes underneath (another admin, another
- // tab) — but only when the box is clean, so it can't eat what is being typed.
- const [baseline, setBaseline] = useState(stored);
- if (stored !== baseline && draft === baseline) {
- setBaseline(stored);
- setDraft(stored);
- }
- const dirty = draft !== stored;
-
- const save = useMutation({
- mutationFn: () =>
- updateAssistantSettings({
- // Empty box clears the rules: null is "forget them", where undefined
- // would mean "leave them alone".
- data: { systemPrompt: draft.trim() ? draft.trim() : null },
- }),
- onSuccess: async () => {
- await queryClient.invalidateQueries({
- queryKey: queryKeys(orgSlug).assistant,
- });
- toast.success("House rules saved");
- },
- onError: (error) => toast.error(error.message ?? "Could not save"),
- });
-
- return (
-
-
-
House rules
-
- Added to the built-in instructions. The built-in ones win a conflict.
-
-
-
- );
-}
-
-type ModelItem = { value: string; label: string };
-
-/**
- * The default-model picker.
- *
- * OpenRouter answers with hundreds of tool-capable models, so this is the same
- * searching Combobox the project and task pickers use rather than a Select
- * nobody can scan. The search covers the model id as well as its name: a
- * provider is spelled one way there ("anthropic/", "google/") and several ways
- * in the names, so the id is what somebody types to see one vendor's list.
- *
- * The stored model is added to the list when the catalogue does not have it —
- * while the catalogue is still loading, and for a model OpenRouter has since
- * retired. The trigger then shows the raw id, which is what is actually saved.
- */
-function ModelPicker({
- models,
- value,
- onValueChange,
- disabled,
-}: {
- models: { id: string; name: string }[];
- /** The stored model id, or "" before one is chosen. */
- value: string;
- onValueChange: (modelId: string) => void;
- disabled?: boolean;
-}) {
- const items = useMemo(() => {
- const known = models.map((model) => ({
- value: model.id,
- label: model.name,
- }));
- if (value === "" || known.some((item) => item.value === value))
- return known;
- return [{ value, label: value }, ...known];
- }, [models, value]);
-
- const [query, setQuery] = useState("");
- const filtered = useMemo(() => {
- if (query.trim() === "") return items;
- return items.filter((item) =>
- matchesSearch(query, [item.label, item.value]),
- );
- }, [items, query]);
-
- const selected = items.find((item) => item.value === value) ?? null;
-
- return (
- {
- if (item) onValueChange(item.value);
- }}
- isItemEqualToValue={(a: ModelItem, b: ModelItem) => a.value === b.value}
- itemToStringLabel={(item: ModelItem) => item.label}
- inputValue={query}
- onInputValueChange={setQuery}
- onOpenChange={(open) => {
- if (!open) setQuery("");
- }}
- autoHighlight
- disabled={disabled}
- >
-
-
- {(item: ModelItem | null) =>
- item ? (
- {item.label}
- ) : (
- "Pick a model"
- )
- }
-
-
-
- No model matches.
-
- {(item: ModelItem) => (
-
- {item.label}
-
- )}
-
-
-
- );
-}
-
-// Admin-only and mounted only for admins: `assistantModelsQuery` sits behind
-// `orgAdminMiddleware` (it needs the key), so prefetching it in the route loader
-// would 403 for every member. Same shape as SlackSection below.
-function OpenRouterSection() {
- const orgSlug = useOrgSlug();
- const queryClient = useQueryClient();
- const { data: settings } = useQuery(assistantSettingsQuery(orgSlug));
- const [apiKey, setApiKey] = useState("");
-
- const configured = settings?.configured ?? false;
- // A row whose key no longer opens (`BETTER_AUTH_SECRET` changed). Not
- // configured, so nothing below that needs the key is shown, but the admin is
- // told why it stopped, and may still disconnect the stored row.
- const unreadable = settings?.keyUnreadable ?? false;
-
- const invalidate = () =>
- queryClient.invalidateQueries({
- queryKey: queryKeys(orgSlug).assistant,
- });
-
- // Only once a key exists — the catalogue call authenticates with it, so
- // asking before then is a guaranteed error.
- const { data: models = [] } = useQuery({
- ...assistantModelsQuery(orgSlug),
- enabled: configured,
- });
-
- const connect = useMutation({
- mutationFn: () =>
- setAssistantSettings({
- data: {
- apiKey: apiKey.trim(),
- // A safe, cheap, tool-capable default so the first question works
- // before anyone has thought about models. Changeable right below.
- defaultModel: settings?.defaultModel ?? "openai/gpt-4o-mini",
- },
- }),
- onSuccess: async () => {
- setApiKey("");
- await invalidate();
- toast.success("OpenRouter connected");
- },
- onError: (error) =>
- toast.error(error.message ?? "Could not connect OpenRouter"),
- });
-
- const setModel = useMutation({
- mutationFn: (defaultModel: string) =>
- updateAssistantSettings({ data: { defaultModel } }),
- onSuccess: async () => {
- await invalidate();
- toast.success("Default model updated");
- },
- onError: (error) => toast.error(error.message ?? "Could not update"),
- });
-
- const toggle = useMutation({
- mutationFn: (enabled: boolean) =>
- updateAssistantSettings({ data: { enabled } }),
- onSuccess: invalidate,
- onError: (error) => toast.error(error.message ?? "Could not update"),
- });
-
- const disconnect = useMutation({
- mutationFn: () => disconnectAssistant(),
- onSuccess: async () => {
- await invalidate();
- toast.success("OpenRouter disconnected");
- },
- onError: (error) => toast.error(error.message ?? "Could not disconnect"),
- });
-
- return (
-
- }
- title="OpenRouter"
- badge={
- configured ? (
-
- {settings?.enabled ? "Connected" : "Paused"}
-
- ) : (
- unreadable && Connect again
- )
- }
- description="Powers the Assistant for the whole workspace. Each answer uses only what the asker can see."
- action={
- configured || unreadable ? (
-
-
- Disconnect
-
- }
- />
-
-
- Disconnect OpenRouter
-
- The Assistant stops for everyone. Past conversations stay.
- To revoke the key, use OpenRouter.
-
-
-
- Cancel
- disconnect.mutate()}
- >
- Disconnect
-
-
-
-
- ) : null
- }
- />
-
-
-
- setApiKey(event.target.value)}
- placeholder="sk-or-v1-…"
- autoComplete="off"
- className="w-56"
- aria-label="OpenRouter API key"
- />
- connect.mutate()}
- >
- {connect.isPending ? "Checking…" : "Save"}
-
-
- }
- />
-
- {configured && (
- setModel.mutate(modelId)}
- disabled={setModel.isPending}
- />
- }
- />
- )}
-
- {configured && (
- toggle.mutate(value)}
- disabled={toggle.isPending}
- />
- }
- />
- )}
-
-
- {configured && }
-
- );
-}
-
// Admin-only, and mounted only for admins — `slackStatusQuery` hits a server fn
// behind `orgAdminMiddleware`, so putting it in the route loader (which every
// member runs) would 403 for everyone else. Same reason `githubInstallationsQuery`
diff --git a/apps/web/src/routes/api/v1/orgs/$orgSlug/assistant/shared-threads/$id.ts b/apps/web/src/routes/api/v1/orgs/$orgSlug/assistant/shared-threads/$id.ts
new file mode 100644
index 00000000..7c184c12
--- /dev/null
+++ b/apps/web/src/routes/api/v1/orgs/$orgSlug/assistant/shared-threads/$id.ts
@@ -0,0 +1,49 @@
+import {
+ type ApiAssistantSharedThread,
+ toApiAssistantMessage,
+ toApiAssistantThread,
+} from "@farmer/core/api";
+import { conversationIdInput } from "@farmer/core/schema";
+import { createFileRoute } from "@tanstack/react-router";
+
+import {
+ type ApiRequest,
+ apiRoute,
+ type OrgRowParams,
+} from "#/server/api-route.ts";
+import { assertAssistantAvailable } from "#/server/assistant-stream.ts";
+
+/**
+ * `GET /api/v1/orgs/$orgSlug/assistant/shared-threads/$id` — a thread that its
+ * owner shared with the organization. Any member may read it. Read only. A
+ * thread that is not shared is a 404. 404 when the deployment has the
+ * assistant switched off.
+ */
+export const Route = createFileRoute(
+ "/api/v1/orgs/$orgSlug/assistant/shared-threads/$id",
+)({
+ server: {
+ handlers: {
+ GET: apiRoute({
+ input: conversationIdInput,
+ raw: ({ params }: ApiRequest) => ({
+ conversationId: params.id,
+ }),
+ run: async (
+ ctx,
+ { conversationId },
+ ): Promise => {
+ await assertAssistantAvailable();
+ const { assistantService } = await import("@farmer/core/services");
+ const shared = await assistantService.getShared(ctx, conversationId);
+ return {
+ thread: toApiAssistantThread(shared.conversation),
+ messages: shared.messages.map(toApiAssistantMessage),
+ sharedAt: shared.sharedAt.toISOString(),
+ sharedBy: shared.sharedBy,
+ };
+ },
+ }),
+ },
+ },
+});
diff --git a/apps/web/src/routes/api/v1/orgs/$orgSlug/assistant/threads/$id/index.ts b/apps/web/src/routes/api/v1/orgs/$orgSlug/assistant/threads/$id/index.ts
index cda4e161..dc6bd277 100644
--- a/apps/web/src/routes/api/v1/orgs/$orgSlug/assistant/threads/$id/index.ts
+++ b/apps/web/src/routes/api/v1/orgs/$orgSlug/assistant/threads/$id/index.ts
@@ -47,11 +47,13 @@ export const Route = createFileRoute(
): Promise => {
await assertAssistantAvailable();
const { assistantService } = await import("@farmer/core/services");
- const { conversation, messages } =
+ const { conversation, messages, promptTokens, contextLength } =
await assistantService.conversations.get(ctx, conversationId);
return {
thread: toApiAssistantThread(conversation),
messages: messages.map(toApiAssistantMessage),
+ promptTokens,
+ contextLength,
};
},
}),
diff --git a/apps/web/src/routes/api/v1/orgs/$orgSlug/assistant/threads/$id/messages/$messageId/undo.ts b/apps/web/src/routes/api/v1/orgs/$orgSlug/assistant/threads/$id/messages/$messageId/undo.ts
new file mode 100644
index 00000000..9300ffb0
--- /dev/null
+++ b/apps/web/src/routes/api/v1/orgs/$orgSlug/assistant/threads/$id/messages/$messageId/undo.ts
@@ -0,0 +1,38 @@
+import {
+ type ApiAssistantMessage,
+ toApiAssistantMessage,
+} from "@farmer/core/api";
+import { assistantMessageIdInput } from "@farmer/core/schema";
+import { createFileRoute } from "@tanstack/react-router";
+
+import { type ApiRequest, apiRoute } from "#/server/api-route.ts";
+import { assertAssistantAvailable } from "#/server/assistant-stream.ts";
+
+type UndoParams = { orgSlug: string; id: string; messageId: string };
+
+/**
+ * `POST /api/v1/orgs/$orgSlug/assistant/threads/$id/messages/$messageId/undo` —
+ * undoes one inline write from its `tool` row and answers with the row. 404
+ * when the deployment has the assistant switched off.
+ */
+export const Route = createFileRoute(
+ "/api/v1/orgs/$orgSlug/assistant/threads/$id/messages/$messageId/undo",
+)({
+ server: {
+ handlers: {
+ POST: apiRoute({
+ input: assistantMessageIdInput,
+ raw: ({ params }: ApiRequest) => ({
+ conversationId: params.id,
+ messageId: params.messageId,
+ }),
+ run: async (ctx, input): Promise => {
+ await assertAssistantAvailable();
+ const { assistantService } = await import("@farmer/core/services");
+ const { message } = await assistantService.undo(ctx, input);
+ return toApiAssistantMessage(message);
+ },
+ }),
+ },
+ },
+});
diff --git a/apps/web/src/routes/api/v1/orgs/$orgSlug/assistant/threads/$id/rewind.ts b/apps/web/src/routes/api/v1/orgs/$orgSlug/assistant/threads/$id/rewind.ts
new file mode 100644
index 00000000..f8856736
--- /dev/null
+++ b/apps/web/src/routes/api/v1/orgs/$orgSlug/assistant/threads/$id/rewind.ts
@@ -0,0 +1,36 @@
+import type { ApiAssistantRewind } from "@farmer/core/api";
+import { conversationIdInput } from "@farmer/core/schema";
+import { createFileRoute } from "@tanstack/react-router";
+
+import {
+ type ApiRequest,
+ apiRoute,
+ type OrgRowParams,
+} from "#/server/api-route.ts";
+import { assertAssistantAvailable } from "#/server/assistant-stream.ts";
+
+/**
+ * `POST /api/v1/orgs/$orgSlug/assistant/threads/$id/rewind` — removes the last
+ * question and the rows after it, and answers with the question text. The
+ * client sends the text again as a new message. 404 when the deployment has
+ * the assistant switched off.
+ */
+export const Route = createFileRoute(
+ "/api/v1/orgs/$orgSlug/assistant/threads/$id/rewind",
+)({
+ server: {
+ handlers: {
+ POST: apiRoute({
+ input: conversationIdInput,
+ raw: ({ params }: ApiRequest) => ({
+ conversationId: params.id,
+ }),
+ run: async (ctx, input): Promise => {
+ await assertAssistantAvailable();
+ const { assistantService } = await import("@farmer/core/services");
+ return assistantService.replaceLastTurn(ctx, input);
+ },
+ }),
+ },
+ },
+});
diff --git a/apps/web/src/routes/api/v1/orgs/$orgSlug/assistant/threads/$id/share.ts b/apps/web/src/routes/api/v1/orgs/$orgSlug/assistant/threads/$id/share.ts
new file mode 100644
index 00000000..78726d84
--- /dev/null
+++ b/apps/web/src/routes/api/v1/orgs/$orgSlug/assistant/threads/$id/share.ts
@@ -0,0 +1,51 @@
+import type { ApiAssistantShare } from "@farmer/core/api";
+import { conversationIdInput } from "@farmer/core/schema";
+import { createFileRoute } from "@tanstack/react-router";
+
+import {
+ type ApiRequest,
+ apiRoute,
+ type OrgRowParams,
+} from "#/server/api-route.ts";
+import { assertAssistantAvailable } from "#/server/assistant-stream.ts";
+
+const fromPath = ({ params }: ApiRequest) => ({
+ conversationId: params.id,
+});
+
+/**
+ * `POST` and `DELETE /api/v1/orgs/$orgSlug/assistant/threads/$id/share` —
+ * share the caller's thread with the organization, and stop sharing it. An
+ * Admin may stop any shared thread. 404 when the deployment has the assistant
+ * switched off.
+ */
+export const Route = createFileRoute(
+ "/api/v1/orgs/$orgSlug/assistant/threads/$id/share",
+)({
+ server: {
+ handlers: {
+ POST: apiRoute({
+ input: conversationIdInput,
+ raw: fromPath,
+ run: async (ctx, { conversationId }): Promise => {
+ await assertAssistantAvailable();
+ const { assistantService } = await import("@farmer/core/services");
+ const { sharedAt } = await assistantService.share(
+ ctx,
+ conversationId,
+ );
+ return { sharedAt: sharedAt.toISOString() };
+ },
+ }),
+ DELETE: apiRoute({
+ input: conversationIdInput,
+ raw: fromPath,
+ run: async (ctx, { conversationId }): Promise => {
+ await assertAssistantAvailable();
+ const { assistantService } = await import("@farmer/core/services");
+ return assistantService.unshare(ctx, conversationId);
+ },
+ }),
+ },
+ },
+});
diff --git a/apps/web/src/routes/api/v1/orgs/$orgSlug/assistant/threads/search.ts b/apps/web/src/routes/api/v1/orgs/$orgSlug/assistant/threads/search.ts
new file mode 100644
index 00000000..000415e2
--- /dev/null
+++ b/apps/web/src/routes/api/v1/orgs/$orgSlug/assistant/threads/search.ts
@@ -0,0 +1,32 @@
+import {
+ type ApiAssistantSearchHit,
+ toApiAssistantSearchHit,
+} from "@farmer/core/api";
+import { searchConversationsInput } from "@farmer/core/schema";
+import { createFileRoute } from "@tanstack/react-router";
+
+import { apiRoute } from "#/server/api-route.ts";
+import { assertAssistantAvailable } from "#/server/assistant-stream.ts";
+
+/**
+ * `GET /api/v1/orgs/$orgSlug/assistant/threads/search?q=` — the caller's own
+ * threads whose title or text match, newest first (at most 30). 404 when the
+ * deployment has the assistant switched off.
+ */
+export const Route = createFileRoute(
+ "/api/v1/orgs/$orgSlug/assistant/threads/search",
+)({
+ server: {
+ handlers: {
+ GET: apiRoute({
+ input: searchConversationsInput,
+ run: async (ctx, input): Promise => {
+ await assertAssistantAvailable();
+ const { assistantService } = await import("@farmer/core/services");
+ const rows = await assistantService.search(ctx, input);
+ return rows.map(toApiAssistantSearchHit);
+ },
+ }),
+ },
+ },
+});
diff --git a/apps/web/src/server/assistant.ts b/apps/web/src/server/assistant.ts
index 3346afa3..1a98a8a6 100644
--- a/apps/web/src/server/assistant.ts
+++ b/apps/web/src/server/assistant.ts
@@ -1,7 +1,10 @@
import {
+ assistantMessageIdInput,
+ assistantUsageInput,
conversationIdInput,
createConversationInput,
renameConversationInput,
+ searchConversationsInput,
setAssistantSettingsInput,
updateAssistantSettingsInput,
} from "@farmer/core/schema";
@@ -68,6 +71,14 @@ export const listAssistantModels = createServerFn({ method: "GET" })
return assistantService.settings.listModels(context.ctx);
});
+export const getAssistantUsage = createServerFn({ method: "GET" })
+ .middleware([orgAdminMiddleware])
+ .validator(assistantUsageInput)
+ .handler(async ({ data, context }) => {
+ const { assistantUsageService } = await import("@farmer/core/services");
+ return assistantUsageService.summary(context.ctx, data);
+ });
+
export const listConversations = createServerFn({ method: "GET" })
.middleware([orgMiddleware])
.handler(async ({ context }) => {
@@ -109,3 +120,53 @@ export const deleteConversation = createServerFn({ method: "POST" })
data.conversationId,
);
});
+
+export const undoAssistantWrite = createServerFn({ method: "POST" })
+ .middleware([orgMiddleware])
+ .validator(assistantMessageIdInput)
+ .handler(async ({ data, context }) => {
+ const { assistantService } = await import("@farmer/core/services");
+ return assistantService.undo(context.ctx, data);
+ });
+
+/** Removes the last question and the rows after it. Returns the question. */
+export const rewindAssistantThread = createServerFn({ method: "POST" })
+ .middleware([orgMiddleware])
+ .validator(conversationIdInput)
+ .handler(async ({ data, context }) => {
+ const { assistantService } = await import("@farmer/core/services");
+ return assistantService.replaceLastTurn(context.ctx, data);
+ });
+
+export const searchConversations = createServerFn({ method: "GET" })
+ .middleware([orgMiddleware])
+ .validator(searchConversationsInput)
+ .handler(async ({ data, context }) => {
+ const { assistantService } = await import("@farmer/core/services");
+ return assistantService.search(context.ctx, data);
+ });
+
+export const shareConversation = createServerFn({ method: "POST" })
+ .middleware([orgMiddleware])
+ .validator(conversationIdInput)
+ .handler(async ({ data, context }) => {
+ const { assistantService } = await import("@farmer/core/services");
+ return assistantService.share(context.ctx, data.conversationId);
+ });
+
+export const unshareConversation = createServerFn({ method: "POST" })
+ .middleware([orgMiddleware])
+ .validator(conversationIdInput)
+ .handler(async ({ data, context }) => {
+ const { assistantService } = await import("@farmer/core/services");
+ return assistantService.unshare(context.ctx, data.conversationId);
+ });
+
+/** A chat that its owner shared with the organization. Read only. */
+export const getSharedConversation = createServerFn({ method: "GET" })
+ .middleware([orgMiddleware])
+ .validator(conversationIdInput)
+ .handler(async ({ data, context }) => {
+ const { assistantService } = await import("@farmer/core/services");
+ return assistantService.getShared(context.ctx, data.conversationId);
+ });
diff --git a/apps/web/src/styles.css b/apps/web/src/styles.css
index b356a404..91df4b2c 100644
--- a/apps/web/src/styles.css
+++ b/apps/web/src/styles.css
@@ -2521,14 +2521,79 @@ html {
animation: shimmer-text 1.4s linear infinite;
}
- /* The pixel-grid loader's cell: a brief lift out of its resting dimness. */
- @keyframes pixel-on {
- 0%,
+ /* The assistant loader: the Farmer wheat. The stalk draws, the grains grow
+ out of it, then they drop. --i staggers the grains from base to tip. */
+ .sprout {
+ overflow: visible;
+ }
+ .sprout-stalk {
+ fill: none;
+ stroke: var(--ink);
+ stroke-width: 4;
+ stroke-linecap: round;
+ animation: sprout-draw 2600ms cubic-bezier(0.3, 0, 0.2, 1) infinite both;
+ }
+ .sprout-grain {
+ fill: var(--ink);
+ transform-box: fill-box;
+ animation: sprout-grain 2600ms infinite both;
+ animation-delay: calc(var(--i) * 150ms + 150ms);
+ }
+ /* Each grain grows from the point where it touches the stalk. */
+ .sprout-v {
+ transform-origin: 50% 0;
+ }
+ .sprout-h {
+ transform-origin: 100% 50%;
+ }
+ .sprout-leaf {
+ transform-origin: 100% 0;
+ }
+ @keyframes sprout-draw {
+ 0% {
+ stroke-dashoffset: 1;
+ }
+ 15%,
+ 78% {
+ stroke-dashoffset: 0;
+ opacity: 1;
+ }
+ 92%,
100% {
- opacity: 0.15;
+ stroke-dashoffset: 0;
+ opacity: 0;
+ }
+ }
+ @keyframes sprout-grain {
+ 0% {
+ scale: 0;
+ opacity: 1;
+ translate: 0 0;
+ rotate: 0deg;
+ }
+ 9% {
+ scale: 1.22;
}
- 35% {
- opacity: 0.85;
+ 14% {
+ scale: 0.92;
+ }
+ 18%,
+ 62% {
+ scale: 1;
+ translate: 0 0;
+ rotate: 0deg;
+ opacity: 1;
+ }
+ 76% {
+ translate: 0 12px;
+ rotate: 25deg;
+ opacity: 0;
+ animation-timing-function: steps(1);
+ }
+ 77%,
+ 100% {
+ scale: 0;
+ opacity: 0;
}
}
@@ -2580,9 +2645,8 @@ html {
transition: none;
}
/* The assistant's entrances and the loader's shimmer are narration: with
- reduced motion the content simply arrives. The loader grid stops at its
- dim resting state, which still reads as "working" because the elapsed
- timer beside it keeps counting. */
+ reduced motion the content simply arrives. The sprout loader shows the
+ full grown wheat, and the elapsed timer beside it keeps counting. */
.assistant-motion,
.assistant-motion * {
animation: none !important;
diff --git a/docs/domains/assistant.md b/docs/domains/assistant.md
index 3e53f5f5..29dc44f8 100644
--- a/docs/domains/assistant.md
+++ b/docs/domains/assistant.md
@@ -4,6 +4,7 @@ An OpenRouter-backed chat page (`$orgSlug/assistant`) that answers questions abo
- **The step ceiling ends in an ANSWER, not an error.** `MAX_STEPS` (8) is a ceiling on model round-trips, and the number is in the system prompt so most turns never reach it. A turn that does gets one more call with the tools taken away (`OUT_OF_STEPS`) — the model cannot ask for a ninth step, so it terminates, and the person gets what the eight steps found plus what is missing from it. The nudge is not stored: it is the loop talking to the model about its own ceiling, not something anyone said. Only a closing answer that is empty falls back to an error (`NO_ANSWER`).
- **A step's independent reads run together.** `runClaimedBatch` claims the leading run of `read` tools in ONE transaction and awaits them with `Promise.all`, so four lists cost one round trip and not four. Writes stay strictly in order. `AssistantTool.serial` opts a read out — `integration_status` sets it, because it can refresh an OAuth token and store it. `list_time_entries` does not: it calls `listRange` with `{ persist: false }`, which writes nothing, so two overlapping ranges cannot race. **A new read that reaches a service which writes must set `serial`**; nothing detects it, and the failure is a race.
+- **Old tool results are stubbed in the wire copy only.** `toWireMessages` calls `elideOldToolResults` (`assistant-wire.ts`): a `tool` result over `ELIDE_MIN_CHARS` (400) from before the last `KEEP_TOOL_RESULT_TURNS` (4) user messages becomes a short stub. Every `tool` row and call id stays, so the pairing rule holds. Stored rows never change, and the current turn is never stubbed. The window is a fixed count, so the prompt prefix stays the same until a new user message moves it.
- **A capped tool result is cut by ROW where the value is a list** (`MAX_TOOL_RESULT_CHARS`), never mid-object, and the note says how many rows were dropped and tells the model to narrow the call ITSELF rather than send the person back to re-ask.
- **A tool that throws tells the model only what a person may read.** The tool result goes to the model provider, so `executeTool` passes a failure's message only when `classifyServiceError` (`services/error-message.ts`) says so — a validation failure, or a class that extends `UserFacingError` (`lib/user-facing-error.ts`: an `AccessError`, a full day, a GitHub rate limit or dead installation, a refused upload, the assistant's own errors), or a bare `Error` sentence a service threw on purpose. Exposure is a property of the class, so a new error a person should read extends the base; one that can carry an address, a URL or a provider's body (`WebhookUrlRefusedError`, `OpenRouterError`, `ObjectStoreError`) does not. A database error, which carries its SQL and parameters, is logged and becomes a generic line. `executeTool` calls `agentErrorMessage`, which adds a recovery hint (`list_tasks`, `list_projects`) to a refused task or project id, as the MCP server does.
@@ -11,6 +12,10 @@ An OpenRouter-backed chat page (`$orgSlug/assistant`) that answers questions abo
- **A tool description must say what OMITTING an optional filter means.** `time_report_summary` and `time_report_detail` default `userId` to "everyone the caller may see", which for a PM, Team Lead or Admin is the whole team. The old wording ("scoped to what the caller is allowed to see") was true and read as "scoped to the caller": ten of thirteen benchmarked models answered "how many hours did I log in August" with the team total, presented as the person's own. Spelling the default out fixed it in every model that got it wrong. A number that is right for a Member and silently wrong for their manager is the failure mode to look for when adding an optional filter.
- **`toolDefinitions(access)` is scoped to the caller, and that is not the authorization.** `AssistantTool.available` only decides what the model is *told* it can do — every definition is re-sent on every step, so offering a Member the admin reports costs tokens and a step spent being refused. Keep predicates coarse ("is a PM anywhere", never "on THIS project"), because the arguments don't exist when the list is built.
- **Three tool kinds (`ToolKind`), and the line is "can they undo this by asking for the opposite".** `read` answers; `write` (logging and correcting single entries) runs inline; `destructive` (deleting an entry or a recurring rule, removing absence, archiving, unlinking commits, pull requests or a GitHub repo, clearing the hour fund, discarding the timer) suspends for approval.
+- **An inline write can be undone from its trace row.** A tool sets `AssistantTool.undo` only where the inverse is exact and cheap: `create_time_entry` (delete the entry), `update_time_entry`, `update_entry_description` and `set_overtime` (restore the old fields). `executeTool` reads the old state before the write and stores the inverse and the entry's new `updatedAt` on the `tool` row (`undo`, `assistantMessage`). `assistantService.undo` claims the row with `undone_at`, so two tabs run it once. It refuses when the entry's `updatedAt` is no longer the stored one (`UndoStaleError`). It runs the inverse through `timeEntriesService`, never through the model. The wire copy of an undone row says `"undone": true`, also after `elideOldToolResults`. The snapshot is read just before the write, not in its transaction, because a tool calls the service with its own transaction. No undo for the timer tools (the stopped entry and the running timer cannot be restored exactly), `copy_day`, `attach_commits` and `attach_pull_requests` (a detach tombstone is permanent), `sync_now`, and the writes that ask for approval.
+- **Chat search covers the caller's own chats only.** `assistantService.search` matches the title and the text of `user` and `assistant` rows, not `tool` rows, which hold raw data and not words a person wrote. It escapes `%` and `_` and declares the escape character, as `ledger.ts` does. It returns at most 30 chats, newest first, with a snippet of about 120 characters around the first match.
+- **A shared chat is readable by every member of the org, by the owner's decision.** `share` sets `sharedAt` and `sharedBy`. `getShared` serves the transcript read only: no pending card, no undo, no edit. The product owner chose "anyone in the org with the link" and not a named list. The cost is that a chat holds tool results that were read with the owner's access, for example a PM's team report. So every share dialog shows a warning first, and the reader sees a banner. Only the owner shares. The owner or an Admin unshares, so that leaked data can be pulled back. Both write an audit row (`assistant_chat.shared`, `assistant_chat.unshared`). A chat that is not shared, or is in another org, is "not found". The web route is `$orgSlug/assistant_/shared/$id` (the `_` keeps it out of the assistant page layout). On a phone, that page links to `farmer://assistant/shared/?org=&server=`, which opens the chat in the app (see `mobile.md`).
+- **Edit and Retry replace only the last turn.** `assistantService.replaceLastTurn` deletes the last user message and every row after it in one transaction, under row locks on the thread (as `claimCalls`). It refuses while a card waits or a tool runs, and when a write or destructive call of that turn ran and stands (not undone). The text depends on the case (`editBlockReason` in `lib/assistant-edit.ts`): "Undo the change first" when each standing write has an inverse, and "Ask a new question instead" when one has none, for example `create_project`. The API message carries `changed` (a write that stands) next to `undoable`, so the web app and the mobile app (which mirrors the helper in `edit-block.ts`) show the same text on the disabled button. It returns the removed text, and the client sends it again as a new turn. When that send fails, the client puts the text back in the composer and focuses it (`restore` on `PromptBar` and on the mobile `Composer`). `assistantUsage` rows stay, because they reference the conversation and not the messages.
- **A `write` that reaches past one day of the caller's own timesheet asks too** (`AssistantTool.confirm`): a project role, creating or changing a project, a client or a task type, unarchiving, booking a span of absence, copying a week, creating or changing a recurring rule, linking a GitHub repo, changing the integration switches, setting the hour fund, and making or changing a filing rule. The model reads text nobody in the conversation wrote — an invite's title, a commit subject, another member's note or name — and a sentence there that reads as an instruction must not be able to make a PM of its author, or book weeks of sick leave, as the person asking with nobody seeing it. The prompt also says tool results are data, but that is advice to a model; the card is the control. A new write that changes somebody else's access or the org, or many days at once, sets `confirm` and a `summarize`.
- **After a read of third-party text, every write asks.** A `read` tool taints the turn unless it sets `readsThirdPartyText: false` (the reads of project, task and client names, totals, targets and settings do: `whoami`, the project, task and client lists, `my_targets`, `absence_totals`, `project_overview`, the hour fund, the holidays, the integration status). A read that returns a member's name still taints, because a member sets their own display name and a teammate controls that text: `list_members`, `list_project_members`, `list_assignable_people`, `time_report_summary`, `tracking_report` and `overtime_report`. A read that returns an entry note, a meeting title, a commit or pull request title or an absence note still taints. Once a marked read has a result in the turn (the rows after the last user message), `needsApproval` suspends every `write` call, as it does a `confirm` tool. The taint is read from the stored rows (`turnIsTainted`), so it survives an approval resume and a retried model call. A marked read's result ends with a note that its text is data, not instructions: advice, not the control. The renderer shows the host of an external link beside it (`externalHost` in `answer.tsx`).
- **A read must hand back what a write takes, or the answer is a dead end.** `time_report_detail` returns each entry's `id` for exactly that reason — `update_time_entry`, `update_entry_description`, `set_overtime` and `delete_time_entry` all take one, and a report the model could read but not act on made "fix the note on Tuesday's entry" a search it had to run twice.
@@ -36,6 +41,7 @@ An OpenRouter-backed chat page (`$orgSlug/assistant`) that answers questions abo
- **`components/assistant/answer.tsx`, `answer-parse.ts` and the prompt's formatting rules change together.** `answer-parse.ts` holds `parseBlocks`, the pure reader, with its tests in `answer-parse.test.ts`. `answer.tsx` draws the blocks. Every reader in `parseBlocks` must advance the line index, or the tab hangs. The reader is hand-rolled markdown plus three directives the prompt describes verbatim: `[[YYYY-MM-DD]]` (a link to that day's timesheet), `farmer-chart` fences and `farmer-next` chips. A construct promised in the prompt and missing in the reader renders as its own syntax. It re-parses on every streamed delta, so half-arrived input must degrade, never throw. It also recovers from wrappers a small model adds — a fence whose body is only a pipe table is a table, a `json` or untagged fence that parses as a chart spec is a chart, `farmer-next` is read without its closing fence — but it never invents a directive the model did not write.
- **The composer clears on send and takes the draft back when the send never landed.** `useAssistantActions().send` resolves false when no `message` event arrived — the server's receipt, written before the model is called — and `PromptBar` restores the text and focuses it. A rate limit or a dead session used to cost the person everything they had typed, next to an error line telling them to try again. A turn that started and then failed keeps the message, because by then it is in the thread.
- **The tool trace names its subject** (`ToolTraceList`, `toolDetail` in `components/assistant/primitives.tsx`): `tool_start` carries the call's raw arguments and the CLIENT decides the wording, beside `toolLabel`. A column of four identical "Read time entries" says nothing about what was read. **The ids in those arguments are resolved to names client-side** — `userId` to a face and a name from `directoryQuery`, and `projectId`/`clientId`/`taskId` from their own lists — because a report filtered per person is otherwise six rows reading the same date range. Each list is fetched only once a trace row actually carries that kind of id, so an ordinary turn costs no extra request; an id whose name has not arrived is left out rather than printed raw.
+- **Ask from any page.** `ask-assistant.tsx` binds Cmd+K or Ctrl+K in the `/$orgSlug` layout, only when the assistant is available. Send starts a new chat in the run store. A chip shows one sentence from `page-context.ts` (built from the URL only), and the person may remove it before sending. The empty chat takes its questions from `suggestions.ts`, built on the client from the targets, entries, unfiled and calendar queries.
- **A turn the person stops keeps what it already wrote.** The read loop in `lib/openrouter-client.ts` had a `finally` and no `catch`, so the rejection `read()` raises when the signal fires carried every token of a half-written answer out with it — Stop, or navigating away, threw away work the org had paid for and left the thread looking as though nothing had been asked. It now returns the partial turn under `finishReason: ABORTED`, and `assistant.service.ts` stores the text **with `toolCalls` set to null**: a stored `tool_calls` row with no `tool` result under it 400s every later request in that thread, and the calls were never run. An empty partial stores nothing and reports nothing — a cancelled turn is not a failure to explain. The client settles the same way it settles a finished turn (`settle` in `assistant-runs.tsx`), or the live half-answer would sit beside the stored one.
- **A turn belongs to a THREAD, and the run store is keyed on the conversation** (`components/assistant/assistant-runs.tsx`, mounted by the `/$orgSlug` layout). The streamed text, the tool traces, the pending card and the error all live per conversation id, so opening a second thread does not show it the first one's answer, and two threads run side by side — one turn at a time PER CONVERSATION, not per person. It is above the route rather than on the page for two reasons that are one: the thread list is in the SIDEBAR, which the page does not contain, so nothing on the page could tell it a thread is working; and a turn then survives navigation, so asking a long question and going to look at your timesheet finds the answer waiting. Three contexts, not one — the rail reads `useAssistantRunning()` (the ids, which change twice a turn) rather than the run map (which changes per token).
- **A stream that ends with no finish reason, or with an error frame, is a failed call, not an answer.** After the 200 is committed, OpenRouter reports an upstream failure as an SSE frame with a top-level `error: { code, message }` and `finish_reason: "error"`, then ends the stream. The parser reads that object and carries it on `OpenRouterStreamCutError.upstream`, and the error message holds the code and the text, for the log and PostHog only. The finish reason `"error"` with no object fails the same way. An upstream can also close a slow call with no frame and no `finish_reason`. In production two calls ran for 120 s, carried no tokens and were reported as a success. `streamChatCompletion` now throws `OpenRouterStreamCutError` when the stream ends, the signal has not fired and no finish reason came. The error carries `partial`, the `ChatTurn` that arrived. A close with the signal already fired is still `ABORTED`. `generate` reports the call with the error message (for example `"stream ended without a finish reason"`) plus the tokens, cost and text that arrived, so PostHog shows `$ai_is_error`. The loop keeps the partial TEXT under the rule for a stop (`keepPartial`) and drops the partial tool calls, which never ran and would leave a `tool_calls` row with no result. The person gets `STREAM_CUT`, not `done` and not `NO_ANSWER`, and never the provider's text. The loop does not retry the call: a retry bills the same prompt again. Tool calls that look whole are not trusted, because the close can come before the last argument fragment. The 180 s timeout is unchanged, and it is a cut too: when it fires mid-body, the body read rejects with a `TimeoutError`, not an `AbortError`. If the caller's signal has not fired, that throws `OpenRouterStreamCutError` with the partial turn and the message `stream timed out before a finish reason`. A deadline that fires before the headers throws the same error with an empty partial turn and the message `request timed out before the response headers`. The person gets `TIMED_OUT` ("took too long ... try a narrower question") in place of `STREAM_CUT`, because a retry of the same prompt likely times out again. `generate` writes every cut to the server log as `[assistant] stream cut`, with the trace id, conversation id, model and step. Before this change an empty cut ended in `NO_ANSWER`, and a cut with text or tool calls was stored and run as a normal turn.
@@ -52,8 +58,9 @@ An OpenRouter-backed chat page (`$orgSlug/assistant`) that answers questions abo
- **The turn streams over a server ROUTE** (`routes/api/assistant/stream.ts`), because a `createServerFn` resolves to one value. The REST API streams the same turn for the mobile app (`api/v1/orgs/$orgSlug/assistant/threads/$id/messages` and `.../approvals`, through `apiStreamRoute`). Both routes call `streamAssistantTurn` (`server/assistant-stream.ts`), which holds the rate limit, the telemetry sink and the stream, so the two cannot drift. It is rate-limited per user (`server/assistant-rate-limit.ts`), since each turn spends the org's key; it stops the model loop when the client disconnects, sets `X-Accel-Buffering: no`, and passes only the app's own error classes to the browser. While a turn runs, `streamAssistantTurn` sends an SSE comment line (`: heartbeat`, `lib/sse-heartbeat.ts`) every 20 s, because a turn can be silent for longer than the host's `idleTimeout` (255 s, `server.ts`) when a model thinks, a call stalls and is retried, and a tool is slow. The client reads only `data:` lines, so the comment is not an event. The `finally` of the stream stops the timer on every exit path, and a client abort stops it too. `lib/openrouter-client.ts` passes its own long timeout, because `externalFetch`'s 15s deadline covers the whole request and would cut a streamed answer mid-sentence.
- **Three switches, all different.** `ASSISTANT_ENABLED=false` (env, default on) takes the feature off the deployment: no nav row, no route, a 404 from the stream endpoint, and every service path refused — except `settings.disconnect`, so a key stays removable. `assistantSettings.enabled` is an admin pausing it for one org. A missing `assistantSettings` row is "never connected". `$orgSlug/route.tsx` resolves `assistantAvailable` from all three for both navs, so a paused org has no Chat tab leading to an explanation; the route still explains itself to someone who typed the URL.
- **Model choice is admin-only.** A conversation pins `assistantSettings.defaultModel` when it starts (`createConversationInput` carries no `model`), so changing the default never re-answers an old thread.
-- The OpenRouter key is per-org, set by an admin under Settings → Workspace → Integrations, and follows the Slack bot token's rule — sealed at rest (`lib/secret-box.ts`), opened only in `loadSettings`, never returned. A key that does not decrypt (a changed `BETTER_AUTH_SECRET`) is its own state, not "never connected": `settings.get` answers `configured: false` with `keyUnreadable: true`, so the nav drops the Chat tab, the assistant page says the key must be pasted again rather than offering a composer whose every message throws, and Settings → Workspace → Integrations badges the row "Connect again" and says why. Saving a key again is the fix. `settings.get` answers with a leading-characters hint, since the tail is the unguessable part.
+- The OpenRouter key is per-org, set by an admin under Settings → AI (`settings/ai.tsx`), and follows the Slack bot token's rule — sealed at rest (`lib/secret-box.ts`), opened only in `loadSettings`, never returned. A key that does not decrypt (a changed `BETTER_AUTH_SECRET`) is its own state, not "never connected": `settings.get` answers `configured: false` with `keyUnreadable: true`, so the nav drops the Chat tab, the assistant page says the key must be pasted again rather than offering a composer whose every message throws, and Settings → AI badges the row "Connect again" and says why. Saving a key again is the fix. `settings.get` answers with a leading-characters hint, since the tail is the unguessable part.
- **What a turn cost is reported through a seam, not to a vendor** — `services/ai-telemetry.ts`, beside `ports.ts` and `notify.ts` and for the same reason: `packages/core` must stay runnable from a process with no analytics in it, so the default sink drops every event and the worker, the CLI's API and the test suite run the identical loop. `apps/web/src/lib/posthog-ai.ts` is the only adapter, installed once by the stream route, and it renames a generation to `$ai_generation` and a tool run to `$ai_span`. **Nothing in there may throw or wait**: an answer somebody is waiting for does not get slower because a metric is in flight. Core hands the content over whole and the ADAPTER decides what leaves the process, because that is a deployment's decision and belongs next to the credentials it is made with.
+- **The usage ledger is `assistantUsage`: one row per billed call, with its cost.** `generate` in `assistant.service.ts` writes it beside each `AiGeneration` (a turn step, the retry and the title call), not through the telemetry sink. The cost is null when the call has no usage row (a stalled attempt): the view counts it as unknown, not as zero. A failed insert is logged and never fails the turn. `userId` has no foreign key and `conversationId` is set null, so a removed person or a deleted thread keeps its cost. `assistantUsageService.summary` (admin only) sums in SQL per organization, person and model, and Settings → AI shows it. Older turns have no cost.
- **A generation's `tool_calls` are what PostHog counts as tool usage, not the `$ai_span` events beside it.** PostHog extracts the tool names from the RESPONSE at ingestion time and writes `$ai_tools_called` and `$ai_tool_call_count` on the generation; `$ai_tools` is only what the model was OFFERED. So `AiGeneration` carries the whole `toolCalls` array rather than a list of names, and `posthog-ai.ts` puts it on `$ai_output_choices` in the OpenAI shape. Without it the Tools tab reads empty on an app that calls tools constantly — the spans are there, and nothing aggregates them. The tool NAME rides either way, as this app's own vocabulary; `arguments` goes behind `POSTHOG_AI_CAPTURE_CONTENT` with the rest of the content.
- The transcript's swap, scroll pinning and wide-table bleed (`FadeSwap`, `PinToEnd`, `.answer-wide`) are explained at their call sites in `assistant.tsx` and `styles.css`.
diff --git a/docs/domains/integrations.md b/docs/domains/integrations.md
index 5b54cde0..68a6c561 100644
--- a/docs/domains/integrations.md
+++ b/docs/domains/integrations.md
@@ -1,6 +1,6 @@
# Integrations (GitHub + Google Calendar + Slack)
-GitHub and Google Calendar are per-member and opt-in via `integrationSettings` (a missing row = every toggle off, so connecting an account never silently enables background sync); Slack is per-org and admin-only. A person's own connections live on `$orgSlug/settings/integrations` (Account → Integrations, beside the MCP and CLI instructions); the workspace's GitHub App installations, Slack and the assistant's key live on `$orgSlug/settings/workspace-integrations` (Workspace → Integrations, admin-only through `requireOrgAdmin`). The two are split by scope, the same split the settings hub draws for every other page. The GitHub and Calendar token helpers check the `account` table first and return null when nothing is linked, rather than letting better-auth throw.
+GitHub and Google Calendar are per-member and opt-in via `integrationSettings` (a missing row = every toggle off, so connecting an account never silently enables background sync); Slack is per-org and admin-only. A person's own connections live on `$orgSlug/settings/integrations` (Account → Integrations, beside the MCP and CLI instructions); the workspace's GitHub App installations and Slack live on `$orgSlug/settings/workspace-integrations` (Workspace → Integrations, admin-only through `requireOrgAdmin`); the assistant's OpenRouter key lives on `$orgSlug/settings/ai` (Settings → AI). The two are split by scope, the same split the settings hub draws for every other page. The GitHub and Calendar token helpers check the `account` table first and return null when nothing is linked, rather than letting better-auth throw.
- **GitHub uses two distinct credential types, don't conflate them.** The per-user OAuth account link (`socialProviders.github`) is used **only for identity** — `GET /user` (resolve the login, to filter activity by author) and `GET /user/installations` (enumerate installations the person may connect). All repo, commit and pull request reads go through a **per-org GitHub App installation token** (`orgGithubInstallation`), obtained after an admin installs the App and GitHub redirects to `api/github/setup.ts`, which re-verifies admin role and resolves the org from a signed `state` (`lib/oauth-state.ts`: org, user and issue time, expiring after 15 minutes). The Slack callback refuses any request without a valid state. GitHub setup reads the active org only when no state was sent at all, because an App installed from GitHub's own UI arrives that way — and then connects nothing: a crafted link arrives the same way, so the installation id only goes on to Workspace → Integrations (`?githubInstallation=`), where the admin confirms it through the `connectGithubInstallation` POST server function, which names the workspace the page showed and is refused when the session's active one has moved. `connectInstallation` still re-verifies that the caller owns the installation's GitHub account (see the next point). Repo reads are scoped to the caller: `attachCommits` requires an assignment on each repo's project and a hex `sha`, `attachPullRequests` holds the same assignment line before any GitHub call, `suggestCommits` and `suggestPullRequests` read only the repos of projects the caller is assigned to, `listLinkedRepos` needs `canTrackOn` on the project and answers an empty list to a non-admin with no assignment on it (so the entry dialog never offers a commit picker that cannot fill), and listing every repo the App reaches, linking a repo and unlinking one are admin-only in the service itself. Settings: `GITHUB_CLIENT_ID/SECRET` (OAuth) are separate from `GITHUB_APP_ID/SLUG/PRIVATE_KEY` (the App). The private key is the PEM or its base64; `appPrivateKeyPem` tells them apart by the `-----BEGIN` line, because the environment has always held the base64 and the Infrastructure page takes the file as pasted. The cached App JWT is keyed by the App ID and the key, so a change on the page is not answered with a token of the App before it.
- **Only the owner of a GitHub account can connect its installation.** `connectInstallation` checks two things. First, the installation must be in `GET /user/installations`. GitHub lists an installation there for anybody with explicit read access to one repo it covers, so this check proves only that the caller can see it. Second, the caller must own the account the installation is on (`assertControlsAccount`): a personal account must be the caller, compared by GitHub's numeric user id, and an organization must answer `GET /orgs/{org}/memberships/{login}` with `state: "active"`, `role: "admin"` (an organization owner) and the caller's own numeric id. The user token only says who the caller is (`GET /user`); the membership is read with the installation's own token, so the check does not depend on what `GITHUB_CLIENT_ID` is, an OAuth app or a GitHub App. Any failure of that membership read is a refusal, and each kind (no permission or not a member, not an owner, a pending invitation, GitHub unreachable) has its own sentence. Without the second check, an outside collaborator could bind a company's installation to a workspace of their own and list every private repo it covers through the installation token. An organization member who is not an owner cannot connect, so an owner must do it.
diff --git a/docs/domains/mobile.md b/docs/domains/mobile.md
index 001f40e4..c885829f 100644
--- a/docs/domains/mobile.md
+++ b/docs/domains/mobile.md
@@ -521,3 +521,7 @@ account. Change each item in this list to your own value:
Run `rg -n 'com\.profico\.farmer'` to find every place. The store secrets
for the workflow `mobile-release.yml` are your own too.
+
+## Shared chat link
+
+A shared chat opens in the app through `farmer://assistant/shared/?org=&server=`. The web page shows an "Open in the app" link on a phone. The app compares `org` and `server` with the signed-in workspace and shows a message on a mismatch. A signed-out app drops the link, because the signed-in screens are protected.
diff --git a/packages/api-client/openapi.json b/packages/api-client/openapi.json
index 35e9b65d..add764b9 100644
--- a/packages/api-client/openapi.json
+++ b/packages/api-client/openapi.json
@@ -6560,6 +6560,8 @@
"org_settings.updated",
"reminder_settings.updated",
"assistant_settings.updated",
+ "assistant_chat.shared",
+ "assistant_chat.unshared",
"audit_log.retention_changed",
"audit_log.exported",
"member.invited",
@@ -7423,6 +7425,286 @@
}
}
},
+ "/orgs/{orgSlug}/assistant/threads/search": {
+ "get": {
+ "operationId": "searchAssistantThreads",
+ "summary": "Search your threads",
+ "description": "Matches the title and the text of the questions and answers, not the tool results. `q` has 2 to 100 characters. At most 30 threads, newest first.",
+ "tags": [
+ "Assistant"
+ ],
+ "parameters": [
+ {
+ "name": "orgSlug",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "description": "The organization's slug, from `GET /me`."
+ },
+ {
+ "name": "q",
+ "in": "query",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 2,
+ "maxLength": 100
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/AssistantSearchHit"
+ }
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "No token, or a bad or expired one.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "The input is not valid.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "429": {
+ "description": "Too many requests.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/orgs/{orgSlug}/assistant/threads/{id}/share": {
+ "post": {
+ "operationId": "shareAssistantThread",
+ "summary": "Share a thread",
+ "description": "Anyone in the organization with the link can read the thread. It can show data that the owner can see and the reader cannot. Only the owner may share. Another person's thread is a 404.",
+ "tags": [
+ "Assistant"
+ ],
+ "parameters": [
+ {
+ "name": "orgSlug",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "description": "The organization's slug, from `GET /me`."
+ },
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "description": "The row's id."
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AssistantShare"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "No token, or a bad or expired one.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Not allowed, or a read-only API token.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "429": {
+ "description": "Too many requests.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "operationId": "unshareAssistantThread",
+ "summary": "Stop sharing a thread",
+ "description": "The owner may. An Admin may stop any shared thread. Any other caller, and a thread that is not shared, is a 404.",
+ "tags": [
+ "Assistant"
+ ],
+ "parameters": [
+ {
+ "name": "orgSlug",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "description": "The organization's slug, from `GET /me`."
+ },
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "description": "The row's id."
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AssistantShare"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "No token, or a bad or expired one.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Not allowed, or a read-only API token.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "429": {
+ "description": "Too many requests.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/orgs/{orgSlug}/assistant/shared-threads/{id}": {
+ "get": {
+ "operationId": "getSharedAssistantThread",
+ "summary": "Read a shared thread",
+ "description": "Any member may read a thread that its owner shared. Read only, and only the questions and the answers: no tool results. A thread that is not shared, or is in another organization, is a 404.",
+ "tags": [
+ "Assistant"
+ ],
+ "parameters": [
+ {
+ "name": "orgSlug",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "description": "The organization's slug, from `GET /me`."
+ },
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "description": "The row's id."
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AssistantSharedThread"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "No token, or a bad or expired one.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "429": {
+ "description": "Too many requests.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/orgs/{orgSlug}/assistant/threads/{id}": {
"get": {
"operationId": "getAssistantThread",
@@ -7457,13 +7739,171 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/AssistantThreadDetail"
+ "$ref": "#/components/schemas/AssistantThreadDetail"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "No token, or a bad or expired one.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "429": {
+ "description": "Too many requests.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ }
+ }
+ },
+ "patch": {
+ "operationId": "renameAssistantThread",
+ "summary": "Rename a thread",
+ "tags": [
+ "Assistant"
+ ],
+ "parameters": [
+ {
+ "name": "orgSlug",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "description": "The organization's slug, from `GET /me`."
+ },
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "description": "The row's id."
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AssistantThreadRename"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "OK",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AssistantThread"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "No token, or a bad or expired one.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Not allowed, or a read-only API token.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "The input is not valid.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "429": {
+ "description": "Too many requests.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "operationId": "deleteAssistantThread",
+ "summary": "Delete a thread",
+ "tags": [
+ "Assistant"
+ ],
+ "parameters": [
+ {
+ "name": "orgSlug",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "description": "The organization's slug, from `GET /me`."
+ },
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "description": "The row's id."
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Deleted"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "No token, or a bad or expired one.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
}
}
}
},
- "401": {
- "description": "No token, or a bad or expired one.",
+ "403": {
+ "description": "Not allowed, or a read-only API token.",
"content": {
"application/json": {
"schema": {
@@ -7483,10 +7923,13 @@
}
}
}
- },
- "patch": {
- "operationId": "renameAssistantThread",
- "summary": "Rename a thread",
+ }
+ },
+ "/orgs/{orgSlug}/assistant/threads/{id}/messages": {
+ "post": {
+ "operationId": "sendAssistantMessage",
+ "summary": "Send a message",
+ "description": "Streams the answer as Server-Sent Events. A message sent while an approval waits declines it. Each person can start 20 turns a minute.",
"tags": [
"Assistant"
],
@@ -7515,18 +7958,18 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/AssistantThreadRename"
+ "$ref": "#/components/schemas/AssistantSend"
}
}
}
},
"responses": {
"200": {
- "description": "OK",
+ "description": "A stream of Server-Sent Events. Each `data:` line is one event, as JSON.",
"content": {
- "application/json": {
+ "text/event-stream": {
"schema": {
- "$ref": "#/components/schemas/AssistantThread"
+ "$ref": "#/components/schemas/AssistantEvent"
}
}
}
@@ -7572,10 +8015,13 @@
}
}
}
- },
- "delete": {
- "operationId": "deleteAssistantThread",
- "summary": "Delete a thread",
+ }
+ },
+ "/orgs/{orgSlug}/assistant/threads/{id}/approvals": {
+ "post": {
+ "operationId": "answerAssistantApproval",
+ "summary": "Approve or reject a write",
+ "description": "Answers the call that `approval_required` named, and streams the rest of the turn. For a batch, `selectedRowIds` keeps only those rows; an empty list rejects. An approval counts as a turn.",
"tags": [
"Assistant"
],
@@ -7599,13 +8045,23 @@
"description": "The row's id."
}
],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AssistantApproval"
+ }
+ }
+ }
+ },
"responses": {
"200": {
- "description": "OK",
+ "description": "A stream of Server-Sent Events. Each `data:` line is one event, as JSON.",
"content": {
- "application/json": {
+ "text/event-stream": {
"schema": {
- "$ref": "#/components/schemas/Deleted"
+ "$ref": "#/components/schemas/AssistantEvent"
}
}
}
@@ -7630,6 +8086,16 @@
}
}
},
+ "422": {
+ "description": "The input is not valid.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
"429": {
"description": "Too many requests.",
"content": {
@@ -7643,11 +8109,11 @@
}
}
},
- "/orgs/{orgSlug}/assistant/threads/{id}/messages": {
+ "/orgs/{orgSlug}/assistant/threads/{id}/messages/{messageId}/undo": {
"post": {
- "operationId": "sendAssistantMessage",
- "summary": "Send a message",
- "description": "Streams the answer as Server-Sent Events. A message sent while an approval waits declines it. Each person can start 20 turns a minute.",
+ "operationId": "undoAssistantWrite",
+ "summary": "Undo a write",
+ "description": "Undoes the write of a `tool` row with `undoable`. 422 when the write cannot be undone, such as when the entry changed since. Returns the row.",
"tags": [
"Assistant"
],
@@ -7669,25 +8135,24 @@
"type": "string"
},
"description": "The row's id."
+ },
+ {
+ "name": "messageId",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "description": "The row's id."
}
],
- "requestBody": {
- "required": true,
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/AssistantSend"
- }
- }
- }
- },
"responses": {
"200": {
- "description": "A stream of Server-Sent Events. Each `data:` line is one event, as JSON.",
+ "description": "OK",
"content": {
- "text/event-stream": {
+ "application/json": {
"schema": {
- "$ref": "#/components/schemas/AssistantEvent"
+ "$ref": "#/components/schemas/AssistantMessage"
}
}
}
@@ -7712,16 +8177,6 @@
}
}
},
- "422": {
- "description": "The input is not valid.",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/Error"
- }
- }
- }
- },
"429": {
"description": "Too many requests.",
"content": {
@@ -7735,11 +8190,11 @@
}
}
},
- "/orgs/{orgSlug}/assistant/threads/{id}/approvals": {
+ "/orgs/{orgSlug}/assistant/threads/{id}/rewind": {
"post": {
- "operationId": "answerAssistantApproval",
- "summary": "Approve or reject a write",
- "description": "Answers the call that `approval_required` named, and streams the rest of the turn. For a batch, `selectedRowIds` keeps only those rows; an empty list rejects. An approval counts as a turn.",
+ "operationId": "rewindAssistantThread",
+ "summary": "Take back the last question",
+ "description": "Removes the last question and the rows after it, then returns the question text. Send it again, edited or not, as a new message. 422 while a card waits, and after a write that was not undone.",
"tags": [
"Assistant"
],
@@ -7763,23 +8218,13 @@
"description": "The row's id."
}
],
- "requestBody": {
- "required": true,
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/AssistantApproval"
- }
- }
- }
- },
"responses": {
"200": {
- "description": "A stream of Server-Sent Events. Each `data:` line is one event, as JSON.",
+ "description": "OK",
"content": {
- "text/event-stream": {
+ "application/json": {
"schema": {
- "$ref": "#/components/schemas/AssistantEvent"
+ "$ref": "#/components/schemas/AssistantRewind"
}
}
}
@@ -7804,16 +8249,6 @@
}
}
},
- "422": {
- "description": "The input is not valid.",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/Error"
- }
- }
- }
- },
"429": {
"description": "Too many requests.",
"content": {
@@ -16907,13 +17342,75 @@
"updatedAt": {
"type": "string",
"description": "An instant, ISO 8601 in UTC."
+ },
+ "sharedAt": {
+ "anyOf": [
+ {
+ "type": "string",
+ "description": "An instant, ISO 8601 in UTC."
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "When the owner shared the thread. Null: not shared."
}
},
"required": [
"id",
"title",
"model",
- "updatedAt"
+ "updatedAt",
+ "sharedAt"
+ ]
+ },
+ "AssistantSearchHit": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "A UUID."
+ },
+ "title": {
+ "type": "string"
+ },
+ "updatedAt": {
+ "type": "string",
+ "description": "An instant, ISO 8601 in UTC."
+ },
+ "snippet": {
+ "description": "About 120 characters of plain text around the first match. Null when only the title matched.",
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "id",
+ "title",
+ "updatedAt",
+ "snippet"
+ ]
+ },
+ "AssistantShare": {
+ "type": "object",
+ "properties": {
+ "sharedAt": {
+ "anyOf": [
+ {
+ "type": "string",
+ "description": "An instant, ISO 8601 in UTC."
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Null after the share stopped."
+ }
+ },
+ "required": [
+ "sharedAt"
]
},
"AssistantMessage": {
@@ -17055,6 +17552,18 @@
}
]
},
+ "undoable": {
+ "type": "boolean",
+ "description": "A `tool` row whose write can still be undone: `POST …/messages/{messageId}/undo`."
+ },
+ "undone": {
+ "type": "boolean",
+ "description": "The person undid this write."
+ },
+ "changed": {
+ "type": "boolean",
+ "description": "A `tool` row whose write ran and still stands, undoable or not."
+ },
"createdAt": {
"type": "string",
"description": "An instant, ISO 8601 in UTC."
@@ -17071,9 +17580,24 @@
"approvalDecision",
"approvalSummary",
"approvalPreview",
+ "undoable",
+ "undone",
+ "changed",
"createdAt"
]
},
+ "AssistantRewind": {
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "string",
+ "description": "The text of the removed question, to send again."
+ }
+ },
+ "required": [
+ "content"
+ ]
+ },
"AssistantThreadDetail": {
"type": "object",
"properties": {
@@ -17086,11 +17610,82 @@
"$ref": "#/components/schemas/AssistantMessage"
},
"description": "Oldest first."
+ },
+ "promptTokens": {
+ "anyOf": [
+ {
+ "type": "integer",
+ "minimum": -9007199254740991,
+ "maximum": 9007199254740991
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Prompt tokens of the last model call."
+ },
+ "contextLength": {
+ "anyOf": [
+ {
+ "type": "integer",
+ "minimum": -9007199254740991,
+ "maximum": 9007199254740991
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Context size of the thread's model."
+ }
+ },
+ "required": [
+ "thread",
+ "messages",
+ "promptTokens",
+ "contextLength"
+ ]
+ },
+ "AssistantSharedThread": {
+ "type": "object",
+ "properties": {
+ "thread": {
+ "$ref": "#/components/schemas/AssistantThread"
+ },
+ "messages": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/AssistantMessage"
+ },
+ "description": "Oldest first."
+ },
+ "sharedAt": {
+ "type": "string",
+ "description": "An instant, ISO 8601 in UTC."
+ },
+ "sharedBy": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "image": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "name",
+ "image"
+ ]
}
},
"required": [
"thread",
- "messages"
+ "messages",
+ "sharedAt",
+ "sharedBy"
]
},
"AssistantEvent": {
@@ -19767,6 +20362,8 @@
"org_settings.updated",
"reminder_settings.updated",
"assistant_settings.updated",
+ "assistant_chat.shared",
+ "assistant_chat.unshared",
"audit_log.retention_changed",
"audit_log.exported",
"member.invited",
diff --git a/packages/api-client/src/client.ts b/packages/api-client/src/client.ts
index 3bbebd12..c8e346a5 100644
--- a/packages/api-client/src/client.ts
+++ b/packages/api-client/src/client.ts
@@ -106,6 +106,11 @@ import {
import {
assistantModelSchema,
assistantSettingsSchema,
+ assistantMessageSchema,
+ assistantRewindSchema,
+ assistantSearchHitSchema,
+ assistantSharedThreadSchema,
+ assistantShareSchema,
assistantThreadDetailSchema,
assistantThreadSchema,
} from "./schemas-assistant";
@@ -1464,6 +1469,45 @@ export class FarmerClient {
);
}
+ /** Search your threads. */
+ searchAssistantThreads(
+ slug: string,
+ query: QueryOf<"searchAssistantThreads">,
+ ) {
+ return this.#request(
+ "GET",
+ orgPath(slug, `/assistant/threads/search${search(query)}`),
+ assistantSearchHitSchema.array(),
+ );
+ }
+
+ /** Share a thread with the organization. */
+ shareAssistantThread(slug: string, id: string) {
+ return this.#request(
+ "POST",
+ orgPath(slug, `/assistant/threads/${encodeURIComponent(id)}/share`),
+ assistantShareSchema,
+ );
+ }
+
+ /** Stop sharing a thread. */
+ unshareAssistantThread(slug: string, id: string) {
+ return this.#request(
+ "DELETE",
+ orgPath(slug, `/assistant/threads/${encodeURIComponent(id)}/share`),
+ assistantShareSchema,
+ );
+ }
+
+ /** Read a shared thread. */
+ getSharedAssistantThread(slug: string, id: string) {
+ return this.#request(
+ "GET",
+ orgPath(slug, `/assistant/shared-threads/${encodeURIComponent(id)}`),
+ assistantSharedThreadSchema,
+ );
+ }
+
/** Start a thread. */
createAssistantThread(slug: string, body: NewAssistantThread) {
return this.#request(
@@ -1530,6 +1574,27 @@ export class FarmerClient {
);
}
+ /** Undo a write. */
+ undoAssistantWrite(slug: string, id: string, messageId: string) {
+ return this.#request(
+ "POST",
+ orgPath(
+ slug,
+ `/assistant/threads/${encodeURIComponent(id)}/messages/${encodeURIComponent(messageId)}/undo`,
+ ),
+ assistantMessageSchema,
+ );
+ }
+
+ /** Take back the last question. */
+ rewindAssistantThread(slug: string, id: string) {
+ return this.#request(
+ "POST",
+ orgPath(slug, `/assistant/threads/${encodeURIComponent(id)}/rewind`),
+ assistantRewindSchema,
+ );
+ }
+
/** One assistant turn as a stream of events. A non-2xx answer throws
* before the first event, as every other call does. */
diff --git a/packages/api-client/src/openapi.gen.ts b/packages/api-client/src/openapi.gen.ts
index a31014a9..4b422241 100644
--- a/packages/api-client/src/openapi.gen.ts
+++ b/packages/api-client/src/openapi.gen.ts
@@ -1561,6 +1561,70 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/orgs/{orgSlug}/assistant/threads/search": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /**
+ * Search your threads
+ * @description Matches the title and the text of the questions and answers, not the tool results. `q` has 2 to 100 characters. At most 30 threads, newest first.
+ */
+ get: operations["searchAssistantThreads"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/orgs/{orgSlug}/assistant/threads/{id}/share": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /**
+ * Share a thread
+ * @description Anyone in the organization with the link can read the thread. It can show data that the owner can see and the reader cannot. Only the owner may share. Another person's thread is a 404.
+ */
+ post: operations["shareAssistantThread"];
+ /**
+ * Stop sharing a thread
+ * @description The owner may. An Admin may stop any shared thread. Any other caller, and a thread that is not shared, is a 404.
+ */
+ delete: operations["unshareAssistantThread"];
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/orgs/{orgSlug}/assistant/shared-threads/{id}": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /**
+ * Read a shared thread
+ * @description Any member may read a thread that its owner shared. Read only, and only the questions and the answers: no tool results. A thread that is not shared, or is in another organization, is a 404.
+ */
+ get: operations["getSharedAssistantThread"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/orgs/{orgSlug}/assistant/threads/{id}": {
parameters: {
query?: never;
@@ -1623,6 +1687,46 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/orgs/{orgSlug}/assistant/threads/{id}/messages/{messageId}/undo": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /**
+ * Undo a write
+ * @description Undoes the write of a `tool` row with `undoable`. 422 when the write cannot be undone, such as when the entry changed since. Returns the row.
+ */
+ post: operations["undoAssistantWrite"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/orgs/{orgSlug}/assistant/threads/{id}/rewind": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /**
+ * Take back the last question
+ * @description Removes the last question and the rows after it, then returns the question text. Send it again, edited or not, as a new message. 422 while a card waits, and after a write that was not undone.
+ */
+ post: operations["rewindAssistantThread"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/orgs/{orgSlug}/projects/{id}": {
parameters: {
query?: never;
@@ -3753,6 +3857,21 @@ export interface components {
model: string;
/** @description An instant, ISO 8601 in UTC. */
updatedAt: string;
+ /** @description When the owner shared the thread. Null: not shared. */
+ sharedAt: string | null;
+ };
+ AssistantSearchHit: {
+ /** @description A UUID. */
+ id: string;
+ title: string;
+ /** @description An instant, ISO 8601 in UTC. */
+ updatedAt: string;
+ /** @description About 120 characters of plain text around the first match. Null when only the title matched. */
+ snippet: string | null;
+ };
+ AssistantShare: {
+ /** @description Null after the share stopped. */
+ sharedAt: string | null;
};
AssistantMessage: {
/** @description A UUID. */
@@ -3782,13 +3901,38 @@ export interface components {
note: string | null;
selectable: boolean;
} | null;
+ /** @description A `tool` row whose write can still be undone: `POST …/messages/{messageId}/undo`. */
+ undoable: boolean;
+ /** @description The person undid this write. */
+ undone: boolean;
+ /** @description A `tool` row whose write ran and still stands, undoable or not. */
+ changed: boolean;
/** @description An instant, ISO 8601 in UTC. */
createdAt: string;
};
+ AssistantRewind: {
+ /** @description The text of the removed question, to send again. */
+ content: string;
+ };
AssistantThreadDetail: {
thread: components["schemas"]["AssistantThread"];
/** @description Oldest first. */
messages: components["schemas"]["AssistantMessage"][];
+ /** @description Prompt tokens of the last model call. */
+ promptTokens: number | null;
+ /** @description Context size of the thread's model. */
+ contextLength: number | null;
+ };
+ AssistantSharedThread: {
+ thread: components["schemas"]["AssistantThread"];
+ /** @description Oldest first. */
+ messages: components["schemas"]["AssistantMessage"][];
+ /** @description An instant, ISO 8601 in UTC. */
+ sharedAt: string;
+ sharedBy: {
+ name: string;
+ image: string | null;
+ };
};
/** @description One Server-Sent Event: each `data:` line is one of these, as JSON. The turn ends after `done` or `error`. */
AssistantEvent: {
@@ -4430,7 +4574,7 @@ export interface components {
/** @enum {string} */
category?: "change" | "security";
/** @enum {string} */
- kind?: "organization.created" | "organization.updated" | "org_settings.updated" | "reminder_settings.updated" | "assistant_settings.updated" | "audit_log.retention_changed" | "audit_log.exported" | "member.invited" | "member.invitation_cancelled" | "member.invitation_declined" | "member.joined" | "member.removed" | "member.claim_declined" | "member.claim_merged" | "member.role_changed" | "member.archived" | "member.restored" | "member.anonymised" | "member.type_changed" | "member.start_date_changed" | "member.email_confirmed" | "team_lead.people_changed" | "client.created" | "client.updated" | "client.archived" | "client.restored" | "project.created" | "project.updated" | "project.archived" | "project.restored" | "project.member_assigned" | "project.member_removed" | "task.created" | "task.updated" | "task.archived" | "task.restored" | "hour_fund.set" | "hour_fund.cleared" | "hour_fund.prefilled" | "holiday.disabled" | "holiday.enabled" | "absence.logged_for_person" | "absence.changed_for_person" | "absence.removed_for_person" | "webhook.created" | "webhook.updated" | "webhook.deleted" | "webhook.secret_rolled" | "github.connected" | "github.disconnected" | "github.repo_linked" | "github.repo_unlinked" | "slack.connected" | "slack.disconnected" | "slack.pinged" | "import.finished" | "import.undone" | "auth.signed_in" | "auth.sign_in_failed" | "auth.signed_out" | "session.revoked" | "account.linked" | "account.unlinked" | "api_token.created" | "api_token.revoked" | "impersonation.started" | "impersonation.stopped";
+ kind?: "organization.created" | "organization.updated" | "org_settings.updated" | "reminder_settings.updated" | "assistant_settings.updated" | "assistant_chat.shared" | "assistant_chat.unshared" | "audit_log.retention_changed" | "audit_log.exported" | "member.invited" | "member.invitation_cancelled" | "member.invitation_declined" | "member.joined" | "member.removed" | "member.claim_declined" | "member.claim_merged" | "member.role_changed" | "member.archived" | "member.restored" | "member.anonymised" | "member.type_changed" | "member.start_date_changed" | "member.email_confirmed" | "team_lead.people_changed" | "client.created" | "client.updated" | "client.archived" | "client.restored" | "project.created" | "project.updated" | "project.archived" | "project.restored" | "project.member_assigned" | "project.member_removed" | "task.created" | "task.updated" | "task.archived" | "task.restored" | "hour_fund.set" | "hour_fund.cleared" | "hour_fund.prefilled" | "holiday.disabled" | "holiday.enabled" | "absence.logged_for_person" | "absence.changed_for_person" | "absence.removed_for_person" | "webhook.created" | "webhook.updated" | "webhook.deleted" | "webhook.secret_rolled" | "github.connected" | "github.disconnected" | "github.repo_linked" | "github.repo_unlinked" | "slack.connected" | "slack.disconnected" | "slack.pinged" | "import.finished" | "import.undone" | "auth.signed_in" | "auth.sign_in_failed" | "auth.signed_out" | "session.revoked" | "account.linked" | "account.unlinked" | "api_token.created" | "api_token.revoked" | "impersonation.started" | "impersonation.stopped";
userId?: string;
from: string;
to: string;
@@ -9383,7 +9527,7 @@ export interface operations {
parameters: {
query?: {
category?: "change" | "security";
- kind?: "organization.created" | "organization.updated" | "org_settings.updated" | "reminder_settings.updated" | "assistant_settings.updated" | "audit_log.retention_changed" | "audit_log.exported" | "member.invited" | "member.invitation_cancelled" | "member.invitation_declined" | "member.joined" | "member.removed" | "member.claim_declined" | "member.claim_merged" | "member.role_changed" | "member.archived" | "member.restored" | "member.anonymised" | "member.type_changed" | "member.start_date_changed" | "member.email_confirmed" | "team_lead.people_changed" | "client.created" | "client.updated" | "client.archived" | "client.restored" | "project.created" | "project.updated" | "project.archived" | "project.restored" | "project.member_assigned" | "project.member_removed" | "task.created" | "task.updated" | "task.archived" | "task.restored" | "hour_fund.set" | "hour_fund.cleared" | "hour_fund.prefilled" | "holiday.disabled" | "holiday.enabled" | "absence.logged_for_person" | "absence.changed_for_person" | "absence.removed_for_person" | "webhook.created" | "webhook.updated" | "webhook.deleted" | "webhook.secret_rolled" | "github.connected" | "github.disconnected" | "github.repo_linked" | "github.repo_unlinked" | "slack.connected" | "slack.disconnected" | "slack.pinged" | "import.finished" | "import.undone" | "auth.signed_in" | "auth.sign_in_failed" | "auth.signed_out" | "session.revoked" | "account.linked" | "account.unlinked" | "api_token.created" | "api_token.revoked" | "impersonation.started" | "impersonation.stopped";
+ kind?: "organization.created" | "organization.updated" | "org_settings.updated" | "reminder_settings.updated" | "assistant_settings.updated" | "assistant_chat.shared" | "assistant_chat.unshared" | "audit_log.retention_changed" | "audit_log.exported" | "member.invited" | "member.invitation_cancelled" | "member.invitation_declined" | "member.joined" | "member.removed" | "member.claim_declined" | "member.claim_merged" | "member.role_changed" | "member.archived" | "member.restored" | "member.anonymised" | "member.type_changed" | "member.start_date_changed" | "member.email_confirmed" | "team_lead.people_changed" | "client.created" | "client.updated" | "client.archived" | "client.restored" | "project.created" | "project.updated" | "project.archived" | "project.restored" | "project.member_assigned" | "project.member_removed" | "task.created" | "task.updated" | "task.archived" | "task.restored" | "hour_fund.set" | "hour_fund.cleared" | "hour_fund.prefilled" | "holiday.disabled" | "holiday.enabled" | "absence.logged_for_person" | "absence.changed_for_person" | "absence.removed_for_person" | "webhook.created" | "webhook.updated" | "webhook.deleted" | "webhook.secret_rolled" | "github.connected" | "github.disconnected" | "github.repo_linked" | "github.repo_unlinked" | "slack.connected" | "slack.disconnected" | "slack.pinged" | "import.finished" | "import.undone" | "auth.signed_in" | "auth.sign_in_failed" | "auth.signed_out" | "session.revoked" | "account.linked" | "account.unlinked" | "api_token.created" | "api_token.revoked" | "impersonation.started" | "impersonation.stopped";
userId?: string;
from?: string;
to?: string;
@@ -9992,6 +10136,205 @@ export interface operations {
};
};
};
+ searchAssistantThreads: {
+ parameters: {
+ query: {
+ q: string;
+ };
+ header?: never;
+ path: {
+ /** @description The organization's slug, from `GET /me`. */
+ orgSlug: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description OK */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["AssistantSearchHit"][];
+ };
+ };
+ /** @description No token, or a bad or expired one. */
+ 401: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
+ /** @description The input is not valid. */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
+ /** @description Too many requests. */
+ 429: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
+ };
+ };
+ shareAssistantThread: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ /** @description The organization's slug, from `GET /me`. */
+ orgSlug: string;
+ /** @description The row's id. */
+ id: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description OK */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["AssistantShare"];
+ };
+ };
+ /** @description No token, or a bad or expired one. */
+ 401: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
+ /** @description Not allowed, or a read-only API token. */
+ 403: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
+ /** @description Too many requests. */
+ 429: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
+ };
+ };
+ unshareAssistantThread: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ /** @description The organization's slug, from `GET /me`. */
+ orgSlug: string;
+ /** @description The row's id. */
+ id: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description OK */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["AssistantShare"];
+ };
+ };
+ /** @description No token, or a bad or expired one. */
+ 401: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
+ /** @description Not allowed, or a read-only API token. */
+ 403: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
+ /** @description Too many requests. */
+ 429: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
+ };
+ };
+ getSharedAssistantThread: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ /** @description The organization's slug, from `GET /me`. */
+ orgSlug: string;
+ /** @description The row's id. */
+ id: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description OK */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["AssistantSharedThread"];
+ };
+ };
+ /** @description No token, or a bad or expired one. */
+ 401: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
+ /** @description Too many requests. */
+ 429: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
+ };
+ };
getAssistantThread: {
parameters: {
query?: never;
@@ -10282,6 +10625,112 @@ export interface operations {
};
};
};
+ undoAssistantWrite: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ /** @description The organization's slug, from `GET /me`. */
+ orgSlug: string;
+ /** @description The row's id. */
+ id: string;
+ /** @description The row's id. */
+ messageId: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description OK */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["AssistantMessage"];
+ };
+ };
+ /** @description No token, or a bad or expired one. */
+ 401: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
+ /** @description Not allowed, or a read-only API token. */
+ 403: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
+ /** @description Too many requests. */
+ 429: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
+ };
+ };
+ rewindAssistantThread: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ /** @description The organization's slug, from `GET /me`. */
+ orgSlug: string;
+ /** @description The row's id. */
+ id: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description OK */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["AssistantRewind"];
+ };
+ };
+ /** @description No token, or a bad or expired one. */
+ 401: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
+ /** @description Not allowed, or a read-only API token. */
+ 403: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
+ /** @description Too many requests. */
+ 429: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
+ };
+ };
getProject: {
parameters: {
query?: never;
diff --git a/packages/api-client/src/schemas-assistant.ts b/packages/api-client/src/schemas-assistant.ts
index 15f4816f..138c5bca 100644
--- a/packages/api-client/src/schemas-assistant.ts
+++ b/packages/api-client/src/schemas-assistant.ts
@@ -48,9 +48,26 @@ export const assistantThreadSchema = z.object({
model: z.string(),
/** An instant, ISO 8601 in UTC. */
updatedAt: z.string(),
+ /** When the owner shared the thread. Null: not shared. */
+ sharedAt: z.string().nullable(),
});
export type AssistantThread = z.output;
+export const assistantSearchHitSchema = z.object({
+ id: z.string(),
+ title: z.string(),
+ updatedAt: z.string(),
+ /** Plain text around the first match. Null when only the title matched. */
+ snippet: z.string().nullable(),
+});
+export type AssistantSearchHit = z.output;
+
+export const assistantShareSchema = z.object({
+ /** Null after the share stopped. */
+ sharedAt: z.string().nullable(),
+});
+export type AssistantShare = z.output;
+
export const assistantMessageSchema = z.object({
id: z.string(),
role: z.string(),
@@ -88,20 +105,48 @@ export const assistantMessageSchema = z.object({
selectable: z.boolean(),
})
.nullable(),
+ /** A `tool` row whose write can still be undone. */
+ undoable: z.boolean(),
+ /** The person undid this write. */
+ undone: z.boolean(),
+ /** A `tool` row whose write ran and still stands. */
+ changed: z.boolean(),
/** An instant, ISO 8601 in UTC. */
createdAt: z.string(),
});
export type AssistantMessage = z.output;
+export const assistantRewindSchema = z.object({
+ /** The text of the removed question, to send again. */
+ content: z.string(),
+});
+export type AssistantRewind = z.output;
+
export const assistantThreadDetailSchema = z.object({
thread: assistantThreadSchema,
/** Oldest first. */
messages: z.array(assistantMessageSchema),
+ /** Prompt tokens of the last model call. Null before the first answer. */
+ promptTokens: z.number().nullable(),
+ /** Context size of the thread's model. Null when unknown. */
+ contextLength: z.number().nullable(),
});
export type AssistantThreadDetail = z.output<
typeof assistantThreadDetailSchema
>;
+export const assistantSharedThreadSchema = z.object({
+ thread: assistantThreadSchema,
+ /** Oldest first. */
+ messages: z.array(assistantMessageSchema),
+ /** An instant, ISO 8601 in UTC. */
+ sharedAt: z.string(),
+ sharedBy: z.object({ name: z.string(), image: z.string().nullable() }),
+});
+export type AssistantSharedThread = z.output<
+ typeof assistantSharedThreadSchema
+>;
+
/**
* One Server-Sent Event: each `data:` line is one of these, as JSON. The turn
* ends after `done` or `error`.
@@ -169,6 +214,14 @@ export type AssistantContractChecks = [
Expect>,
Expect>,
Expect>,
+ Expect>,
+ Expect<
+ Parses
+ >,
+ Expect>,
+ Expect<
+ Parses
+ >,
Expect<
Parses
>,
diff --git a/packages/core/drizzle/0084_married_solo.sql b/packages/core/drizzle/0084_married_solo.sql
new file mode 100644
index 00000000..fb82aeac
--- /dev/null
+++ b/packages/core/drizzle/0084_married_solo.sql
@@ -0,0 +1,19 @@
+CREATE TABLE "assistant_usage" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "organization_id" text NOT NULL,
+ "user_id" text NOT NULL,
+ "conversation_id" uuid,
+ "model" text NOT NULL,
+ "served_model" text,
+ "kind" text NOT NULL,
+ "attempt" integer NOT NULL,
+ "prompt_tokens" integer,
+ "completion_tokens" integer,
+ "cost_usd" numeric(14, 8),
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+ALTER TABLE "assistant_usage" ADD CONSTRAINT "assistant_usage_organization_id_organization_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organization"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "assistant_usage" ADD CONSTRAINT "assistant_usage_conversation_id_assistant_conversation_id_fk" FOREIGN KEY ("conversation_id") REFERENCES "public"."assistant_conversation"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
+CREATE INDEX "assistant_usage_org_created_idx" ON "assistant_usage" USING btree ("organization_id","created_at");--> statement-breakpoint
+CREATE INDEX "assistant_usage_org_user_created_idx" ON "assistant_usage" USING btree ("organization_id","user_id","created_at");
\ No newline at end of file
diff --git a/packages/core/drizzle/0085_uneven_polaris.sql b/packages/core/drizzle/0085_uneven_polaris.sql
new file mode 100644
index 00000000..a17e44de
--- /dev/null
+++ b/packages/core/drizzle/0085_uneven_polaris.sql
@@ -0,0 +1,2 @@
+ALTER TABLE "assistant_message" ADD COLUMN "undo" jsonb;--> statement-breakpoint
+ALTER TABLE "assistant_message" ADD COLUMN "undone_at" timestamp with time zone;
\ No newline at end of file
diff --git a/packages/core/drizzle/0086_nostalgic_zaladane.sql b/packages/core/drizzle/0086_nostalgic_zaladane.sql
new file mode 100644
index 00000000..3253e8b5
--- /dev/null
+++ b/packages/core/drizzle/0086_nostalgic_zaladane.sql
@@ -0,0 +1,3 @@
+ALTER TABLE "assistant_conversation" ADD COLUMN "shared_at" timestamp with time zone;--> statement-breakpoint
+ALTER TABLE "assistant_conversation" ADD COLUMN "shared_by" text;--> statement-breakpoint
+ALTER TABLE "assistant_conversation" ADD CONSTRAINT "assistant_conversation_shared_by_user_id_fk" FOREIGN KEY ("shared_by") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;
\ No newline at end of file
diff --git a/packages/core/drizzle/meta/0083_snapshot.json b/packages/core/drizzle/meta/0086_snapshot.json
similarity index 97%
rename from packages/core/drizzle/meta/0083_snapshot.json
rename to packages/core/drizzle/meta/0086_snapshot.json
index e5491515..ccd7a5ea 100644
--- a/packages/core/drizzle/meta/0083_snapshot.json
+++ b/packages/core/drizzle/meta/0086_snapshot.json
@@ -1,6 +1,6 @@
{
- "id": "1f03650c-9b1c-4274-8f6a-0ef7bbd92521",
- "prevId": "044f51aa-e1b5-427c-9d74-7551912b2db6",
+ "id": "f9e67da2-d3fb-43ad-a433-fb0b0dec9174",
+ "prevId": "6cd7f929-fdf2-4c42-af1b-fbd9d8c02ecb",
"version": "7",
"dialect": "postgresql",
"tables": {
@@ -171,6 +171,18 @@
"primaryKey": false,
"notNull": true
},
+ "shared_at": {
+ "name": "shared_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "shared_by": {
+ "name": "shared_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
@@ -241,6 +253,19 @@
],
"onDelete": "cascade",
"onUpdate": "no action"
+ },
+ "assistant_conversation_shared_by_user_id_fk": {
+ "name": "assistant_conversation_shared_by_user_id_fk",
+ "tableFrom": "assistant_conversation",
+ "tableTo": "user",
+ "columnsFrom": [
+ "shared_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
@@ -328,6 +353,18 @@
"primaryKey": false,
"notNull": false
},
+ "undo": {
+ "name": "undo",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "undone_at": {
+ "name": "undone_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
"model": {
"name": "model",
"type": "text",
@@ -518,6 +555,169 @@
"checkConstraints": {},
"isRLSEnabled": false
},
+ "public.assistant_usage": {
+ "name": "assistant_usage",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "conversation_id": {
+ "name": "conversation_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "served_model": {
+ "name": "served_model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "attempt": {
+ "name": "attempt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "prompt_tokens": {
+ "name": "prompt_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "completion_tokens": {
+ "name": "completion_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "numeric(14, 8)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "assistant_usage_org_created_idx": {
+ "name": "assistant_usage_org_created_idx",
+ "columns": [
+ {
+ "expression": "organization_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "assistant_usage_org_user_created_idx": {
+ "name": "assistant_usage_org_user_created_idx",
+ "columns": [
+ {
+ "expression": "organization_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "assistant_usage_organization_id_organization_id_fk": {
+ "name": "assistant_usage_organization_id_organization_id_fk",
+ "tableFrom": "assistant_usage",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "assistant_usage_conversation_id_assistant_conversation_id_fk": {
+ "name": "assistant_usage_conversation_id_assistant_conversation_id_fk",
+ "tableFrom": "assistant_usage",
+ "tableTo": "assistant_conversation",
+ "columnsFrom": [
+ "conversation_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
"public.audit_event": {
"name": "audit_event",
"schema": "",
diff --git a/packages/core/drizzle/meta/_journal.json b/packages/core/drizzle/meta/_journal.json
index 325d2801..de0177d0 100644
--- a/packages/core/drizzle/meta/_journal.json
+++ b/packages/core/drizzle/meta/_journal.json
@@ -589,6 +589,27 @@
"when": 1794231768774,
"tag": "0083_supreme_hellion",
"breakpoints": true
+ },
+ {
+ "idx": 84,
+ "version": "7",
+ "when": 1794427085271,
+ "tag": "0084_married_solo",
+ "breakpoints": true
+ },
+ {
+ "idx": 85,
+ "version": "7",
+ "when": 1794427729591,
+ "tag": "0085_uneven_polaris",
+ "breakpoints": true
+ },
+ {
+ "idx": 86,
+ "version": "7",
+ "when": 1794428658709,
+ "tag": "0086_nostalgic_zaladane",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/core/src/api/assistant.test.ts b/packages/core/src/api/assistant.test.ts
index 0724ed52..374954f3 100644
--- a/packages/core/src/api/assistant.test.ts
+++ b/packages/core/src/api/assistant.test.ts
@@ -50,12 +50,14 @@ describe("toApiAssistantThread", () => {
model: "openai/gpt-4o-mini",
createdAt: AT,
updatedAt: AT,
+ sharedAt: AT,
};
expect(toApiAssistantThread(row)).toStrictEqual({
id: "t-1",
title: "Hours in August",
model: "openai/gpt-4o-mini",
updatedAt: "2026-10-06T08:00:00.000Z",
+ sharedAt: "2026-10-06T08:00:00.000Z",
});
});
});
@@ -73,6 +75,8 @@ describe("toApiAssistantMessage", () => {
approvalDecision: null,
approvalSummary: null,
approvalPreview: null,
+ undo: null,
+ undoneAt: null,
model: "openai/gpt-4o-mini",
promptTokens: 120,
completionTokens: 30,
@@ -108,6 +112,9 @@ describe("toApiAssistantMessage", () => {
note: null,
selectable: true,
},
+ undoable: false,
+ undone: false,
+ changed: false,
createdAt: "2026-10-06T08:00:00.000Z",
});
});
diff --git a/packages/core/src/api/assistant.ts b/packages/core/src/api/assistant.ts
index 603af676..34eee263 100644
--- a/packages/core/src/api/assistant.ts
+++ b/packages/core/src/api/assistant.ts
@@ -78,6 +78,9 @@ export type ApiAssistantThread = {
/** The model the thread was pinned to when it started. */
model: string;
updatedAt: string;
+ /** When the owner shared the thread with the organization. Null: not
+ * shared. */
+ sharedAt: string | null;
};
export const toApiAssistantThread = (row: {
@@ -85,11 +88,35 @@ export const toApiAssistantThread = (row: {
title: string;
model: string;
updatedAt: Date;
+ sharedAt: Date | null;
}): ApiAssistantThread => ({
id: row.id,
title: row.title,
model: row.model,
updatedAt: row.updatedAt.toISOString(),
+ sharedAt: row.sharedAt ? row.sharedAt.toISOString() : null,
+});
+
+/** One hit of `GET …/assistant/threads/search`. */
+export type ApiAssistantSearchHit = {
+ id: string;
+ title: string;
+ updatedAt: string;
+ /** About 120 characters of plain text around the first match in a
+ * message. Null when only the title matched. */
+ snippet: string | null;
+};
+
+export const toApiAssistantSearchHit = (row: {
+ id: string;
+ title: string;
+ updatedAt: Date;
+ snippet: string | null;
+}): ApiAssistantSearchHit => ({
+ id: row.id,
+ title: row.title,
+ updatedAt: row.updatedAt.toISOString(),
+ snippet: row.snippet,
});
export type ApiAssistantToolCall = {
@@ -128,6 +155,13 @@ export type ApiAssistantMessage = {
/** The sentence the approval card showed. */
approvalSummary: string | null;
approvalPreview: ApiApprovalPreview | null;
+ /** A `tool` row whose write can still be undone:
+ * `POST …/messages/$messageId/undo`. */
+ undoable: boolean;
+ /** The person undid this write. */
+ undone: boolean;
+ /** A `tool` row whose write ran and still stands, undoable or not. */
+ changed: boolean;
createdAt: string;
};
@@ -157,6 +191,10 @@ export const toApiAssistantMessage = (row: {
note?: string;
selectable?: boolean;
} | null;
+ undo: object | null;
+ undoneAt: Date | null;
+ /** Absent on a read-only view, which offers no edit. */
+ changed?: boolean;
createdAt: Date;
}): ApiAssistantMessage => ({
id: row.id,
@@ -186,13 +224,41 @@ export const toApiAssistantMessage = (row: {
selectable: row.approvalPreview.selectable ?? false,
}
: null,
+ undoable: row.undo !== null && row.undoneAt === null,
+ undone: row.undoneAt !== null,
+ changed: row.changed ?? false,
createdAt: row.createdAt.toISOString(),
});
+/** `POST …/threads/$id/rewind`: the removed question, to send again. */
+export type ApiAssistantRewind = { content: string };
+
/** `GET /api/v1/orgs/$slug/assistant/threads/$id`. Messages oldest first. */
export type ApiAssistantThreadDetail = {
thread: ApiAssistantThread;
messages: ApiAssistantMessage[];
+ /** Prompt tokens of the last model call. Null before the first answer. */
+ promptTokens: number | null;
+ /** Context size of the thread's model. Null when unknown. */
+ contextLength: number | null;
+};
+
+/** `POST` and `DELETE …/threads/$id/share`. */
+export type ApiAssistantShare = {
+ /** Null after the share stopped. */
+ sharedAt: string | null;
+};
+
+/**
+ * `GET /api/v1/orgs/$slug/assistant/shared-threads/$id`: a chat that its owner
+ * shared with the organization. Read only: no approval waits, nothing can be
+ * undone.
+ */
+export type ApiAssistantSharedThread = {
+ thread: ApiAssistantThread;
+ messages: ApiAssistantMessage[];
+ sharedAt: string;
+ sharedBy: { name: string; image: string | null };
};
/**
diff --git a/packages/core/src/db/schema/assistant.ts b/packages/core/src/db/schema/assistant.ts
index f0a1f088..45818cf2 100644
--- a/packages/core/src/db/schema/assistant.ts
+++ b/packages/core/src/db/schema/assistant.ts
@@ -4,6 +4,7 @@ import {
index,
integer,
jsonb,
+ numeric,
pgTable,
text,
timestamp,
@@ -69,10 +70,10 @@ export const assistantSettings = pgTable(
(t) => [unique("assistant_settings_org_unq").on(t.organizationId)],
);
-// A conversation belongs to ONE person in ONE org. There is deliberately no
-// sharing: the assistant answers through the caller's own Ctx, so two people
-// asking the same question can legitimately get different answers, and a shared
-// thread would show a Member the PM's view of it.
+// A conversation belongs to ONE person in ONE org. Only the owner can write to
+// it. The owner may share it read-only with the org (`sharedAt`): anyone in the
+// org can read it. Tool results in it were read with the owner's access, so the
+// share dialog warns about that.
export const assistantConversation = pgTable(
"assistant_conversation",
{
@@ -85,6 +86,12 @@ export const assistantConversation = pgTable(
title: text("title").notNull().default("New chat"),
/** Pinned at creation from `assistantSettings.defaultModel`. */
model: text("model").notNull(),
+ /** When the owner shared the chat with the org. Null: not shared. */
+ sharedAt: ts("shared_at"),
+ /** Who shared it. Set and cleared with `sharedAt`. */
+ sharedBy: text("shared_by").references(() => user.id, {
+ onDelete: "set null",
+ }),
...stamps,
},
(t) => [
@@ -106,6 +113,40 @@ export type AssistantToolCall = {
arguments: string;
};
+/** The fields of a time entry that `update` writes, as they were. */
+export type UndoEntryFields = {
+ projectId: string | null;
+ taskId: string;
+ date: string;
+ description: string;
+ durationSeconds: number;
+ overtime: boolean;
+ fillsDay: boolean;
+};
+
+/** The exact inverse of one inline write. `updatedAt` is the entry's value
+ * right after the write (ISO): the undo runs only if it is still that. */
+export type AssistantUndo =
+ | { kind: "delete_entry"; entryId: string; updatedAt: string }
+ | {
+ kind: "restore_entry";
+ entryId: string;
+ updatedAt: string;
+ before: UndoEntryFields;
+ }
+ | {
+ kind: "restore_description";
+ entryId: string;
+ updatedAt: string;
+ description: string;
+ }
+ | {
+ kind: "restore_overtime";
+ entryId: string;
+ updatedAt: string;
+ overtime: boolean;
+ };
+
export const assistantMessage = pgTable(
"assistant_message",
{
@@ -155,6 +196,9 @@ export const assistantMessage = pgTable(
* first rendered did, rather than the way today's code would. */
selectable?: boolean;
}>(),
+ /** Set on a `tool` row of a write that can be undone. */
+ undo: jsonb("undo").$type(),
+ undoneAt: ts("undone_at"),
model: text("model"),
promptTokens: integer("prompt_tokens"),
completionTokens: integer("completion_tokens"),
@@ -168,6 +212,40 @@ export const assistantMessage = pgTable(
],
);
+// One row per billed model call, written beside each `AiGeneration`. The cost
+// is null when the call has no usage row (a stalled attempt): unknown, not zero.
+// `userId` has no foreign key and `conversationId` is set null, so a removed
+// person or a deleted thread keeps its cost.
+export const assistantUsage = pgTable(
+ "assistant_usage",
+ {
+ id: uuid("id").primaryKey().defaultRandom(),
+ organizationId: org(),
+ userId: text("user_id").notNull(),
+ conversationId: uuid("conversation_id").references(
+ () => assistantConversation.id,
+ { onDelete: "set null" },
+ ),
+ /** The model id the call asked for. */
+ model: text("model").notNull(),
+ servedModel: text("served_model"),
+ kind: text("kind").notNull().$type<"turn" | "title">(),
+ attempt: integer("attempt").notNull(),
+ promptTokens: integer("prompt_tokens"),
+ completionTokens: integer("completion_tokens"),
+ costUsd: numeric("cost_usd", { precision: 14, scale: 8, mode: "number" }),
+ createdAt: ts("created_at").notNull().defaultNow(),
+ },
+ (t) => [
+ index("assistant_usage_org_created_idx").on(t.organizationId, t.createdAt),
+ index("assistant_usage_org_user_created_idx").on(
+ t.organizationId,
+ t.userId,
+ t.createdAt,
+ ),
+ ],
+);
+
export const assistantConversationRelations = relations(
assistantConversation,
({ many }) => ({ messages: many(assistantMessage) }),
diff --git a/packages/core/src/lib/assistant-edit.ts b/packages/core/src/lib/assistant-edit.ts
new file mode 100644
index 00000000..eccfbfb3
--- /dev/null
+++ b/packages/core/src/lib/assistant-edit.ts
@@ -0,0 +1,22 @@
+// Why the last question of a thread cannot be edited. Pure, so the server and
+// the web app give the same text. The mobile app mirrors it in
+// `apps/mobile/src/assistant/edit-block.ts`, as it cannot import core.
+
+export const EDIT_AFTER_UNDOABLE_CHANGE =
+ "This answer changed your data. Undo the change first, then edit.";
+
+export const EDIT_AFTER_FINAL_CHANGE =
+ "This answer changed your data, and the change cannot be undone here. Ask a new question instead.";
+
+/**
+ * The reason for a turn whose writes still stand, or null when none does.
+ * One write with no inverse makes the whole turn final.
+ */
+export const editBlockReason = (
+ standing: readonly { undoable: boolean }[],
+): string | null => {
+ if (standing.length === 0) return null;
+ return standing.every((write) => write.undoable)
+ ? EDIT_AFTER_UNDOABLE_CHANGE
+ : EDIT_AFTER_FINAL_CHANGE;
+};
diff --git a/packages/core/src/lib/audit.ts b/packages/core/src/lib/audit.ts
index 284cc8db..4054558b 100644
--- a/packages/core/src/lib/audit.ts
+++ b/packages/core/src/lib/audit.ts
@@ -71,6 +71,14 @@ export const AUDIT_KINDS = {
category: "change",
sentence: "changed the assistant settings",
},
+ "assistant_chat.shared": {
+ category: "change",
+ sentence: "shared the assistant chat {target}",
+ },
+ "assistant_chat.unshared": {
+ category: "change",
+ sentence: "stopped sharing the assistant chat {target}",
+ },
"audit_log.retention_changed": {
category: "change",
sentence: "changed how long the audit log is kept",
diff --git a/packages/core/src/lib/plain-text.test.ts b/packages/core/src/lib/plain-text.test.ts
new file mode 100644
index 00000000..2367f553
--- /dev/null
+++ b/packages/core/src/lib/plain-text.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, test } from "bun:test";
+
+import { plainText } from "./plain-text";
+
+describe("plainText", () => {
+ test("drops closed and unclosed fences", () => {
+ expect(
+ plainText('A\n```farmer-chart\n{"value":6}\n```\nB\n```farmer-next\nQ?'),
+ ).toBe("A B");
+ });
+
+ test("turns a date directive into the date", () => {
+ expect(plainText("Busiest was [[2026-11-11]].")).toBe(
+ "Busiest was 2026-11-11.",
+ );
+ });
+
+ test("strips emphasis, code ticks, links and headings", () => {
+ expect(
+ plainText("## Title\n**bold** *it* `code` [text](https://x.y/z)"),
+ ).toBe("Title bold it code text");
+ });
+
+ test("turns table pipes into spaces", () => {
+ expect(plainText("| a | b |")).toBe("a b");
+ });
+
+ test("keeps an underscore inside a word", () => {
+ expect(plainText("_it_ snake_case")).toBe("it snake_case");
+ });
+});
diff --git a/packages/core/src/lib/plain-text.ts b/packages/core/src/lib/plain-text.ts
new file mode 100644
index 00000000..35afa03d
--- /dev/null
+++ b/packages/core/src/lib/plain-text.ts
@@ -0,0 +1,12 @@
+/** A chat message as plain text: no fences, directives or markdown marks. */
+export const plainText = (markdown: string): string =>
+ markdown
+ .replace(/```[\s\S]*?(```|$)/g, " ")
+ .replace(/\[\[(\d{4}-\d{2}-\d{2})\]\]/g, "$1")
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
+ .replace(/`([^`]*)`/g, "$1")
+ .replace(/^\s{0,3}#{1,6}\s+/gm, "")
+ .replace(/\*+|(?;
// Deliberately carries no `model`. Choosing one is an admin decision made once,
-// in Settings → Integrations, and a conversation pins whatever the org default
+// in Settings → AI, and a conversation pins whatever the org default
// was when it started. An optional field here that nothing sends would be a
// caller-supplied override of that decision sitting unused until somebody found
// it — which is the same shape as every other input that quietly became a hole.
@@ -69,6 +69,12 @@ export type RenameConversationInput = z.infer;
export const conversationIdInput = z.object({ conversationId: z.uuid() });
export type ConversationIdInput = z.infer;
+/** One stored message of one of the caller's threads. */
+export const assistantMessageIdInput = z.object({
+ conversationId: z.uuid(),
+ messageId: z.uuid(),
+});
+
/** What a person types to the assistant. */
export const assistantMessageText = z.string().trim().min(1).max(10_000);
@@ -105,3 +111,11 @@ export const runAssistantInput = z
path: ["message"],
});
export type RunAssistantInput = z.infer;
+
+export const MIN_SEARCH_CHARS = 2;
+export const MAX_SEARCH_CHARS = 100;
+
+export const searchConversationsInput = z.object({
+ q: z.string().trim().min(MIN_SEARCH_CHARS).max(MAX_SEARCH_CHARS),
+});
+export type SearchConversationsInput = z.infer;
diff --git a/packages/core/src/schema/reports.ts b/packages/core/src/schema/reports.ts
index d9f2b82d..d07b2701 100644
--- a/packages/core/src/schema/reports.ts
+++ b/packages/core/src/schema/reports.ts
@@ -80,3 +80,7 @@ export type OvertimeReportInput = z.infer;
export const absenceReportInput = withRangeLimits(z.object({ ...range }));
export type AbsenceReportInput = z.infer;
+
+// The AI usage view takes the same period, under the same ceiling.
+export const assistantUsageInput = withRangeLimits(z.object({ ...range }));
+export type AssistantUsageInput = z.infer;
diff --git a/packages/core/src/services/assistant-share.test.ts b/packages/core/src/services/assistant-share.test.ts
new file mode 100644
index 00000000..0fa3074b
--- /dev/null
+++ b/packages/core/src/services/assistant-share.test.ts
@@ -0,0 +1,315 @@
+// Search across a person's chats, and sharing a chat with the organization.
+
+import {
+ afterAll,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ test,
+} from "bun:test";
+
+import { eq } from "drizzle-orm";
+
+import { db } from "../db";
+import {
+ assistantConversation,
+ assistantMessage,
+} from "../db/schema/assistant";
+import { auditEvent } from "../db/schema/audit";
+import { member, organization, user } from "../db/schema/auth";
+import { at, createTestDb, present, type TestDb } from "../test/harness";
+import { assistantService } from "./assistant.service";
+import type { Ctx } from "./types";
+
+const ORG = "org-share";
+const OTHER_ORG = "org-share-other";
+const ME = "u-share-me";
+const PEER = "u-share-peer";
+const ADMIN = "u-share-admin";
+const STRANGER = "u-share-stranger";
+
+const mine: Ctx = { organizationId: ORG, userId: ME };
+const peer: Ctx = { organizationId: ORG, userId: PEER };
+const admin: Ctx = { organizationId: ORG, userId: ADMIN };
+const stranger: Ctx = { organizationId: OTHER_ORG, userId: STRANGER };
+
+let harness: TestDb;
+
+const chat = async (
+ owner: Ctx,
+ title: string,
+ rows: { role: "user" | "assistant" | "tool"; content: string }[] = [],
+) => {
+ const row = at(
+ await db
+ .insert(assistantConversation)
+ .values({
+ organizationId: owner.organizationId,
+ userId: owner.userId,
+ title,
+ model: "test/model",
+ })
+ .returning(),
+ 0,
+ );
+ for (const [index, message] of rows.entries()) {
+ await db.insert(assistantMessage).values({
+ organizationId: owner.organizationId,
+ conversationId: row.id,
+ createdAt: new Date(2026, 0, 1, 0, 0, index),
+ ...message,
+ });
+ }
+ return row.id;
+};
+
+const auditKinds = async () =>
+ (
+ await db
+ .select({ kind: auditEvent.kind })
+ .from(auditEvent)
+ .where(eq(auditEvent.organizationId, ORG))
+ )
+ .map((row) => row.kind)
+ .sort();
+
+beforeAll(async () => {
+ harness = await createTestDb();
+ for (const id of [ORG, OTHER_ORG]) {
+ await db
+ .insert(organization)
+ .values({ id, name: id, slug: id, createdAt: new Date() });
+ }
+ const people = [
+ [ME, ORG, "member"],
+ [PEER, ORG, "member"],
+ [ADMIN, ORG, "admin"],
+ [STRANGER, OTHER_ORG, "member"],
+ ] as const;
+ for (const [id, organizationId, role] of people) {
+ await db.insert(user).values({
+ id,
+ name: id,
+ email: `${id}@example.com`,
+ emailVerified: true,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ });
+ await db.insert(member).values({
+ id: `m-${id}`,
+ organizationId,
+ userId: id,
+ role,
+ createdAt: new Date(),
+ });
+ }
+});
+
+afterAll(async () => {
+ await harness.close();
+});
+
+beforeEach(async () => {
+ await db.delete(assistantConversation);
+ await db.delete(auditEvent);
+});
+
+describe("search", () => {
+ test("matches the title and the body, ignoring case", async () => {
+ const byTitle = await chat(mine, "Budget review");
+ const byBody = await chat(mine, "Other", [
+ { role: "user", content: "How is the BUDGET for May?" },
+ ]);
+ await chat(mine, "Unrelated", [{ role: "user", content: "hello" }]);
+ const hits = await assistantService.search(mine, { q: "budget" });
+ expect(hits.map((hit) => hit.id).sort()).toEqual([byTitle, byBody].sort());
+ const body = present(
+ hits.find((hit) => hit.id === byBody),
+ "body hit",
+ );
+ expect(body.snippet).toContain("BUDGET");
+ expect(
+ present(
+ hits.find((hit) => hit.id === byTitle),
+ "title hit",
+ ).snippet,
+ ).toBeNull();
+ });
+
+ test("a snippet is plain text without fences", async () => {
+ const id = await chat(mine, "Chart", [
+ {
+ role: "assistant",
+ content:
+ '```farmer-chart\n{"value":6.5}\n```\nBusiest day was [[2026-11-11]].\n```farmer-next\nWhat next?',
+ },
+ ]);
+ const [inText, inFence] = await Promise.all([
+ assistantService.search(mine, { q: "busiest" }),
+ assistantService.search(mine, { q: "value" }),
+ ]);
+ expect(at(inText, 0).id).toBe(id);
+ expect(at(inText, 0).snippet).toBe("Busiest day was 2026-11-11.");
+ expect(at(inFence, 0).snippet).toBe("Busiest day was 2026-11-11.");
+ });
+
+ test("a snippet from a long message sits around the match", async () => {
+ const id = await chat(mine, "Long", [
+ {
+ role: "assistant",
+ content: `${"filler ".repeat(500)}the NEEDLE here${" tail".repeat(500)}`,
+ },
+ ]);
+ const [hit] = await assistantService.search(mine, { q: "needle" });
+ expect(present(hit, "hit").id).toBe(id);
+ expect(present(hit, "hit").snippet).toMatch(/^….*the NEEDLE here.*…$/);
+ expect(present(hit, "hit").snippet?.length).toBeLessThan(130);
+ });
+
+ test("never returns another person's or another org's chat", async () => {
+ await chat(peer, "Secret plan", [{ role: "user", content: "secret" }]);
+ await chat(stranger, "Secret plan", [{ role: "user", content: "secret" }]);
+ expect(await assistantService.search(mine, { q: "secret" })).toEqual([]);
+ });
+
+ test("percent and underscore are literal", async () => {
+ const percent = await chat(mine, "a", [
+ { role: "user", content: "we hit 100% today" },
+ ]);
+ await chat(mine, "b", [{ role: "user", content: "we hit 1000 today" }]);
+ await chat(mine, "c", [{ role: "user", content: "snake_case name" }]);
+ await chat(mine, "d", [{ role: "user", content: "snakeXcase name" }]);
+ const pct = await assistantService.search(mine, { q: "0%" });
+ expect(pct.map((hit) => hit.id)).toEqual([percent]);
+ const under = await assistantService.search(mine, { q: "e_c" });
+ expect(under).toHaveLength(1);
+ expect(at(under, 0).title).toBe("c");
+ });
+
+ test("the snippet comes from the earliest match", async () => {
+ await chat(mine, "Two", [
+ { role: "user", content: "first needle here" },
+ { role: "assistant", content: "second needle there" },
+ ]);
+ const hits = await assistantService.search(mine, { q: "needle" });
+ expect(hits).toHaveLength(1);
+ expect(at(hits, 0).snippet).toBe("first needle here");
+ });
+
+ test("tool rows do not match", async () => {
+ await chat(mine, "t", [
+ { role: "user", content: "show me" },
+ { role: "tool", content: "needle in a tool result" },
+ ]);
+ expect(await assistantService.search(mine, { q: "needle" })).toEqual([]);
+ });
+});
+
+describe("share", () => {
+ test("the owner shares and unshares, and each is audited", async () => {
+ const id = await chat(mine, "Team report");
+ await assistantService.share(mine, id);
+ const shared = await assistantService.conversations.get(mine, id);
+ expect(shared.conversation.sharedAt).not.toBeNull();
+ expect(shared.conversation.sharedBy).toBe(ME);
+ await assistantService.unshare(mine, id);
+ const after = await assistantService.conversations.get(mine, id);
+ expect(after.conversation.sharedAt).toBeNull();
+ expect(after.conversation.sharedBy).toBeNull();
+ expect(await auditKinds()).toEqual([
+ "assistant_chat.shared",
+ "assistant_chat.unshared",
+ ]);
+ });
+
+ test("a non-owner cannot share, and a member cannot unshare", async () => {
+ const id = await chat(mine, "Team report");
+ await expect(assistantService.share(peer, id)).rejects.toThrow(
+ "Conversation not found",
+ );
+ await assistantService.share(mine, id);
+ await expect(assistantService.unshare(peer, id)).rejects.toThrow(
+ "Conversation not found",
+ );
+ });
+
+ test("an admin can unshare any shared chat", async () => {
+ const id = await chat(mine, "Team report");
+ await assistantService.share(mine, id);
+ await assistantService.unshare(admin, id);
+ await expect(assistantService.getShared(peer, id)).rejects.toThrow(
+ "Conversation not found",
+ );
+ });
+});
+
+describe("getShared", () => {
+ test("a member reads a shared chat, read only", async () => {
+ const id = await chat(mine, "Team report", [
+ { role: "user", content: "who is late?" },
+ { role: "assistant", content: "Nobody." },
+ ]);
+ await db
+ .update(assistantMessage)
+ .set({
+ pendingApproval: true,
+ undo: {
+ kind: "delete_entry",
+ entryId: "e1",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ },
+ })
+ .where(eq(assistantMessage.conversationId, id));
+ await assistantService.share(mine, id);
+ const view = await assistantService.getShared(peer, id);
+ expect(view.messages.map((row) => row.content)).toEqual([
+ "who is late?",
+ "Nobody.",
+ ]);
+ expect(
+ view.messages.every((row) => !row.pendingApproval && !row.undo),
+ ).toBe(true);
+ expect(view.sharedBy.name).toBe(ME);
+ expect(view.sharedAt).toBeInstanceOf(Date);
+ });
+
+ test("a shared chat exposes no tool rows and no tool calls", async () => {
+ const id = await chat(mine, "Team report", [
+ { role: "user", content: "who is late?" },
+ { role: "assistant", content: "Checking." },
+ { role: "tool", content: '{"secret":"owner-only data"}' },
+ ]);
+ await db
+ .update(assistantMessage)
+ .set({
+ toolCalls: [{ id: "c1", name: "list_entries", arguments: "{}" }],
+ approvalSummary: "Delete 3 entries",
+ approvalPreview: { columns: ["a"], rows: [{ id: "r", cells: ["x"] }] },
+ })
+ .where(eq(assistantMessage.role, "assistant"));
+ await assistantService.share(mine, id);
+ const view = await assistantService.getShared(peer, id);
+ expect(view.messages.map((row) => row.role)).toEqual(["user", "assistant"]);
+ expect(
+ view.messages.every(
+ (row) =>
+ row.toolCalls === null &&
+ row.approvalSummary === null &&
+ row.approvalPreview === null,
+ ),
+ ).toBe(true);
+ expect(JSON.stringify(view)).not.toContain("owner-only data");
+ });
+
+ test("an unshared chat and another org's chat are not found", async () => {
+ const id = await chat(mine, "Private");
+ await expect(assistantService.getShared(peer, id)).rejects.toThrow(
+ "Conversation not found",
+ );
+ await assistantService.share(mine, id);
+ await expect(assistantService.getShared(stranger, id)).rejects.toThrow(
+ "Conversation not found",
+ );
+ });
+});
diff --git a/packages/core/src/services/assistant-tools.ts b/packages/core/src/services/assistant-tools.ts
index 21f26ff5..d3d4f981 100644
--- a/packages/core/src/services/assistant-tools.ts
+++ b/packages/core/src/services/assistant-tools.ts
@@ -91,6 +91,13 @@ import {
yearReportInput,
} from "../schema";
import type { Access } from "./access.service";
+import {
+ type UndoCapturer,
+ undoCreateEntry,
+ undoDescription,
+ undoOvertime,
+ undoUpdateEntry,
+} from "./assistant-undo";
import { clientsService } from "./clients.service";
import { complianceService, type PeriodTarget } from "./compliance.service";
import {
@@ -289,6 +296,13 @@ export type AssistantTool = {
* approval card (`taintsTurn` in assistant.service.ts).
*/
readsThirdPartyText?: boolean;
+ /**
+ * Captures the exact inverse of this inline `write`, so the person can undo
+ * it from the chat. Set it only where the inverse is exact and cheap.
+ * Best-effort: it runs before the write, and a failure costs the undo, never
+ * the write.
+ */
+ undo?: UndoCapturer;
/** Runs the tool. The result is stringified for the model and never
* inspected by the loop, so `Serializable | void` is the whole contract:
* domain rows with their Dates intact, or nothing at all. */
@@ -1311,6 +1325,7 @@ export const ASSISTANT_TOOLS: AssistantTool[] = [
description:
"Log a new time entry for the current user. Durations are in seconds and must be a multiple of 900 (15 minutes). Needs a taskId; needs a projectId unless it is an absence.",
schema: createTimeEntryToolInput,
+ undo: undoCreateEntry,
summarize: (_ctx, args) =>
`Log ${hours(args.durationSeconds)} on ${args.date}${
args.description ? ` — ${String(args.description).slice(0, 80)}` : ""
@@ -1324,6 +1339,7 @@ export const ASSISTANT_TOOLS: AssistantTool[] = [
description:
"Change an existing time entry of the current user. Send every field, not just the changed one. To change only the note, use update_entry_description.",
schema: updateTimeEntryToolInput,
+ undo: undoUpdateEntry,
summarize: (_ctx, args) =>
`Change an entry on ${args.date} to ${hours(args.durationSeconds)}`,
run: async (ctx, args) =>
@@ -1335,6 +1351,7 @@ export const ASSISTANT_TOOLS: AssistantTool[] = [
description:
"Change only the description of one of the current user's entries, leaving its hours, task and project alone.",
schema: updateTimeEntryDescriptionInput,
+ undo: undoDescription,
run: async (ctx, args) =>
timeEntriesService.updateDescription(
ctx,
@@ -1347,6 +1364,7 @@ export const ASSISTANT_TOOLS: AssistantTool[] = [
description:
"Flag one of the current user's entries as overtime, or clear the flag. Overtime is never inferred — somebody has to say so.",
schema: setTimeEntryOvertimeInput,
+ undo: undoOvertime,
run: async (ctx, args) =>
timeEntriesService.setOvertime(
ctx,
diff --git a/packages/core/src/services/assistant-undo.test.ts b/packages/core/src/services/assistant-undo.test.ts
new file mode 100644
index 00000000..c1843627
--- /dev/null
+++ b/packages/core/src/services/assistant-undo.test.ts
@@ -0,0 +1,504 @@
+// Undo of an inline write, and the replacement of the last turn.
+
+import {
+ afterAll,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ test,
+} from "bun:test";
+
+import { eq } from "drizzle-orm";
+
+import { db } from "../db";
+import {
+ assistantConversation,
+ assistantMessage,
+ assistantSettings,
+ assistantUsage,
+} from "../db/schema/assistant";
+import { member, organization, user } from "../db/schema/auth";
+import {
+ client,
+ project,
+ projectMember,
+ task,
+ timeEntry,
+} from "../db/schema/domain";
+import { timeEntryGithubCommit } from "../db/schema/github";
+import type { JsonRecord } from "../lib/json";
+import type { ChatMessage, ChatTurn } from "../lib/openrouter-client";
+import { at, createTestDb, present, type TestDb } from "../test/harness";
+import { assistantService, setChatModelForTests } from "./assistant.service";
+import { timeEntriesService } from "./time-entries.service";
+import type { Ctx } from "./types";
+
+const ORG = "org-undo";
+const ME = "u-undo-me";
+const OTHER = "u-undo-other";
+
+const mine: Ctx = { organizationId: ORG, userId: ME };
+const other: Ctx = { organizationId: ORG, userId: OTHER };
+
+let harness: TestDb;
+let projectId = "";
+let devTaskId = "";
+let script: ChatTurn[] = [];
+let seen: ChatMessage[][] = [];
+// Runs while the scripted model "generates", to act in the middle of a turn.
+let onGenerate: (() => Promise) | null = null;
+
+const turn = (over: Partial = {}): ChatTurn => ({
+ content: "",
+ toolCalls: [],
+ promptTokens: null,
+ completionTokens: null,
+ costUsd: null,
+ finishReason: null,
+ ...over,
+});
+
+const call = (id: string, name: string, args: JsonRecord) => ({
+ id,
+ name,
+ arguments: JSON.stringify(args),
+});
+
+const logArgs = { date: "2026-03-04", durationSeconds: 3600 };
+const createCall = (id = "c1") =>
+ call(id, "create_time_entry", {
+ ...logArgs,
+ projectId,
+ taskId: devTaskId,
+ description: "review",
+ });
+
+const ask = async (chatId: string, message: string, turns: ChatTurn[]) => {
+ script = turns;
+ await assistantService.run(
+ mine,
+ { conversationId: chatId, message },
+ () => {},
+ );
+};
+
+const toolRow = async (chatId: string) =>
+ present(
+ (
+ await db.query.assistantMessage.findMany({
+ where: eq(assistantMessage.conversationId, chatId),
+ })
+ ).find((row) => row.role === "tool"),
+ "tool row",
+ );
+
+/** A thread whose first question made one entry. */
+const loggedThread = async () => {
+ const chat = await assistantService.conversations.create(mine);
+ await assistantService.conversations.rename(mine, {
+ conversationId: chat.id,
+ title: "t",
+ });
+ await ask(chat.id, "log an hour", [
+ turn({ toolCalls: [createCall()] }),
+ turn({ content: "Done." }),
+ ]);
+ return chat.id;
+};
+
+beforeAll(async () => {
+ harness = await createTestDb();
+ setChatModelForTests({
+ streamChatCompletion: async (opts) => {
+ seen.push(opts.messages);
+ await onGenerate?.();
+ return present(script.shift(), "scripted turn");
+ },
+ listModels: async () => [],
+ verifyKey: async () => {},
+ });
+ await db
+ .insert(organization)
+ .values({ id: ORG, name: "Undo", slug: ORG, createdAt: new Date() });
+ for (const id of [ME, OTHER]) {
+ await db.insert(user).values({
+ id,
+ name: id,
+ email: `${id}@example.com`,
+ emailVerified: true,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ });
+ await db.insert(member).values({
+ id: `m-${id}`,
+ organizationId: ORG,
+ userId: id,
+ role: "member",
+ createdAt: new Date(),
+ });
+ }
+ const acme = at(
+ await db
+ .insert(client)
+ .values({ organizationId: ORG, name: "Acme" })
+ .returning(),
+ 0,
+ );
+ const proj = at(
+ await db
+ .insert(project)
+ .values({
+ organizationId: ORG,
+ clientId: acme.id,
+ name: "Product",
+ type: "product_team" as const,
+ })
+ .returning(),
+ 0,
+ );
+ projectId = proj.id;
+ await db.insert(projectMember).values({
+ organizationId: ORG,
+ projectId,
+ userId: ME,
+ role: "member",
+ active: true,
+ });
+ const dev = at(
+ await db
+ .insert(task)
+ .values({
+ organizationId: ORG,
+ name: "Development",
+ scope: "organization" as const,
+ systemKey: "development" as const,
+ })
+ .returning(),
+ 0,
+ );
+ devTaskId = dev.id;
+});
+
+afterAll(async () => {
+ setChatModelForTests(null);
+ await harness.close();
+});
+
+beforeEach(async () => {
+ script = [];
+ seen = [];
+ onGenerate = null;
+ await db.delete(assistantConversation);
+ await db.delete(assistantSettings);
+ await db.delete(timeEntry);
+ await db.insert(assistantSettings).values({
+ organizationId: ORG,
+ apiKey: "sk-or-v1-undo",
+ defaultModel: "test/model",
+ });
+});
+
+describe("undo", () => {
+ test("undoing a created entry deletes it, once", async () => {
+ const chatId = await loggedThread();
+ expect(await db.select().from(timeEntry)).toHaveLength(1);
+ const row = await toolRow(chatId);
+ expect(row.undo?.kind).toBe("delete_entry");
+
+ const result = await assistantService.undo(mine, {
+ conversationId: chatId,
+ messageId: row.id,
+ });
+ expect(result.message.id).toBe(row.id);
+ expect(result.message.changed).toBe(false);
+ expect(result.message.undoneAt).not.toBeNull();
+ expect(await db.select().from(timeEntry)).toHaveLength(0);
+ expect((await toolRow(chatId)).undoneAt).not.toBeNull();
+
+ await expect(
+ assistantService.undo(mine, {
+ conversationId: chatId,
+ messageId: row.id,
+ }),
+ ).rejects.toThrow("cannot be undone");
+ });
+
+ test("undoing an update restores the previous fields", async () => {
+ const chatId = await loggedThread();
+ const entry = at(await db.select().from(timeEntry), 0);
+ await ask(chatId, "change it", [
+ turn({
+ toolCalls: [
+ call("c2", "update_time_entry", {
+ timeEntryId: entry.id,
+ date: "2026-03-05",
+ projectId,
+ taskId: devTaskId,
+ durationSeconds: 7200,
+ description: "changed",
+ }),
+ ],
+ }),
+ turn({ content: "Changed." }),
+ ]);
+ const changed = at(await db.select().from(timeEntry), 0);
+ expect(changed.durationSeconds).toBe(7200);
+
+ const rows = await db.query.assistantMessage.findMany({
+ where: eq(assistantMessage.conversationId, chatId),
+ });
+ const updateRow = present(
+ rows.find((r) => r.toolName === "update_time_entry"),
+ "update row",
+ );
+ await assistantService.undo(mine, {
+ conversationId: chatId,
+ messageId: updateRow.id,
+ });
+ const restored = at(await db.select().from(timeEntry), 0);
+ expect(restored.durationSeconds).toBe(3600);
+ expect(restored.date).toBe("2026-03-04");
+ expect(restored.description).toBe("review");
+ });
+
+ test("undo is refused after the entry changed", async () => {
+ const chatId = await loggedThread();
+ const entry = at(await db.select().from(timeEntry), 0);
+ await timeEntriesService.updateDescription(mine, {
+ timeEntryId: entry.id,
+ description: "edited by hand",
+ });
+ const row = await toolRow(chatId);
+ await expect(
+ assistantService.undo(mine, {
+ conversationId: chatId,
+ messageId: row.id,
+ }),
+ ).rejects.toThrow("changed since");
+ expect(await db.select().from(timeEntry)).toHaveLength(1);
+ expect((await toolRow(chatId)).undoneAt).toBeNull();
+ });
+
+ test("undo is refused for another person's conversation", async () => {
+ const chatId = await loggedThread();
+ const row = await toolRow(chatId);
+ await expect(
+ assistantService.undo(other, {
+ conversationId: chatId,
+ messageId: row.id,
+ }),
+ ).rejects.toThrow("not found");
+ expect(await db.select().from(timeEntry)).toHaveLength(1);
+ });
+
+ test("undo of a create is refused once the entry holds a commit", async () => {
+ const chatId = await loggedThread();
+ const entry = at(await db.select().from(timeEntry), 0);
+ await db.insert(timeEntryGithubCommit).values({
+ timeEntryId: entry.id,
+ sha: "abc123",
+ message: "fix",
+ committedAt: new Date(),
+ url: "https://example.com/c/abc123",
+ });
+ const row = await toolRow(chatId);
+ await expect(
+ assistantService.undo(mine, {
+ conversationId: chatId,
+ messageId: row.id,
+ }),
+ ).rejects.toThrow("commits or reviews");
+ expect(await db.select().from(timeEntry)).toHaveLength(1);
+ expect((await toolRow(chatId)).undoneAt).toBeNull();
+ });
+
+ test("an update of a fill-day entry offers no undo", async () => {
+ const chatId = await loggedThread();
+ const entry = at(await db.select().from(timeEntry), 0);
+ await db.update(timeEntry).set({ fillsDay: true });
+ await ask(chatId, "change it", [
+ turn({
+ toolCalls: [
+ call("c2", "update_time_entry", {
+ timeEntryId: entry.id,
+ date: "2026-03-04",
+ projectId,
+ taskId: devTaskId,
+ durationSeconds: 7200,
+ description: "changed",
+ }),
+ ],
+ }),
+ turn({ content: "Changed." }),
+ ]);
+ const rows = await db.query.assistantMessage.findMany({
+ where: eq(assistantMessage.conversationId, chatId),
+ });
+ const updateRow = present(
+ rows.find((r) => r.toolName === "update_time_entry"),
+ "update row",
+ );
+ expect(updateRow.undo).toBeNull();
+ });
+
+ test("the model is told that a later turn's undone write is gone", async () => {
+ const chatId = await loggedThread();
+ const row = await toolRow(chatId);
+ await assistantService.undo(mine, {
+ conversationId: chatId,
+ messageId: row.id,
+ });
+ seen = [];
+ await ask(chatId, "what now?", [turn({ content: "Nothing." })]);
+ const tool = present(
+ at(seen, 0).find((m) => m.role === "tool"),
+ "tool message",
+ );
+ expect(tool.content).toContain('"undone":true');
+ expect(tool.content).toContain("The person undid this change.");
+ });
+});
+
+describe("replaceLastTurn", () => {
+ test("is refused while a write of the turn stands, allowed after undo", async () => {
+ const chatId = await loggedThread();
+ await expect(
+ assistantService.replaceLastTurn(mine, { conversationId: chatId }),
+ ).rejects.toThrow("Undo the change first");
+
+ const row = await toolRow(chatId);
+ await assistantService.undo(mine, {
+ conversationId: chatId,
+ messageId: row.id,
+ });
+ const removed = await assistantService.replaceLastTurn(mine, {
+ conversationId: chatId,
+ });
+ expect(removed.content).toBe("log an hour");
+ });
+
+ test("says to ask a new question when a standing write has no inverse", async () => {
+ const chat = await assistantService.conversations.create(mine);
+ await db.insert(assistantMessage).values([
+ {
+ organizationId: ORG,
+ conversationId: chat.id,
+ role: "user",
+ content: "make a project",
+ createdAt: new Date(1000),
+ },
+ {
+ organizationId: ORG,
+ createdAt: new Date(2000),
+ conversationId: chat.id,
+ role: "tool",
+ toolCallId: "p1",
+ toolName: "create_project",
+ content: '{"ok":true}',
+ },
+ ]);
+ await expect(
+ assistantService.replaceLastTurn(mine, { conversationId: chat.id }),
+ ).rejects.toThrow("Ask a new question instead");
+ });
+
+ test("deletes exactly the last turn and keeps the usage rows", async () => {
+ const chat = await assistantService.conversations.create(mine);
+ await assistantService.conversations.rename(mine, {
+ conversationId: chat.id,
+ title: "t",
+ });
+ await ask(chat.id, "first", [turn({ content: "One." })]);
+ await ask(chat.id, "second", [turn({ content: "Two." })]);
+ const usageBefore = await db.select().from(assistantUsage);
+ expect(usageBefore.length).toBeGreaterThan(0);
+
+ await assistantService.replaceLastTurn(mine, { conversationId: chat.id });
+ const rows = await db.query.assistantMessage.findMany({
+ where: eq(assistantMessage.conversationId, chat.id),
+ });
+ expect(rows.map((r) => r.content).sort()).toEqual(["first", "One."].sort());
+ expect(await db.select().from(assistantUsage)).toHaveLength(
+ usageBefore.length,
+ );
+ });
+
+ test("is allowed after a call that was refused before it ran", async () => {
+ const chat = await assistantService.conversations.create(mine);
+ await db.insert(assistantMessage).values([
+ {
+ organizationId: ORG,
+ conversationId: chat.id,
+ role: "user",
+ content: "log it",
+ createdAt: new Date(1000),
+ },
+ {
+ organizationId: ORG,
+ createdAt: new Date(2000),
+ conversationId: chat.id,
+ role: "tool",
+ toolCallId: "p1",
+ toolName: "create_time_entry",
+ content: "The arguments were not valid JSON.",
+ },
+ ]);
+ const removed = await assistantService.replaceLastTurn(mine, {
+ conversationId: chat.id,
+ });
+ expect(removed.content).toBe("log it");
+ });
+
+ test("drops the answer of a turn whose question was removed meanwhile", async () => {
+ const chat = await assistantService.conversations.create(mine);
+ await assistantService.conversations.rename(mine, {
+ conversationId: chat.id,
+ title: "t",
+ });
+ onGenerate = async () => {
+ onGenerate = null;
+ await assistantService.replaceLastTurn(mine, {
+ conversationId: chat.id,
+ });
+ };
+ await ask(chat.id, "first", [turn({ content: "Late answer." })]);
+ const rows = await db.query.assistantMessage.findMany({
+ where: eq(assistantMessage.conversationId, chat.id),
+ });
+ expect(rows).toHaveLength(0);
+ });
+
+ test("keeps a turn's answer tied to its own question after a rewind", async () => {
+ const chat = await assistantService.conversations.create(mine);
+ await assistantService.conversations.rename(mine, {
+ conversationId: chat.id,
+ title: "t",
+ });
+ onGenerate = async () => {
+ onGenerate = null;
+ await assistantService.replaceLastTurn(mine, {
+ conversationId: chat.id,
+ });
+ // The next question lands while the first turn still writes.
+ await db.insert(assistantMessage).values({
+ organizationId: ORG,
+ conversationId: chat.id,
+ role: "user",
+ content: "second",
+ });
+ };
+ await ask(chat.id, "first", [turn({ content: "Late answer." })]);
+ const rows = await db.query.assistantMessage.findMany({
+ where: eq(assistantMessage.conversationId, chat.id),
+ });
+ expect(rows.map((row) => row.content)).toEqual(["second"]);
+ });
+
+ test("is refused for another person's conversation", async () => {
+ const chatId = await loggedThread();
+ await expect(
+ assistantService.replaceLastTurn(other, { conversationId: chatId }),
+ ).rejects.toThrow("not found");
+ });
+});
diff --git a/packages/core/src/services/assistant-undo.ts b/packages/core/src/services/assistant-undo.ts
new file mode 100644
index 00000000..e5ddde70
--- /dev/null
+++ b/packages/core/src/services/assistant-undo.ts
@@ -0,0 +1,166 @@
+import { eq } from "drizzle-orm";
+import { z } from "zod";
+
+import { db } from "../db";
+import type { AssistantUndo } from "../db/schema/assistant";
+import {
+ timeEntryGithubCommit,
+ timeEntryGithubPrActivity,
+} from "../db/schema/github";
+import type { JsonRecord, Serializable } from "../lib/json";
+import { UserFacingError } from "../lib/user-facing-error";
+import { timeEntriesService } from "./time-entries.service";
+import type { Ctx } from "./types";
+
+/** The entry changed after the write, so the saved inverse is not exact. */
+export class UndoStaleError extends UserFacingError {
+ constructor() {
+ super("This entry changed since, so the change cannot be undone.");
+ this.name = "UndoStaleError";
+ }
+}
+
+/** The entry gained commits or reviews, which a delete would cascade away. */
+export class UndoHasEvidenceError extends UserFacingError {
+ constructor() {
+ super("This entry holds commits or reviews, so it cannot be undone.");
+ this.name = "UndoHasEvidenceError";
+ }
+}
+
+/** Reads the state before a write. The returned function builds the inverse
+ * from the result of the write, or gives null when it cannot be exact. */
+export type UndoCapture = (result: Serializable | void) => AssistantUndo | null;
+export type UndoCapturer = (
+ ctx: Ctx,
+ args: JsonRecord,
+) => Promise;
+
+const writtenRow = z.object({ id: z.string(), updatedAt: z.date() });
+const entryArgs = z.object({ timeEntryId: z.string() });
+
+/** The row a write returned, as the id and the new `updatedAt`. */
+const written = (result: Serializable | void) => {
+ const parsed = writtenRow.safeParse(result);
+ return parsed.success
+ ? {
+ entryId: parsed.data.id,
+ updatedAt: parsed.data.updatedAt.toISOString(),
+ }
+ : null;
+};
+
+const entryBefore = async (ctx: Ctx, args: JsonRecord) => {
+ const parsed = entryArgs.safeParse(args);
+ if (!parsed.success) return null;
+ return (
+ (await timeEntriesService.getOwn(ctx, parsed.data.timeEntryId)) ?? null
+ );
+};
+
+export const undoCreateEntry: UndoCapturer = async () => (result) => {
+ const row = written(result);
+ return row && { kind: "delete_entry", ...row };
+};
+
+export const undoUpdateEntry: UndoCapturer = async (ctx, args) => {
+ const before = await entryBefore(ctx, args);
+ // `update` recomputes the duration of a fill-day entry, so no inverse is exact.
+ if (!before || before.fillsDay) return null;
+ return (result) => {
+ const row = written(result);
+ return (
+ row && {
+ kind: "restore_entry",
+ ...row,
+ before: {
+ projectId: before.projectId,
+ taskId: before.taskId,
+ date: before.date,
+ description: before.description,
+ durationSeconds: before.durationSeconds,
+ overtime: before.overtime,
+ fillsDay: before.fillsDay,
+ },
+ }
+ );
+ };
+};
+
+export const undoDescription: UndoCapturer = async (ctx, args) => {
+ const before = await entryBefore(ctx, args);
+ if (!before) return null;
+ return (result) => {
+ const row = written(result);
+ return (
+ row && {
+ kind: "restore_description",
+ ...row,
+ description: before.description,
+ }
+ );
+ };
+};
+
+export const undoOvertime: UndoCapturer = async (ctx, args) => {
+ const before = await entryBefore(ctx, args);
+ if (!before) return null;
+ return (result) => {
+ const row = written(result);
+ return (
+ row && { kind: "restore_overtime", ...row, overtime: before.overtime }
+ );
+ };
+};
+
+/** Adding a commit or a review does not touch `updatedAt`, so the staleness
+ * guard cannot see them. */
+const holdsEvidence = async (entryId: string) => {
+ const [commit] = await db
+ .select({ id: timeEntryGithubCommit.id })
+ .from(timeEntryGithubCommit)
+ .where(eq(timeEntryGithubCommit.timeEntryId, entryId))
+ .limit(1);
+ if (commit) return true;
+ const [activity] = await db
+ .select({ id: timeEntryGithubPrActivity.id })
+ .from(timeEntryGithubPrActivity)
+ .where(eq(timeEntryGithubPrActivity.timeEntryId, entryId))
+ .limit(1);
+ return Boolean(activity);
+};
+
+/** Runs the inverse through the same services as the caller. Refuses when the
+ * entry is not exactly as the write left it. */
+export const applyUndo = async (ctx: Ctx, undo: AssistantUndo) => {
+ const current = await timeEntriesService.getOwn(ctx, undo.entryId);
+ if (current?.updatedAt.getTime() !== new Date(undo.updatedAt).getTime()) {
+ throw new UndoStaleError();
+ }
+ switch (undo.kind) {
+ case "delete_entry":
+ // shortcut: check and delete are not one transaction, and `remove` has no refuse option; evidence added in that small window is not seen.
+ if (await holdsEvidence(undo.entryId)) throw new UndoHasEvidenceError();
+ await timeEntriesService.remove(ctx, undo.entryId);
+ return;
+ case "restore_entry":
+ await timeEntriesService.update(ctx, {
+ timeEntryId: undo.entryId,
+ ...undo.before,
+ projectId: undo.before.projectId ?? undefined,
+ });
+ return;
+ case "restore_description":
+ await timeEntriesService.updateDescription(ctx, {
+ timeEntryId: undo.entryId,
+ description: undo.description,
+ });
+ return;
+ case "restore_overtime":
+ await timeEntriesService.setOvertime(ctx, {
+ timeEntryId: undo.entryId,
+ overtime: undo.overtime,
+ });
+ return;
+ }
+};
diff --git a/packages/core/src/services/assistant-usage.service.ts b/packages/core/src/services/assistant-usage.service.ts
new file mode 100644
index 00000000..1505c578
--- /dev/null
+++ b/packages/core/src/services/assistant-usage.service.ts
@@ -0,0 +1,136 @@
+// The AI usage ledger: what each billed model call cost, per organization and
+// per person. Written beside each `AiGeneration` in `assistant.service.ts`, not
+// through the telemetry sink, which must never wait or throw.
+
+import { and, eq, gte, lt, sql } from "drizzle-orm";
+
+import { db } from "../db";
+import { assistantUsage } from "../db/schema/assistant";
+import { loggableError } from "../lib/loggable-error";
+import { dayBoundsInTz } from "../lib/time";
+import {
+ type AssistantUsageInput,
+ assistantUsageInput,
+} from "../schema/reports";
+import { ctxTimezone, requireAdmin } from "./context";
+import { membersService } from "./members.service";
+import type { Ctx } from "./types";
+
+export type AssistantUsageEntry = {
+ conversationId: string;
+ model: string;
+ servedModel: string | null;
+ kind: "turn" | "title";
+ attempt: number;
+ promptTokens: number | null;
+ completionTokens: number | null;
+ /** Null when the call has no usage row: unknown, not zero. */
+ costUsd: number | null;
+};
+
+/** Write one ledger row. A failure is logged and never reaches the turn. */
+export const recordAssistantUsage = async (
+ ctx: Ctx,
+ entry: AssistantUsageEntry,
+): Promise => {
+ try {
+ await db.insert(assistantUsage).values({
+ organizationId: ctx.organizationId,
+ userId: ctx.userId,
+ ...entry,
+ });
+ } catch (error) {
+ console.error(
+ "[assistant] usage ledger insert failed",
+ loggableError(error),
+ );
+ }
+};
+
+export type UsageTotals = {
+ calls: number;
+ /** Calls with no known cost. They add nothing to `costUsd`. */
+ unknownCostCalls: number;
+ promptTokens: number;
+ completionTokens: number;
+ costUsd: number;
+};
+
+export type AssistantUsagePerson = UsageTotals & {
+ userId: string;
+ name: string;
+ image: string | null;
+};
+
+export type AssistantUsageModel = UsageTotals & { model: string };
+
+export type AssistantUsageSummary = {
+ totals: UsageTotals;
+ people: AssistantUsagePerson[];
+ models: AssistantUsageModel[];
+};
+
+const totalsSql = {
+ calls: sql`count(*)::int`,
+ unknownCostCalls: sql`(count(*) filter (where ${assistantUsage.costUsd} is null))::int`,
+ promptTokens: sql`coalesce(sum(${assistantUsage.promptTokens}), 0)::int`,
+ completionTokens: sql`coalesce(sum(${assistantUsage.completionTokens}), 0)::int`,
+ costUsd: sql`coalesce(sum(${assistantUsage.costUsd}), 0)::float8`,
+};
+
+const byCostDesc = (a: UsageTotals, b: UsageTotals) => b.costUsd - a.costUsd;
+
+const summary = async (
+ ctx: Ctx,
+ input: AssistantUsageInput,
+): Promise => {
+ await requireAdmin(ctx);
+ const { from, to } = assistantUsageInput.parse(input);
+ const tz = await ctxTimezone(ctx);
+ const where = and(
+ eq(assistantUsage.organizationId, ctx.organizationId),
+ gte(assistantUsage.createdAt, dayBoundsInTz(from, tz).start),
+ lt(assistantUsage.createdAt, dayBoundsInTz(to, tz).end),
+ );
+
+ const [[totals], personRows, modelRows, { members }] = await Promise.all([
+ db.select(totalsSql).from(assistantUsage).where(where),
+ db
+ .select({ userId: assistantUsage.userId, ...totalsSql })
+ .from(assistantUsage)
+ .where(where)
+ .groupBy(assistantUsage.userId),
+ db
+ .select({ model: assistantUsage.model, ...totalsSql })
+ .from(assistantUsage)
+ .where(where)
+ .groupBy(assistantUsage.model),
+ membersService.roster(ctx),
+ ]);
+
+ const byUser = new Map(members.map((m) => [m.userId, m.user]));
+ const people = personRows
+ .map((row) => {
+ const person = byUser.get(row.userId);
+ return {
+ ...row,
+ name: person?.name ?? "Removed person",
+ image: person?.image ?? null,
+ };
+ })
+ .sort(byCostDesc);
+
+ return {
+ totals: totals ?? {
+ calls: 0,
+ unknownCostCalls: 0,
+ promptTokens: 0,
+ completionTokens: 0,
+ costUsd: 0,
+ },
+ people,
+ models: modelRows.sort(byCostDesc),
+ };
+};
+
+export const assistantUsageService = { summary };
diff --git a/packages/core/src/services/assistant-usage.test.ts b/packages/core/src/services/assistant-usage.test.ts
new file mode 100644
index 00000000..379afceb
--- /dev/null
+++ b/packages/core/src/services/assistant-usage.test.ts
@@ -0,0 +1,149 @@
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+
+import { eq } from "drizzle-orm";
+
+import { db } from "../db";
+import { assistantConversation, assistantUsage } from "../db/schema/assistant";
+import { member, organization, user } from "../db/schema/auth";
+import { at, createTestDb, present, type TestDb } from "../test/harness";
+import { AccessError } from "./access.service";
+import { assistantUsageService } from "./assistant-usage.service";
+import type { Ctx } from "./types";
+
+const ORG = "au-org";
+const OTHER = "au-other";
+const ADMIN = "u-au-admin";
+const WORKER = "u-au-worker";
+const FOREIGN = "u-au-foreign";
+
+let harness: TestDb;
+let chatId = "";
+
+const ctx = (userId: string, organizationId = ORG): Ctx => ({
+ organizationId,
+ userId,
+});
+const range = { from: "2026-01-01", to: "2026-12-31" };
+const at12 = new Date("2026-06-15T12:00:00Z");
+
+const row = (
+ over: Partial & { userId: string },
+): typeof assistantUsage.$inferInsert => ({
+ organizationId: ORG,
+ model: "m/one",
+ kind: "turn",
+ attempt: 1,
+ promptTokens: 100,
+ completionTokens: 10,
+ costUsd: 0.5,
+ createdAt: at12,
+ ...over,
+});
+
+beforeAll(async () => {
+ harness = await createTestDb();
+ const now = new Date();
+ await db.insert(organization).values([
+ { id: ORG, name: "Usage", slug: ORG, createdAt: now },
+ { id: OTHER, name: "Elsewhere", slug: OTHER, createdAt: now },
+ ]);
+ await db.insert(user).values(
+ [ADMIN, WORKER, FOREIGN].map((id) => ({
+ id,
+ name: id,
+ email: `${id}@example.com`,
+ emailVerified: true,
+ createdAt: now,
+ updatedAt: now,
+ })),
+ );
+ await db.insert(member).values([
+ {
+ id: "m-au-admin",
+ organizationId: ORG,
+ userId: ADMIN,
+ role: "admin",
+ createdAt: now,
+ },
+ {
+ id: "m-au-worker",
+ organizationId: ORG,
+ userId: WORKER,
+ role: "member",
+ createdAt: now,
+ },
+ {
+ id: "m-au-foreign",
+ organizationId: OTHER,
+ userId: FOREIGN,
+ role: "admin",
+ createdAt: now,
+ },
+ ]);
+ const [chat] = await db
+ .insert(assistantConversation)
+ .values({ organizationId: ORG, userId: WORKER, model: "m/one" })
+ .returning();
+ chatId = present(chat, "conversation").id;
+ await db.insert(assistantUsage).values([
+ row({ userId: WORKER, conversationId: chatId, costUsd: 0.25 }),
+ row({
+ userId: WORKER,
+ conversationId: chatId,
+ costUsd: null,
+ attempt: 2,
+ }),
+ row({ userId: ADMIN, model: "m/two", kind: "title", costUsd: 1 }),
+ row({ userId: WORKER, createdAt: new Date("2025-01-01T00:00:00Z") }),
+ row({ userId: FOREIGN, organizationId: OTHER, costUsd: 99 }),
+ ]);
+});
+
+afterAll(async () => {
+ await harness.close();
+});
+
+describe("assistantUsageService.summary", () => {
+ test("sums the cost, counts the calls, and keeps unknown cost apart", async () => {
+ const result = await assistantUsageService.summary(ctx(ADMIN), range);
+ expect(result.totals.calls).toBe(3);
+ expect(result.totals.costUsd).toBeCloseTo(1.25);
+ expect(result.totals.unknownCostCalls).toBe(1);
+ const worker = present(
+ result.people.find((p) => p.userId === WORKER),
+ "worker row",
+ );
+ expect(worker.calls).toBe(2);
+ expect(worker.unknownCostCalls).toBe(1);
+ expect(worker.costUsd).toBeCloseTo(0.25);
+ expect(at(result.people, 0).userId).toBe(ADMIN);
+ expect(result.models.map((m) => m.model).sort()).toEqual([
+ "m/one",
+ "m/two",
+ ]);
+ });
+
+ test("a deleted conversation keeps its rows", async () => {
+ await db
+ .delete(assistantConversation)
+ .where(eq(assistantConversation.id, chatId));
+ const result = await assistantUsageService.summary(ctx(ADMIN), range);
+ expect(result.totals.calls).toBe(3);
+ });
+
+ test("another organization's rows never show", async () => {
+ const result = await assistantUsageService.summary(
+ ctx(FOREIGN, OTHER),
+ range,
+ );
+ expect(result.totals.calls).toBe(1);
+ expect(result.totals.costUsd).toBe(99);
+ expect(result.people.map((p) => p.userId)).toEqual([FOREIGN]);
+ });
+
+ test("a Member is refused", async () => {
+ await expect(
+ assistantUsageService.summary(ctx(WORKER), range),
+ ).rejects.toBeInstanceOf(AccessError);
+ });
+});
diff --git a/packages/core/src/services/assistant-wire.test.ts b/packages/core/src/services/assistant-wire.test.ts
new file mode 100644
index 00000000..522b7766
--- /dev/null
+++ b/packages/core/src/services/assistant-wire.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, test } from "bun:test";
+
+import type { ChatMessage } from "../lib/openrouter-client";
+import { at } from "../test/harness";
+import {
+ ELIDE_MIN_CHARS,
+ ELIDED_RESULT,
+ elideOldToolResults,
+ KEEP_TOOL_RESULT_TURNS,
+} from "./assistant-wire";
+
+const big = "x".repeat(ELIDE_MIN_CHARS + 1);
+
+/** One turn: user, assistant with a call, and the tool result. */
+const turn = (n: number, result: string): ChatMessage[] => [
+ { role: "user", content: `q${n}` },
+ {
+ role: "assistant",
+ content: "",
+ tool_calls: [
+ {
+ id: `c${n}`,
+ type: "function",
+ function: { name: "t", arguments: "{}" },
+ },
+ ],
+ },
+ { role: "tool", content: result, tool_call_id: `c${n}` },
+];
+
+const toolRows = (wire: ChatMessage[]) =>
+ wire.flatMap((m) => (m.role === "tool" ? [m] : []));
+
+describe("elideOldToolResults", () => {
+ test("stubs big results older than the window", () => {
+ const turns = KEEP_TOOL_RESULT_TURNS + 2;
+ const wire = Array.from({ length: turns }, (_, n) => turn(n, big)).flat();
+ const out = toolRows(elideOldToolResults(wire));
+ expect(out).toHaveLength(turns);
+ out.forEach((row, n) => {
+ const old = n < 2;
+ expect(row.tool_call_id).toBe(`c${n}`);
+ expect(row.content).toBe(old ? ELIDED_RESULT : big);
+ });
+ });
+
+ test("keeps small results and the current turn", () => {
+ const wire = [
+ ...turn(0, "tiny"),
+ ...turn(1, big),
+ ...turn(2, big),
+ ...turn(3, big),
+ ...turn(4, big),
+ ...turn(5, big),
+ ];
+ const out = toolRows(elideOldToolResults(wire));
+ expect(at(out, 0).content).toBe("tiny");
+ expect(at(out, 1).content).toBe(ELIDED_RESULT);
+ expect(at(out, 5).content).toBe(big);
+ });
+
+ test("leaves a short thread and the input untouched", () => {
+ const wire = turn(0, big);
+ expect(elideOldToolResults(wire)).toBe(wire);
+ expect(at(wire, 2)).toEqual({
+ role: "tool",
+ content: big,
+ tool_call_id: "c0",
+ });
+ });
+});
diff --git a/packages/core/src/services/assistant-wire.ts b/packages/core/src/services/assistant-wire.ts
new file mode 100644
index 00000000..1158f53d
--- /dev/null
+++ b/packages/core/src/services/assistant-wire.ts
@@ -0,0 +1,46 @@
+import type { ChatMessage } from "../lib/openrouter-client";
+
+/** Turns (user messages) whose tool results stay whole. Older ones are
+ * stubbed. A fixed count bounds the size of the prompt. */
+export const KEEP_TOOL_RESULT_TURNS = 4;
+
+/** A shorter result costs nothing, so it stays. */
+export const ELIDE_MIN_CHARS = 400;
+
+export const ELIDED_RESULT = JSON.stringify({
+ elided: true,
+ note: "Older result removed to save space. Call the tool again if you need it.",
+});
+
+/** A tool result the person undid. The model must not assume the write stands. */
+export const undoneContent = (content: string) =>
+ JSON.stringify({
+ result: content,
+ undone: true,
+ note: "The person undid this change.",
+ });
+
+/**
+ * Replace big tool results of old turns with a stub. Wire copy only.
+ * Every tool row and its `tool_call_id` stays: one result per call id.
+ */
+export const elideOldToolResults = (wire: ChatMessage[]): ChatMessage[] => {
+ let seen = 0;
+ let boundary = -1;
+ for (let i = wire.length - 1; i >= 0; i--) {
+ if (wire[i]?.role !== "user") continue;
+ seen += 1;
+ if (seen === KEEP_TOOL_RESULT_TURNS) {
+ boundary = i;
+ break;
+ }
+ }
+ if (boundary === -1) return wire;
+ return wire.map((message, i) =>
+ i < boundary &&
+ message.role === "tool" &&
+ message.content.length > ELIDE_MIN_CHARS
+ ? { ...message, content: ELIDED_RESULT }
+ : message,
+ );
+};
diff --git a/packages/core/src/services/assistant.service.ts b/packages/core/src/services/assistant.service.ts
index 84706f20..b503618d 100644
--- a/packages/core/src/services/assistant.service.ts
+++ b/packages/core/src/services/assistant.service.ts
@@ -1,14 +1,29 @@
-import { and, asc, desc, eq, sql } from "drizzle-orm";
-import type { PgInsertValue } from "drizzle-orm/pg-core";
+import {
+ and,
+ asc,
+ desc,
+ eq,
+ exists,
+ inArray,
+ isNotNull,
+ isNull,
+ or,
+ type SQL,
+ sql,
+} from "drizzle-orm";
+import type { AnyPgColumn, PgInsertValue } from "drizzle-orm/pg-core";
import { z } from "zod";
import { db } from "../db";
import {
type AssistantToolCall,
+ type AssistantUndo,
assistantConversation,
assistantMessage,
assistantSettings,
} from "../db/schema/assistant";
+import { user } from "../db/schema/auth";
+import { editBlockReason } from "../lib/assistant-edit";
import { isAssistantEnabled } from "../lib/assistant-flag";
import type { JsonRecord, Serializable } from "../lib/json";
import { loggableError } from "../lib/loggable-error";
@@ -24,6 +39,7 @@ import {
streamChatCompletion,
verifyKey,
} from "../lib/openrouter-client";
+import { plainText } from "../lib/plain-text";
import { openAndHeal, sealSecret } from "../lib/secret-box";
import { dayKeyInTz } from "../lib/time";
import { UserFacingError } from "../lib/user-facing-error";
@@ -31,6 +47,7 @@ import type {
CreateConversationInput,
RenameConversationInput,
RunAssistantInput,
+ SearchConversationsInput,
SetAssistantSettingsInput,
UpdateAssistantSettingsInput,
} from "../schema";
@@ -42,6 +59,9 @@ import {
systemPrompt,
toolDefinitions,
} from "./assistant-tools";
+import { applyUndo } from "./assistant-undo";
+import { recordAssistantUsage } from "./assistant-usage.service";
+import { elideOldToolResults, undoneContent } from "./assistant-wire";
import { diffFields, recordAudit } from "./audit";
import { ctxAccess, ctxTimezone, requireAdmin } from "./context";
import { agentErrorMessage } from "./error-message";
@@ -126,6 +146,7 @@ export const chatModel = (): ChatModelPort => portOverride ?? realPort;
/** Test-only: substitute a scripted model. Pass null to restore. */
export const setChatModelForTests = (port: ChatModelPort | null): void => {
portOverride = port;
+ catalogues.clear();
};
// ── events ───────────────────────────────────────────────────────────────────
@@ -481,6 +502,63 @@ const requireConversation = async (ctx: Ctx, conversationId: string) => {
return row;
};
+const MODEL_CATALOGUE_TTL_MS = 60 * 60 * 1000;
+const MODEL_CATALOGUE_FAILURE_TTL_MS = 60 * 1000;
+// One catalogue per organization: the key, and so the model list, is its own.
+const catalogues = new Map<
+ string,
+ { at: number; lengths: Map }
+>();
+// One lookup in flight per organization, so concurrent cold reads make one call.
+const catalogueLoads = new Map<
+ string,
+ Promise