From 9ab3f9fb5cfe2f48d1626a4455216e782474098e Mon Sep 17 00:00:00 2001
From: Omar Zunic
Date: Wed, 11 Nov 2026 20:55:22 +0100
Subject: [PATCH 01/16] feat(web): draw the assistant loader as a sprout
The loader was a 3x3 pixel grid with no tie to the brand. It is now
the wheat from the Farmer mark: the stalk draws, the grains spring
out of it, then they drop. The grains come from the MARK path
itself, so the loader and the logo cannot drift apart.
---
.../src/components/assistant/primitives.tsx | 63 ++++++++------
apps/web/src/components/farmer-mark.tsx | 2 +-
apps/web/src/styles.css | 82 +++++++++++++++++--
3 files changed, 113 insertions(+), 34 deletions(-)
diff --git a/apps/web/src/components/assistant/primitives.tsx b/apps/web/src/components/assistant/primitives.tsx
index b2b87bf3..b923f827 100644
--- a/apps/web/src/components/assistant/primitives.tsx
+++ b/apps/web/src/components/assistant/primitives.tsx
@@ -11,9 +11,17 @@
// Sources: LoadingState.tsx, ThinkingState.tsx, ApprovalCard.tsx.
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 { useOrgSlug } from "#/hooks/use-org-slug.ts";
import { cn } from "#/lib/utils.ts";
@@ -26,35 +34,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, so we drop 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 +107,7 @@ export function AssistantLoader({ label = "Thinking" }: { label?: string }) {
// be maintained by hand.
return (
- );
-}
-
function AssistantPage() {
const orgSlug = useOrgSlug();
const queryClient = useQueryClient();
@@ -377,6 +367,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
diff --git a/apps/web/src/routes/$orgSlug/assistant_/shared/$id.tsx b/apps/web/src/routes/$orgSlug/assistant_/shared/$id.tsx
new file mode 100644
index 00000000..db3b7553
--- /dev/null
+++ b/apps/web/src/routes/$orgSlug/assistant_/shared/$id.tsx
@@ -0,0 +1,160 @@
+import { ChatCircleDotsIcon, InfoIcon } from "@phosphor-icons/react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import {
+ createFileRoute,
+ Link,
+ redirect,
+ useNavigate,
+} from "@tanstack/react-router";
+import { toast } from "sonner";
+
+import { Answer } from "#/components/assistant/answer.tsx";
+import { UserMessage } from "#/components/assistant/user-message.tsx";
+import { MenuPath } from "#/components/menu-path.tsx";
+import {
+ Avatar,
+ AvatarFallback,
+ AvatarImage,
+} from "#/components/ui/avatar.tsx";
+import { Button } from "#/components/ui/button.tsx";
+import { PageFull } from "#/components/ui/page-header.tsx";
+import { When } from "#/components/when.tsx";
+import { useOrgSlug } from "#/hooks/use-org-slug.ts";
+import {
+ assistantSettingsQuery,
+ sharedConversationQuery,
+} from "#/queries/assistant.ts";
+import { queryKeys } from "#/queries/keys.ts";
+import { unshareConversation } from "#/server/assistant.ts";
+
+/** A chat that its owner shared with the organization. Read only: no composer,
+ * no approval card and no undo. */
+export const Route = createFileRoute("/$orgSlug/assistant_/shared/$id")({
+ beforeLoad: ({ context, params }) => {
+ if (!context.assistantEnabled) {
+ throw redirect({ to: "/$orgSlug", params: { orgSlug: params.orgSlug } });
+ }
+ },
+ component: SharedChatPage,
+});
+
+function Explain({
+ title,
+ children,
+}: {
+ title: string;
+ children: React.ReactNode;
+}) {
+ return (
+
+
+
+ );
+}
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/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 16d1c98c..1a98a8a6 100644
--- a/apps/web/src/server/assistant.ts
+++ b/apps/web/src/server/assistant.ts
@@ -4,6 +4,7 @@ import {
conversationIdInput,
createConversationInput,
renameConversationInput,
+ searchConversationsInput,
setAssistantSettingsInput,
updateAssistantSettingsInput,
} from "@farmer/core/schema";
@@ -136,3 +137,36 @@ export const rewindAssistantThread = createServerFn({ method: "POST" })
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/docs/domains/assistant.md b/docs/domains/assistant.md
index 67ecd9f0..d1765427 100644
--- a/docs/domains/assistant.md
+++ b/docs/domains/assistant.md
@@ -13,6 +13,8 @@ An OpenRouter-backed chat page (`$orgSlug/assistant`) that answers questions abo
- **`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).
- **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): "This answer changed your data. Undo the change first, then edit." It returns the removed text, and the client sends it again as a new turn. `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`).
diff --git a/packages/api-client/openapi.json b/packages/api-client/openapi.json
index de536916..c11c6a67 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.",
+ "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.",
+ "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. 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/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",
@@ -17060,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": {
@@ -17296,6 +17640,49 @@
"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",
+ "sharedAt",
+ "sharedBy"
+ ]
+ },
"AssistantEvent": {
"oneOf": [
{
@@ -19970,6 +20357,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 fc57a7b5..c8e346a5 100644
--- a/packages/api-client/src/client.ts
+++ b/packages/api-client/src/client.ts
@@ -108,6 +108,9 @@ import {
assistantSettingsSchema,
assistantMessageSchema,
assistantRewindSchema,
+ assistantSearchHitSchema,
+ assistantSharedThreadSchema,
+ assistantShareSchema,
assistantThreadDetailSchema,
assistantThreadSchema,
} from "./schemas-assistant";
@@ -1466,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(
diff --git a/packages/api-client/src/openapi.gen.ts b/packages/api-client/src/openapi.gen.ts
index 0d943227..fc70e666 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.
+ */
+ post: operations["shareAssistantThread"];
+ /**
+ * Stop sharing a thread
+ * @description The owner may. An Admin may stop any shared thread.
+ */
+ 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. A thread that is not shared 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;
@@ -3793,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. */
@@ -3842,6 +3921,17 @@ export interface components {
/** @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: {
/** @constant */
@@ -4482,7 +4572,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;
@@ -9435,7 +9525,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;
@@ -10044,6 +10134,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;
diff --git a/packages/api-client/src/schemas-assistant.ts b/packages/api-client/src/schemas-assistant.ts
index 90b0d0b3..04fc495d 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(),
@@ -116,6 +133,18 @@ 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`.
@@ -184,6 +213,13 @@ export type AssistantContractChecks = [
Expect>,
Expect>,
Expect>,
+ Expect<
+ Parses
+ >,
+ Expect>,
+ Expect<
+ Parses
+ >,
Expect<
Parses
>,
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/0085_snapshot.json b/packages/core/drizzle/meta/0086_snapshot.json
similarity index 99%
rename from packages/core/drizzle/meta/0085_snapshot.json
rename to packages/core/drizzle/meta/0086_snapshot.json
index f269bf45..ccd7a5ea 100644
--- a/packages/core/drizzle/meta/0085_snapshot.json
+++ b/packages/core/drizzle/meta/0086_snapshot.json
@@ -1,6 +1,6 @@
{
- "id": "6cd7f929-fdf2-4c42-af1b-fbd9d8c02ecb",
- "prevId": "0d3ef796-53e9-4ff8-a0bb-ac71a772bd60",
+ "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": {},
diff --git a/packages/core/drizzle/meta/_journal.json b/packages/core/drizzle/meta/_journal.json
index 18e9f9f3..de0177d0 100644
--- a/packages/core/drizzle/meta/_journal.json
+++ b/packages/core/drizzle/meta/_journal.json
@@ -603,6 +603,13 @@
"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 aa90da55..34864ff2 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",
});
});
});
diff --git a/packages/core/src/api/assistant.ts b/packages/core/src/api/assistant.ts
index 663556dc..4f21c497 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 = {
@@ -211,6 +238,24 @@ export type ApiAssistantThreadDetail = {
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 };
+};
+
/**
* One event of a streamed turn: the `data:` line of each Server-Sent Event,
* as JSON. The same events the web app's chat reads.
diff --git a/packages/core/src/db/schema/assistant.ts b/packages/core/src/db/schema/assistant.ts
index 8f4655a8..45818cf2 100644
--- a/packages/core/src/db/schema/assistant.ts
+++ b/packages/core/src/db/schema/assistant.ts
@@ -70,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",
{
@@ -86,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) => [
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/schema/assistant.ts b/packages/core/src/schema/assistant.ts
index c8670639..6a0881a4 100644
--- a/packages/core/src/schema/assistant.ts
+++ b/packages/core/src/schema/assistant.ts
@@ -111,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/services/assistant-share.test.ts b/packages/core/src/services/assistant-share.test.ts
new file mode 100644
index 00000000..bab4057f
--- /dev/null
+++ b/packages/core/src/services/assistant-share.test.ts
@@ -0,0 +1,247 @@
+// 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("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("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("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.service.ts b/packages/core/src/services/assistant.service.ts
index 380fa00a..89904157 100644
--- a/packages/core/src/services/assistant.service.ts
+++ b/packages/core/src/services/assistant.service.ts
@@ -3,12 +3,15 @@ import {
asc,
desc,
eq,
+ exists,
inArray,
isNotNull,
isNull,
+ or,
+ type SQL,
sql,
} from "drizzle-orm";
-import type { PgInsertValue } from "drizzle-orm/pg-core";
+import type { AnyPgColumn, PgInsertValue } from "drizzle-orm/pg-core";
import { z } from "zod";
import { db } from "../db";
@@ -41,6 +44,7 @@ import type {
CreateConversationInput,
RenameConversationInput,
RunAssistantInput,
+ SearchConversationsInput,
SetAssistantSettingsInput,
UpdateAssistantSettingsInput,
} from "../schema";
@@ -58,6 +62,7 @@ import { elideOldToolResults, undoneContent } from "./assistant-wire";
import { diffFields, recordAudit } from "./audit";
import { ctxAccess, ctxTimezone, requireAdmin } from "./context";
import { agentErrorMessage } from "./error-message";
+import { membersService } from "./members.service";
import type { Ctx } from "./types";
export class AssistantError extends UserFacingError {
@@ -529,6 +534,7 @@ const conversations = {
title: assistantConversation.title,
model: assistantConversation.model,
updatedAt: assistantConversation.updatedAt,
+ sharedAt: assistantConversation.sharedAt,
})
.from(assistantConversation)
.where(
@@ -594,6 +600,189 @@ const conversations = {
},
};
+// ── search ───────────────────────────────────────────────────────────────────
+
+const SNIPPET_CHARS = 120;
+const SEARCH_LIMIT = 30;
+
+/** Case-insensitive substring match with the LIKE wildcards taken literally.
+ * Escaped against a backslash and declared with ESCAPE, as `notePredicate` in
+ * `ledger.ts` does. */
+const containsTerm = (column: AnyPgColumn, term: string): SQL => {
+ const escaped = term.replace(/[\\%_]/g, (match) => `\\${match}`);
+ return sql`${column} ilike ${`%${escaped}%`} escape '\\'`;
+};
+
+/** About `SNIPPET_CHARS` of plain text around the first match. */
+const snippetAround = (content: string, term: string): string => {
+ const text = content.replace(/\s+/g, " ").trim();
+ const hit = Math.max(0, text.toLowerCase().indexOf(term.toLowerCase()));
+ const start = Math.max(
+ 0,
+ hit - Math.floor((SNIPPET_CHARS - term.length) / 2),
+ );
+ const piece = text.slice(start, start + SNIPPET_CHARS);
+ return `${start > 0 ? "…" : ""}${piece}${start + SNIPPET_CHARS < text.length ? "…" : ""}`;
+};
+
+/** Messages a person typed or read: not the tool rows. */
+const readableMessage = inArray(assistantMessage.role, ["user", "assistant"]);
+
+const search = async (ctx: Ctx, input: SearchConversationsInput) => {
+ const term = input.q;
+ const matchingMessage = and(
+ eq(assistantMessage.conversationId, assistantConversation.id),
+ readableMessage,
+ containsTerm(assistantMessage.content, term),
+ );
+ const rows = await db
+ .select({
+ id: assistantConversation.id,
+ title: assistantConversation.title,
+ updatedAt: assistantConversation.updatedAt,
+ })
+ .from(assistantConversation)
+ .where(
+ and(
+ eq(assistantConversation.organizationId, ctx.organizationId),
+ eq(assistantConversation.userId, ctx.userId),
+ or(
+ containsTerm(assistantConversation.title, term),
+ exists(
+ db
+ .select({ one: sql`1` })
+ .from(assistantMessage)
+ .where(matchingMessage),
+ ),
+ ),
+ ),
+ )
+ .orderBy(desc(assistantConversation.updatedAt))
+ .limit(SEARCH_LIMIT);
+ if (rows.length === 0) return [];
+ const hits = await db
+ .select({
+ conversationId: assistantMessage.conversationId,
+ content: assistantMessage.content,
+ })
+ .from(assistantMessage)
+ .where(
+ and(
+ inArray(
+ assistantMessage.conversationId,
+ rows.map((row) => row.id),
+ ),
+ readableMessage,
+ containsTerm(assistantMessage.content, term),
+ ),
+ )
+ .orderBy(asc(assistantMessage.createdAt));
+ const first = new Map();
+ for (const hit of hits) {
+ if (!first.has(hit.conversationId))
+ first.set(hit.conversationId, hit.content);
+ }
+ return rows.map((row) => {
+ const content = first.get(row.id);
+ return {
+ ...row,
+ snippet: content === undefined ? null : snippetAround(content, term),
+ };
+ });
+};
+
+// ── sharing ──────────────────────────────────────────────────────────────────
+
+const conversationTarget = (row: { id: string; title: string }) => ({
+ type: "assistant_conversation",
+ id: row.id,
+ label: row.title,
+});
+
+/** Share one of the caller's chats with the organization. */
+const share = async (ctx: Ctx, conversationId: string) => {
+ const row = await requireConversation(ctx, conversationId);
+ if (row.sharedAt) return { sharedAt: row.sharedAt };
+ const sharedAt = new Date();
+ await db
+ .update(assistantConversation)
+ .set({ sharedAt, sharedBy: ctx.userId })
+ .where(conversationWhere(ctx, conversationId));
+ await recordAudit(ctx, {
+ kind: "assistant_chat.shared",
+ target: conversationTarget(row),
+ subjectUserId: row.userId,
+ });
+ return { sharedAt };
+};
+
+/** Stop sharing. The owner may, and so may an Admin for any chat in the org,
+ * so that leaked data can be pulled back. */
+const unshare = async (ctx: Ctx, conversationId: string) => {
+ const access = await ctxAccess(ctx);
+ const row = await db.query.assistantConversation.findFirst({
+ where: and(
+ eq(assistantConversation.id, conversationId),
+ eq(assistantConversation.organizationId, ctx.organizationId),
+ isNotNull(assistantConversation.sharedAt),
+ ),
+ });
+ if (!row || (row.userId !== ctx.userId && !access.isAdmin)) {
+ throw new AssistantError("Conversation not found");
+ }
+ await db
+ .update(assistantConversation)
+ .set({ sharedAt: null, sharedBy: null })
+ .where(eq(assistantConversation.id, row.id));
+ await recordAudit(ctx, {
+ kind: "assistant_chat.unshared",
+ target: conversationTarget(row),
+ subjectUserId: row.userId,
+ });
+ return { sharedAt: null };
+};
+
+/** A stored row as a reader sees it: nothing waits for an answer and nothing
+ * can be undone. */
+const readOnlyRow = (row: StoredMessage): StoredMessage => ({
+ ...row,
+ pendingApproval: false,
+ undo: null,
+});
+
+/** Read one shared chat. Any member of the org may. A chat that is not shared,
+ * or is in another org, is not found. */
+const getShared = async (ctx: Ctx, conversationId: string) => {
+ await ctxAccess(ctx);
+ if (!isAssistantEnabled()) throw new AssistantDisabledError();
+ const conversation = await db.query.assistantConversation.findFirst({
+ where: and(
+ eq(assistantConversation.id, conversationId),
+ eq(assistantConversation.organizationId, ctx.organizationId),
+ isNotNull(assistantConversation.sharedAt),
+ ),
+ });
+ if (!conversation?.sharedAt)
+ throw new AssistantError("Conversation not found");
+ const [messages, roster] = await Promise.all([
+ db.query.assistantMessage.findMany({
+ where: eq(assistantMessage.conversationId, conversation.id),
+ orderBy: asc(assistantMessage.createdAt),
+ }),
+ membersService.roster(ctx),
+ ]);
+ const sharer = roster.members.find((m) => m.userId === conversation.sharedBy);
+ return {
+ conversation,
+ messages: messages.map(readOnlyRow),
+ sharedAt: conversation.sharedAt,
+ sharedBy: {
+ name: sharer?.user.name ?? "A colleague",
+ image: sharer?.user.image ?? null,
+ },
+ };
+};
+
// ── the loop ─────────────────────────────────────────────────────────────────
type StoredMessage = typeof assistantMessage.$inferSelect;
@@ -2223,4 +2412,8 @@ export const assistantService = {
run,
undo,
replaceLastTurn,
+ search,
+ share,
+ unshare,
+ getShared,
};
diff --git a/packages/core/src/services/audit-coverage.test.ts b/packages/core/src/services/audit-coverage.test.ts
index 8ae08708..42c32ac1 100644
--- a/packages/core/src/services/audit-coverage.test.ts
+++ b/packages/core/src/services/audit-coverage.test.ts
@@ -212,14 +212,18 @@ const SERVICES = {
service: {
undo: assistantService.undo,
replaceLastTurn: assistantService.replaceLastTurn,
+ share: assistantService.share,
+ unshare: assistantService.unshare,
+ search: assistantService.search,
+ getShared: assistantService.getShared,
},
coverage: {
- recorded: {},
+ recorded: { share: true, unshare: true },
exempt: {
undo: "runs the inverse of a write on the person's own time through timeEntriesService",
replaceLastTurn: "deletes the person's own chat rows",
},
- reads: [],
+ reads: ["search", "getShared"],
},
},
webhooksService: {
From a0ce6016ac8a390395b9e58641316cf792a28b67 Mon Sep 17 00:00:00 2001
From: Omar Zunic
Date: Wed, 11 Nov 2026 21:45:11 +0100
Subject: [PATCH 08/16] fix(assistant): keep the edited text when the resend
fails
After a rewind, the question is gone from the thread. If the resend
then failed, the text was lost apart from a toast. The web and the
mobile app now put the text back in the composer and focus it.
The refusal for a turn with a write that has no inverse said "Undo the
change first", which the person cannot do. The core error now depends
on the case, in one pure helper (editBlockReason). The API message
carries a new `changed` field, so the web app and the mobile app show
the same text on the disabled Edit and Retry buttons.
---
apps/mobile/src/assistant/chat.tsx | 8 +--
apps/mobile/src/assistant/composer.tsx | 22 ++++++---
apps/mobile/src/assistant/edit-block.test.ts | 49 +++++++++++++++++++
apps/mobile/src/assistant/edit-block.ts | 18 +++++++
apps/mobile/src/assistant/stored-turn.tsx | 11 ++++-
apps/mobile/src/assistant/turn.test.ts | 1 +
.../src/components/assistant/prompt-bar.tsx | 20 ++++++--
.../src/components/assistant/stored-turn.tsx | 10 +++-
apps/web/src/lib/openapi.ts | 5 ++
apps/web/src/routes/$orgSlug/assistant.tsx | 16 +++---
docs/domains/assistant.md | 2 +-
packages/api-client/openapi.json | 5 ++
packages/api-client/src/openapi.gen.ts | 2 +
packages/api-client/src/schemas-assistant.ts | 2 +
packages/core/src/api/assistant.test.ts | 1 +
packages/core/src/api/assistant.ts | 5 ++
packages/core/src/lib/assistant-edit.ts | 22 +++++++++
.../core/src/services/assistant-undo.test.ts | 25 ++++++++++
.../core/src/services/assistant.service.ts | 16 ++++--
19 files changed, 211 insertions(+), 29 deletions(-)
create mode 100644 apps/mobile/src/assistant/edit-block.test.ts
create mode 100644 apps/mobile/src/assistant/edit-block.ts
create mode 100644 packages/core/src/lib/assistant-edit.ts
diff --git a/apps/mobile/src/assistant/chat.tsx b/apps/mobile/src/assistant/chat.tsx
index afa1580b..723901f2 100644
--- a/apps/mobile/src/assistant/chat.tsx
+++ b/apps/mobile/src/assistant/chat.tsx
@@ -19,6 +19,7 @@ import { Answer } from "./answer";
import { ApprovalCard } from "./approval-card";
import { Composer } from "./composer";
import { ContextNote } from "./context-note";
+import { editBlockReason } from "./edit-block";
import { useRun, useRunActions } from "./runs";
import { useChatHeaderActions } from "./share";
import { LastQuestionActions, StoredWrite } from "./stored-turn";
@@ -99,9 +100,8 @@ export function Chat({ id: routeId }: { id: string | null }) {
? "Wait for the answer to finish."
: pending
? "Answer the card first."
- : rows.slice(lastUserIndex).some((row) => row.undoable)
- ? "This answer changed your data. Undo the change first, then edit."
- : null;
+ : editBlockReason(messages);
+ const [restore, setRestore] = useState<{ text: string } | null>(null);
const send = async (text: string) => {
pinned.current = true;
@@ -244,6 +244,7 @@ export function Chat({ id: routeId }: { id: string | null }) {
text={message.content}
reason={editBlock}
onSend={send}
+ onRestore={(text) => setRestore({ text })}
/>
) : null}
@@ -326,6 +327,7 @@ export function Chat({ id: routeId }: { id: string | null }) {
keyboardOpen={keyboardOpen}
placeholder="Ask about your time"
autoFocus={id === null}
+ restore={restore}
/>
diff --git a/apps/mobile/src/assistant/composer.tsx b/apps/mobile/src/assistant/composer.tsx
index c7a29927..b4f7bc61 100644
--- a/apps/mobile/src/assistant/composer.tsx
+++ b/apps/mobile/src/assistant/composer.tsx
@@ -1,4 +1,4 @@
-import { useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { Platform, Pressable, TextInput, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -22,6 +22,7 @@ export function Composer({
keyboardOpen,
placeholder,
autoFocus = false,
+ restore = null,
}: {
/** True when the message reached the server. */
onSend: (text: string) => Promise;
@@ -34,6 +35,9 @@ export function Composer({
placeholder: string;
/** Open the keyboard at once, for a new chat. */
autoFocus?: boolean;
+ /** A text to put back, as after a send that never landed. A new object
+ * each time. */
+ restore?: { text: string } | null;
}) {
const palette = usePalette();
const insets = useSafeAreaInsets();
@@ -41,15 +45,21 @@ export function Composer({
const input = useRef(null);
const canSend = text.trim() !== "" && !streaming && !locked;
+ const giveBack = (message: string) => {
+ setText((current) => (current === "" ? message : current));
+ input.current?.focus();
+ };
+ // A new `restore` object is the only trigger, so `giveBack` stays out of the deps.
+ useEffect(() => {
+ if (restore) giveBack(restore.text);
+ // oxlint-disable-next-line react-hooks/exhaustive-deps -- see above
+ }, [restore]);
+
const send = async () => {
const message = text.trim();
if (!message || streaming || locked) return;
setText("");
- const landed = await onSend(message);
- if (!landed) {
- setText((current) => (current === "" ? message : current));
- input.current?.focus();
- }
+ if (!(await onSend(message))) giveBack(message);
};
return (
diff --git a/apps/mobile/src/assistant/edit-block.test.ts b/apps/mobile/src/assistant/edit-block.test.ts
new file mode 100644
index 00000000..ae64c32e
--- /dev/null
+++ b/apps/mobile/src/assistant/edit-block.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, test } from "bun:test";
+
+import type { AssistantMessage } from "@farmer/api-client";
+
+import { editBlockReason } from "./edit-block";
+
+const row = (
+ partial: Partial & Pick,
+): AssistantMessage => ({
+ content: "",
+ toolCalls: null,
+ toolCallId: null,
+ toolName: null,
+ pendingApproval: false,
+ approvalDecision: null,
+ approvalSummary: null,
+ approvalPreview: null,
+ undoable: false,
+ undone: false,
+ changed: false,
+ createdAt: "2026-10-06T10:00:00.000Z",
+ ...partial,
+});
+
+const question = row({ id: "q", role: "user" });
+
+describe("editBlockReason", () => {
+ test("is null when no write stands", () => {
+ expect(editBlockReason([question])).toBeNull();
+ });
+
+ test("asks for an undo when every write has an inverse", () => {
+ const write = row({ id: "t", role: "tool", changed: true, undoable: true });
+ expect(editBlockReason([question, write])).toContain("Undo the change");
+ });
+
+ test("says to ask again when one write has no inverse", () => {
+ const undoable = row({
+ id: "a",
+ role: "tool",
+ changed: true,
+ undoable: true,
+ });
+ const final = row({ id: "b", role: "tool", changed: true });
+ expect(editBlockReason([question, undoable, final])).toContain(
+ "Ask a new question instead",
+ );
+ });
+});
diff --git a/apps/mobile/src/assistant/edit-block.ts b/apps/mobile/src/assistant/edit-block.ts
new file mode 100644
index 00000000..c1447ac0
--- /dev/null
+++ b/apps/mobile/src/assistant/edit-block.ts
@@ -0,0 +1,18 @@
+import type { AssistantMessage } from "@farmer/api-client";
+
+// Mirror of `editBlockReason` in `packages/core/src/lib/assistant-edit.ts`,
+// as the app cannot import core. Keep the two texts equal.
+const AFTER_UNDOABLE_CHANGE =
+ "This answer changed your data. Undo the change first, then edit.";
+const AFTER_FINAL_CHANGE =
+ "This answer changed your data, and the change cannot be undone here. Ask a new question instead.";
+
+/** Why the last question cannot be edited because of a write, or null. */
+export const editBlockReason = (messages: AssistantMessage[]) => {
+ const last = messages.map((message) => message.role).lastIndexOf("user");
+ const standing = messages.slice(last).filter((message) => message.changed);
+ if (standing.length === 0) return null;
+ return standing.every((message) => message.undoable)
+ ? AFTER_UNDOABLE_CHANGE
+ : AFTER_FINAL_CHANGE;
+};
diff --git a/apps/mobile/src/assistant/stored-turn.tsx b/apps/mobile/src/assistant/stored-turn.tsx
index db9e0051..a59091e1 100644
--- a/apps/mobile/src/assistant/stored-turn.tsx
+++ b/apps/mobile/src/assistant/stored-turn.tsx
@@ -67,12 +67,16 @@ export function LastQuestionActions({
text,
reason,
onSend,
+ onRestore,
}: {
threadId: 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;
}) {
const palette = usePalette();
const rewind = useRewindThread();
@@ -84,11 +88,14 @@ export function LastQuestionActions({
setFailure(null);
try {
await rewind.mutateAsync(threadId);
- if (!(await onSend(next))) setFailure("The message was not sent.");
- else setEditing(false);
} catch (error) {
setFailure(error instanceof Error ? error.message : "Could not send.");
+ return;
}
+ setEditing(false);
+ // The rewind removed the question, so this row is about to unmount and
+ // the composer shows the text and the run shows the error.
+ if (!(await onSend(next))) onRestore(next);
};
if (editing) {
diff --git a/apps/mobile/src/assistant/turn.test.ts b/apps/mobile/src/assistant/turn.test.ts
index 8a1d6ced..0cd6eec9 100644
--- a/apps/mobile/src/assistant/turn.test.ts
+++ b/apps/mobile/src/assistant/turn.test.ts
@@ -25,6 +25,7 @@ const message = (
approvalPreview: null,
undoable: false,
undone: false,
+ changed: false,
createdAt: "2026-10-06T10:00:00.000Z",
...partial,
});
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/stored-turn.tsx b/apps/web/src/components/assistant/stored-turn.tsx
index d8f73542..1dd0e41d 100644
--- a/apps/web/src/components/assistant/stored-turn.tsx
+++ b/apps/web/src/components/assistant/stored-turn.tsx
@@ -104,6 +104,7 @@ export function LastQuestionActions({
text,
reason,
onSend,
+ onRestore,
editing,
onEditingChange,
}: {
@@ -112,6 +113,9 @@ export function LastQuestionActions({
/** 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;
}) {
@@ -124,7 +128,11 @@ export function LastQuestionActions({
await queryClient.invalidateQueries({
queryKey: conversationQuery(orgSlug, conversationId).queryKey,
});
- if (!(await onSend(next))) throw new Error("The message was not sent");
+ 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"),
diff --git a/apps/web/src/lib/openapi.ts b/apps/web/src/lib/openapi.ts
index 3cf033d4..166e065d 100644
--- a/apps/web/src/lib/openapi.ts
+++ b/apps/web/src/lib/openapi.ts
@@ -1590,6 +1590,11 @@ const apiAssistantMessage = named(
"A `tool` row whose write can still be undone: `POST …/messages/{messageId}/undo`.",
),
undone: z.boolean().describe("The person undid this write."),
+ changed: z
+ .boolean()
+ .describe(
+ "A `tool` row whose write ran and still stands, undoable or not.",
+ ),
createdAt: iso,
}),
),
diff --git a/apps/web/src/routes/$orgSlug/assistant.tsx b/apps/web/src/routes/$orgSlug/assistant.tsx
index 8f21024a..5ca9c996 100644
--- a/apps/web/src/routes/$orgSlug/assistant.tsx
+++ b/apps/web/src/routes/$orgSlug/assistant.tsx
@@ -1,3 +1,4 @@
+import { editBlockReason } from "@farmer/core/lib/assistant-edit";
import { ChatCircleDotsIcon } from "@phosphor-icons/react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { createFileRoute, redirect, useNavigate } from "@tanstack/react-router";
@@ -249,14 +250,15 @@ function AssistantPage() {
const editBlock = (() => {
if (stream.isStreaming) return "Wait for the answer to finish.";
if (pending) return "Answer the card first.";
- const standing = messages
- .slice(lastUserIndex)
- .some((m) => m.undo && !m.undoneAt);
- return standing
- ? "This answer changed your data. Undo the change first, then edit."
- : null;
+ return editBlockReason(
+ messages
+ .slice(lastUserIndex)
+ .filter((m) => m.changed)
+ .map((m) => ({ undoable: Boolean(m.undo) })),
+ );
})();
const [editing, setEditing] = useState(false);
+ 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
@@ -441,6 +443,7 @@ function AssistantPage() {
text={message.content}
reason={editBlock}
onSend={send}
+ onRestore={(text) => setRestore({ text })}
editing={editing}
onEditingChange={setEditing}
/>
@@ -585,6 +588,7 @@ function AssistantPage() {
}
autoFocus
focusKey={conversationId}
+ restore={restore}
/>
diff --git a/docs/domains/assistant.md b/docs/domains/assistant.md
index d1765427..143cd46e 100644
--- a/docs/domains/assistant.md
+++ b/docs/domains/assistant.md
@@ -15,7 +15,7 @@ An OpenRouter-backed chat page (`$orgSlug/assistant`) that answers questions abo
- **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).
-- **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): "This answer changed your data. Undo the change first, then edit." It returns the removed text, and the client sends it again as a new turn. `assistantUsage` rows stay, because they reference the conversation and not the messages.
+- **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.
diff --git a/packages/api-client/openapi.json b/packages/api-client/openapi.json
index c11c6a67..0e822fb3 100644
--- a/packages/api-client/openapi.json
+++ b/packages/api-client/openapi.json
@@ -17560,6 +17560,10 @@
"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."
@@ -17578,6 +17582,7 @@
"approvalPreview",
"undoable",
"undone",
+ "changed",
"createdAt"
]
},
diff --git a/packages/api-client/src/openapi.gen.ts b/packages/api-client/src/openapi.gen.ts
index fc70e666..4fb7db56 100644
--- a/packages/api-client/src/openapi.gen.ts
+++ b/packages/api-client/src/openapi.gen.ts
@@ -3905,6 +3905,8 @@ export interface components {
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;
};
diff --git a/packages/api-client/src/schemas-assistant.ts b/packages/api-client/src/schemas-assistant.ts
index 04fc495d..138c5bca 100644
--- a/packages/api-client/src/schemas-assistant.ts
+++ b/packages/api-client/src/schemas-assistant.ts
@@ -109,6 +109,8 @@ export const assistantMessageSchema = z.object({
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(),
});
diff --git a/packages/core/src/api/assistant.test.ts b/packages/core/src/api/assistant.test.ts
index 34864ff2..374954f3 100644
--- a/packages/core/src/api/assistant.test.ts
+++ b/packages/core/src/api/assistant.test.ts
@@ -114,6 +114,7 @@ describe("toApiAssistantMessage", () => {
},
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 4f21c497..34eee263 100644
--- a/packages/core/src/api/assistant.ts
+++ b/packages/core/src/api/assistant.ts
@@ -160,6 +160,8 @@ export type ApiAssistantMessage = {
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;
};
@@ -191,6 +193,8 @@ export const toApiAssistantMessage = (row: {
} | 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,
@@ -222,6 +226,7 @@ export const toApiAssistantMessage = (row: {
: null,
undoable: row.undo !== null && row.undoneAt === null,
undone: row.undoneAt !== null,
+ changed: row.changed ?? false,
createdAt: row.createdAt.toISOString(),
});
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/services/assistant-undo.test.ts b/packages/core/src/services/assistant-undo.test.ts
index 467f9893..b67e112e 100644
--- a/packages/core/src/services/assistant-undo.test.ts
+++ b/packages/core/src/services/assistant-undo.test.ts
@@ -320,6 +320,31 @@ describe("replaceLastTurn", () => {
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, {
diff --git a/packages/core/src/services/assistant.service.ts b/packages/core/src/services/assistant.service.ts
index 89904157..e44c8523 100644
--- a/packages/core/src/services/assistant.service.ts
+++ b/packages/core/src/services/assistant.service.ts
@@ -22,6 +22,7 @@ import {
assistantMessage,
assistantSettings,
} from "../db/schema/assistant";
+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";
@@ -578,7 +579,12 @@ const conversations = {
promptTokens === null
? null
: await contextLengthOf(ctx, conversation.model);
- return { conversation, messages, promptTokens, contextLength };
+ return {
+ conversation,
+ messages: messages.map((row) => ({ ...row, changed: changedData(row) })),
+ promptTokens,
+ contextLength,
+ };
},
rename: async (ctx: Ctx, input: RenameConversationInput) => {
@@ -2337,9 +2343,6 @@ const undo = async (
return { ok: true };
};
-const EDIT_AFTER_CHANGE =
- "This answer changed your data. Undo the change first, then edit.";
-
/** Results that say the call did not change anything. */
const NOT_RUN_RESULTS = new Set([
DECLINED,
@@ -2395,7 +2398,10 @@ const replaceLastTurn = async (
) {
throw new AssistantError("The answer is not finished yet.");
}
- if (turn.some(changedData)) throw new AssistantError(EDIT_AFTER_CHANGE);
+ const blocked = editBlockReason(
+ turn.filter(changedData).map((row) => ({ undoable: row.undo !== null })),
+ );
+ if (blocked) throw new AssistantError(blocked);
await tx.delete(assistantMessage).where(
inArray(
assistantMessage.id,
From 91b471252976d67eb25031ce9dcfd61e6673cf11 Mon Sep 17 00:00:00 2001
From: Omar Zunic
Date: Wed, 11 Nov 2026 21:54:06 +0100
Subject: [PATCH 09/16] fix(assistant): show plain text in search snippets
A search snippet was cut from the raw message text. It showed
markdown, chart JSON and directive syntax.
Turn the message into plain text first. Drop fenced blocks, turn
date directives into the date, and strip emphasis, code ticks,
links, heading marks and table pipes. A match that sat only in a
removed block falls back to the start of the text.
---
packages/core/src/lib/plain-text.test.ts | 31 +++++++++++++++++++
packages/core/src/lib/plain-text.ts | 12 +++++++
.../core/src/services/assistant-share.test.ts | 17 ++++++++++
.../core/src/services/assistant.service.ts | 6 ++--
4 files changed, 64 insertions(+), 2 deletions(-)
create mode 100644 packages/core/src/lib/plain-text.test.ts
create mode 100644 packages/core/src/lib/plain-text.ts
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(/\*+|(? {
).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("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" }]);
diff --git a/packages/core/src/services/assistant.service.ts b/packages/core/src/services/assistant.service.ts
index e44c8523..aeaef5a8 100644
--- a/packages/core/src/services/assistant.service.ts
+++ b/packages/core/src/services/assistant.service.ts
@@ -38,6 +38,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";
@@ -619,9 +620,10 @@ const containsTerm = (column: AnyPgColumn, term: string): SQL => {
return sql`${column} ilike ${`%${escaped}%`} escape '\\'`;
};
-/** About `SNIPPET_CHARS` of plain text around the first match. */
+/** About `SNIPPET_CHARS` of plain text around the first match. A match that
+ * only sat in removed markup falls back to the start of the text. */
const snippetAround = (content: string, term: string): string => {
- const text = content.replace(/\s+/g, " ").trim();
+ const text = plainText(content);
const hit = Math.max(0, text.toLowerCase().indexOf(term.toLowerCase()));
const start = Math.max(
0,
From e257a82fa537130485b2c7bbc7fe2411efbc933b Mon Sep 17 00:00:00 2001
From: Omar Zunic
Date: Wed, 11 Nov 2026 21:55:47 +0100
Subject: [PATCH 10/16] chore: tidy the better-ai diff
Shorten long comments in the AI settings page, the reports tab link
and the sprout loader. Keep each reason, drop the history and the
restated code. Remove one stray comma in the integrations doc.
No behavior change.
---
.../src/components/assistant/primitives.tsx | 2 +-
apps/web/src/routes/$orgSlug/reports.tsx | 5 +--
apps/web/src/routes/$orgSlug/settings/ai.tsx | 43 +++++--------------
docs/domains/integrations.md | 2 +-
4 files changed, 14 insertions(+), 38 deletions(-)
diff --git a/apps/web/src/components/assistant/primitives.tsx b/apps/web/src/components/assistant/primitives.tsx
index 64b28f38..e52e7de8 100644
--- a/apps/web/src/components/assistant/primitives.tsx
+++ b/apps/web/src/components/assistant/primitives.tsx
@@ -39,7 +39,7 @@ import { toolLabel } from "./tool-labels.ts";
/* ── the sprout loader (LoadingState) ─────────────────────────────────────── */
// The Farmer wheat. The stalk draws, then each grain grows out of it and drops.
-// The first piece of the mark is the tile, so we drop it.
+// 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];
diff --git a/apps/web/src/routes/$orgSlug/reports.tsx b/apps/web/src/routes/$orgSlug/reports.tsx
index 99492102..7710e05e 100644
--- a/apps/web/src/routes/$orgSlug/reports.tsx
+++ b/apps/web/src/routes/$orgSlug/reports.tsx
@@ -106,10 +106,7 @@ function ReportsPage() {
diff --git a/apps/web/src/routes/$orgSlug/settings/ai.tsx b/apps/web/src/routes/$orgSlug/settings/ai.tsx
index b20ba230..7531bb18 100644
--- a/apps/web/src/routes/$orgSlug/settings/ai.tsx
+++ b/apps/web/src/routes/$orgSlug/settings/ai.tsx
@@ -108,19 +108,12 @@ function AiSettingsPage() {
);
}
-/**
- * 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.
- */
+/** House rules for the system prompt. Explicit save: the switches write on change. */
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.
+ // Re-seed on a server change, but only while the box is clean.
const [baseline, setBaseline] = useState(stored);
if (stored !== baseline && draft === baseline) {
setBaseline(stored);
@@ -131,8 +124,7 @@ function HouseRulesRow({ stored }: { stored: string }) {
const save = useMutation({
mutationFn: () =>
updateAssistantSettings({
- // Empty box clears the rules: null is "forget them", where undefined
- // would mean "leave them alone".
+ // null clears the rules; undefined leaves them.
data: { systemPrompt: draft.trim() ? draft.trim() : null },
}),
onSuccess: async () => {
@@ -180,17 +172,9 @@ function HouseRulesRow({ stored }: { stored: string }) {
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.
+ * The default-model picker: a searching Combobox, as OpenRouter lists hundreds.
+ * The search covers the model id, so "anthropic/" lists one vendor. A stored
+ * model that the catalogue lacks is added, and the trigger shows its raw id.
*/
function ModelPicker({
models,
@@ -267,9 +251,8 @@ function ModelPicker({
);
}
-// 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.
+// Admin only: `assistantModelsQuery` needs the key, so a loader prefetch would
+// 403 for a member. Same shape as SlackSection below.
function OpenRouterSection() {
const orgSlug = useOrgSlug();
const queryClient = useQueryClient();
@@ -277,9 +260,7 @@ function OpenRouterSection() {
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.
+ // The stored key no longer opens (`BETTER_AUTH_SECRET` changed). The admin may disconnect it.
const unreadable = settings?.keyUnreadable ?? false;
const invalidate = () =>
@@ -287,8 +268,7 @@ function OpenRouterSection() {
queryKey: queryKeys(orgSlug).assistant,
});
- // Only once a key exists — the catalogue call authenticates with it, so
- // asking before then is a guaranteed error.
+ // The catalogue call needs the key.
const { data: models = [] } = useQuery({
...assistantModelsQuery(orgSlug),
enabled: configured,
@@ -299,8 +279,7 @@ function OpenRouterSection() {
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.
+ // A cheap, tool-capable default. The admin may change it below.
defaultModel: settings?.defaultModel ?? "openai/gpt-4o-mini",
},
}),
diff --git a/docs/domains/integrations.md b/docs/domains/integrations.md
index e80959fb..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, 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 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.
From 5fc58861938e4a99264c1ffe54860f73f216c2bc Mon Sep 17 00:00:00 2001
From: Omar Zunic
Date: Wed, 11 Nov 2026 22:05:20 +0100
Subject: [PATCH 11/16] fix(assistant): address review findings
Drop the answer of a turn when its question row was removed while the
model wrote. A share lock on the question row makes the check and the
insert one step.
Refuse the undo of a created entry when it holds commits or reviews.
These rows do not change updatedAt, so the staleness guard misses them.
Offer no undo for an update of a fill-day entry. The update recomputes
the duration, so the inverse is not exact.
Count the four refusals that run before a tool as not run, so edit and
retry are not blocked.
Key the model catalogue cache per organization. Cache a failure for 60
seconds and log the error.
Read the sharer name with one query in place of the whole roster.
Read only a window around the match in the chat search.
Let the CSV guard keep durations such as -1:30 and signed currency
amounts such as -EUR 5 unchanged.
Correct a comment on the tool result window.
---
.../assistant/answer-export.test.ts | 7 +
.../src/components/assistant/answer-export.ts | 5 +-
.../core/src/services/assistant-share.test.ts | 13 ++
.../core/src/services/assistant-undo.test.ts | 100 +++++++++++++
packages/core/src/services/assistant-undo.ts | 35 ++++-
packages/core/src/services/assistant-wire.ts | 2 +-
.../core/src/services/assistant.service.ts | 132 +++++++++++++-----
7 files changed, 257 insertions(+), 37 deletions(-)
diff --git a/apps/web/src/components/assistant/answer-export.test.ts b/apps/web/src/components/assistant/answer-export.test.ts
index 079aeaa4..b8921f8a 100644
--- a/apps/web/src/components/assistant/answer-export.test.ts
+++ b/apps/web/src/components/assistant/answer-export.test.ts
@@ -43,6 +43,13 @@ describe("toCsv", () => {
expect(body(csv)).toBe("'=1+1,'+x,'@a,-2.5,'-x,+3\r\n");
});
+ test("keeps a negative duration and a signed currency amount", () => {
+ const csv = toCsv([
+ ["-1:30", "-€5", "-$5", "+0:45", "=1:30", "-€x", "-5:"],
+ ]);
+ expect(body(csv)).toBe("-1:30,-€5,-$5,+0:45,'=1:30,'-€x,'-5:\r\n");
+ });
+
test("writes plain values for markdown cells", () => {
const csv = toCsv([["[[2026-08-03]]", "**5**"]]);
expect(body(csv)).toBe("2026-08-03,5\r\n");
diff --git a/apps/web/src/components/assistant/answer-export.ts b/apps/web/src/components/assistant/answer-export.ts
index 97976e8d..f3d43219 100644
--- a/apps/web/src/components/assistant/answer-export.ts
+++ b/apps/web/src/components/assistant/answer-export.ts
@@ -16,10 +16,11 @@ export const plainCell = (cell: string) =>
.replace(/`([^`]+)`/g, "$1")
.trim();
-const isPlainNumber = (value: string) => /^[-+]?[\d.,]*\d%?$/.test(value);
+const isPlainNumber = (value: string) =>
+ /^[-+]?(?:[$€£]?[\d.,]*\d%?|\d+:\d{2}(?::\d{2})?)$/.test(value);
/** A spreadsheet runs a cell that starts with one of these as a formula. A
- * plain number, such as `-2.5`, stays as it is. */
+ * plain number, such as `-2.5`, `-€5` or `-1:30`, stays as it is. */
const guardFormula = (value: string) =>
/^[=+\-@]/.test(value) && !isPlainNumber(value) ? `'${value}` : value;
diff --git a/packages/core/src/services/assistant-share.test.ts b/packages/core/src/services/assistant-share.test.ts
index 3eed881a..155dbf48 100644
--- a/packages/core/src/services/assistant-share.test.ts
+++ b/packages/core/src/services/assistant-share.test.ts
@@ -154,6 +154,19 @@ describe("search", () => {
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" }]);
diff --git a/packages/core/src/services/assistant-undo.test.ts b/packages/core/src/services/assistant-undo.test.ts
index b67e112e..e8c81dac 100644
--- a/packages/core/src/services/assistant-undo.test.ts
+++ b/packages/core/src/services/assistant-undo.test.ts
@@ -26,6 +26,7 @@ import {
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";
@@ -45,6 +46,8 @@ 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: "",
@@ -109,6 +112,7 @@ beforeAll(async () => {
setChatModelForTests({
streamChatCompletion: async (opts) => {
seen.push(opts.messages);
+ await onGenerate?.();
return present(script.shift(), "scripted turn");
},
listModels: async () => [],
@@ -184,6 +188,7 @@ afterAll(async () => {
beforeEach(async () => {
script = [];
seen = [];
+ onGenerate = null;
await db.delete(assistantConversation);
await db.delete(assistantSettings);
await db.delete(timeEntry);
@@ -284,6 +289,56 @@ describe("undo", () => {
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);
@@ -366,6 +421,51 @@ describe("replaceLastTurn", () => {
);
});
+ 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("is refused for another person's conversation", async () => {
const chatId = await loggedThread();
await expect(
diff --git a/packages/core/src/services/assistant-undo.ts b/packages/core/src/services/assistant-undo.ts
index b169f166..cbc5f65c 100644
--- a/packages/core/src/services/assistant-undo.ts
+++ b/packages/core/src/services/assistant-undo.ts
@@ -1,6 +1,12 @@
+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";
@@ -14,6 +20,14 @@ export class UndoStaleError extends UserFacingError {
}
}
+/** 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;
@@ -51,7 +65,8 @@ export const undoCreateEntry: UndoCapturer = async () => (result) => {
export const undoUpdateEntry: UndoCapturer = async (ctx, args) => {
const before = await entryBefore(ctx, args);
- if (!before) return null;
+ // `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 (
@@ -98,6 +113,23 @@ export const undoOvertime: UndoCapturer = async (ctx, args) => {
};
};
+/** 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) => {
@@ -107,6 +139,7 @@ export const applyUndo = async (ctx: Ctx, undo: AssistantUndo) => {
}
switch (undo.kind) {
case "delete_entry":
+ if (await holdsEvidence(undo.entryId)) throw new UndoHasEvidenceError();
await timeEntriesService.remove(ctx, undo.entryId);
return;
case "restore_entry":
diff --git a/packages/core/src/services/assistant-wire.ts b/packages/core/src/services/assistant-wire.ts
index 09d81226..1158f53d 100644
--- a/packages/core/src/services/assistant-wire.ts
+++ b/packages/core/src/services/assistant-wire.ts
@@ -1,7 +1,7 @@
import type { ChatMessage } from "../lib/openrouter-client";
/** Turns (user messages) whose tool results stay whole. Older ones are
- * stubbed. A fixed count keeps the prompt prefix the same between turns. */
+ * 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. */
diff --git a/packages/core/src/services/assistant.service.ts b/packages/core/src/services/assistant.service.ts
index aeaef5a8..8e87de3e 100644
--- a/packages/core/src/services/assistant.service.ts
+++ b/packages/core/src/services/assistant.service.ts
@@ -22,6 +22,7 @@ import {
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";
@@ -64,7 +65,6 @@ import { elideOldToolResults, undoneContent } from "./assistant-wire";
import { diffFields, recordAudit } from "./audit";
import { ctxAccess, ctxTimezone, requireAdmin } from "./context";
import { agentErrorMessage } from "./error-message";
-import { membersService } from "./members.service";
import type { Ctx } from "./types";
export class AssistantError extends UserFacingError {
@@ -146,7 +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;
- catalogue = null;
+ catalogues.clear();
};
// ── events ───────────────────────────────────────────────────────────────────
@@ -503,27 +503,38 @@ const requireConversation = async (ctx: Ctx, conversationId: string) => {
};
const MODEL_CATALOGUE_TTL_MS = 60 * 60 * 1000;
-let catalogue: { at: number; lengths: Map } | null =
- null;
+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 }
+>();
/** The context size of a model, for the meter. Any member may see it, so it
- * skips the admin gate of `listModels`. A failed lookup gives null. */
+ * skips the admin gate of `listModels`. A failed lookup gives null, and is
+ * kept for a minute so a broken key is not retried on every read. */
const contextLengthOf = async (
ctx: Ctx,
modelId: string,
): Promise => {
+ const cached = catalogues.get(ctx.organizationId);
+ if (cached && Date.now() - cached.at <= MODEL_CATALOGUE_TTL_MS) {
+ return cached.lengths.get(modelId) ?? null;
+ }
try {
- if (!catalogue || Date.now() - catalogue.at > MODEL_CATALOGUE_TTL_MS) {
- const row = await loadSettings(ctx);
- if (!row?.apiKey) return null;
- const models = await chatModel().listModels(row.apiKey);
- catalogue = {
- at: Date.now(),
- lengths: new Map(models.map((m) => [m.id, m.contextLength])),
- };
- }
- return catalogue.lengths.get(modelId) ?? null;
- } catch {
+ const row = await loadSettings(ctx);
+ if (!row?.apiKey) return null;
+ const models = await chatModel().listModels(row.apiKey);
+ const lengths = new Map(models.map((m) => [m.id, m.contextLength]));
+ catalogues.set(ctx.organizationId, { at: Date.now(), lengths });
+ return lengths.get(modelId) ?? null;
+ } catch (error) {
+ console.error("[assistant] model catalogue failed", loggableError(error));
+ // Fresh enough to skip a retry for the failure TTL, empty so it gives null.
+ catalogues.set(ctx.organizationId, {
+ at: Date.now() - MODEL_CATALOGUE_TTL_MS + MODEL_CATALOGUE_FAILURE_TTL_MS,
+ lengths: new Map(),
+ });
return null;
}
};
@@ -620,6 +631,15 @@ const containsTerm = (column: AnyPgColumn, term: string): SQL => {
return sql`${column} ilike ${`%${escaped}%`} escape '\\'`;
};
+/** Raw characters kept on each side of the match. More than a snippet, because
+ * `plainText` removes markup afterwards. */
+const WINDOW_CHARS = 400;
+
+/** A slice of the column around the first match, so a long message is not
+ * loaded whole. A match with no literal position (case folding) starts at 1. */
+const windowAround = (column: AnyPgColumn, term: string): SQL =>
+ sql`substring(${column} from greatest(1, position(lower(${term}::text) in lower(${column})) - ${sql.raw(String(WINDOW_CHARS))}) for ${sql.raw(String(term.length + 2 * WINDOW_CHARS))})`;
+
/** About `SNIPPET_CHARS` of plain text around the first match. A match that
* only sat in removed markup falls back to the start of the text. */
const snippetAround = (content: string, term: string): string => {
@@ -671,7 +691,7 @@ const search = async (ctx: Ctx, input: SearchConversationsInput) => {
const hits = await db
.select({
conversationId: assistantMessage.conversationId,
- content: assistantMessage.content,
+ content: windowAround(assistantMessage.content, term),
})
.from(assistantMessage)
.where(
@@ -772,21 +792,25 @@ const getShared = async (ctx: Ctx, conversationId: string) => {
});
if (!conversation?.sharedAt)
throw new AssistantError("Conversation not found");
- const [messages, roster] = await Promise.all([
+ const [messages, [sharer]] = await Promise.all([
db.query.assistantMessage.findMany({
where: eq(assistantMessage.conversationId, conversation.id),
orderBy: asc(assistantMessage.createdAt),
}),
- membersService.roster(ctx),
+ conversation.sharedBy
+ ? db
+ .select({ name: user.name, image: user.image })
+ .from(user)
+ .where(eq(user.id, conversation.sharedBy))
+ : [],
]);
- const sharer = roster.members.find((m) => m.userId === conversation.sharedBy);
return {
conversation,
messages: messages.map(readOnlyRow),
sharedAt: conversation.sharedAt,
sharedBy: {
- name: sharer?.user.name ?? "A colleague",
- image: sharer?.user.image ?? null,
+ name: sharer?.name ?? "A colleague",
+ image: sharer?.image ?? null,
},
};
};
@@ -937,6 +961,33 @@ const insertMessage = async (
return row;
};
+/** The id of the question a turn answers: the last user row of its history. */
+const questionId = (history: StoredMessage[]): string | null =>
+ history.filter((row) => row.role === "user").at(-1)?.id ?? null;
+
+/**
+ * Store an assistant row, unless its question was removed meanwhile.
+ * `replaceLastTurn` can delete the question while the model still writes.
+ * A share lock on the question row makes the check and the insert one step.
+ */
+const insertAnswer = async (
+ ctx: Ctx,
+ conversationId: string,
+ questionRowId: string | null,
+ values: Parameters[2],
+) =>
+ db.transaction(async (tx) => {
+ if (questionRowId) {
+ const [question] = await tx
+ .select({ id: assistantMessage.id })
+ .from(assistantMessage)
+ .where(eq(assistantMessage.id, questionRowId))
+ .for("share");
+ if (!question) return null;
+ }
+ return insertMessage(ctx, conversationId, values, { client: tx });
+ });
+
/**
* Take the right to answer one tool call — or a run of them — by writing their
* answers.
@@ -1891,9 +1942,10 @@ const keepPartial = async (
ctx: Ctx,
conversation: { id: string; model: string },
turn: ChatTurn,
+ questionRowId: string | null,
): Promise => {
if (!turn.content.trim()) return;
- await insertMessage(ctx, conversation.id, {
+ const row = await insertAnswer(ctx, conversation.id, questionRowId, {
role: "assistant",
content: turn.content,
toolCalls: null,
@@ -1902,7 +1954,7 @@ const keepPartial = async (
completionTokens: turn.completionTokens,
pendingApproval: false,
});
- await touchConversation(conversation.id);
+ if (row) await touchConversation(conversation.id);
};
/** Bump the thread so the rail orders by real activity, not by creation. */
@@ -2089,8 +2141,9 @@ const reportCut = async (
error: OpenRouterStreamCutError,
signal: AbortSignal | undefined,
onEvent: EmitEvent,
+ questionRowId: string | null,
): Promise => {
- await keepPartial(ctx, conversation, error.partial);
+ await keepPartial(ctx, conversation, error.partial, questionRowId);
if (!signal?.aborted)
onEvent({
type: "error",
@@ -2110,6 +2163,7 @@ const runStep = async (
const { conversation, signal, onEvent } = run;
const history = await loadHistory(conversation.id);
if (await resurfaceSuspended(ctx, history, onEvent)) return "ended";
+ const question = questionId(history);
let turn: ChatTurn;
try {
@@ -2125,7 +2179,7 @@ const runStep = async (
});
} catch (error) {
if (error instanceof OpenRouterStreamCutError) {
- await reportCut(ctx, conversation, error, signal, onEvent);
+ await reportCut(ctx, conversation, error, signal, onEvent, question);
return "ended";
}
if (error instanceof OpenRouterError) {
@@ -2145,7 +2199,7 @@ const runStep = async (
// An empty partial stores nothing and reports nothing: stopping a turn
// before it said anything is not a failure to explain.
if (signal?.aborted) {
- await keepPartial(ctx, conversation, turn);
+ await keepPartial(ctx, conversation, turn, question);
return "ended";
}
@@ -2163,7 +2217,7 @@ const runStep = async (
return "ended";
}
- const assistantRow = await insertMessage(ctx, conversation.id, {
+ const assistantRow = await insertAnswer(ctx, conversation.id, question, {
role: "assistant",
content: turn.content,
toolCalls: turn.toolCalls.length ? turn.toolCalls : null,
@@ -2173,6 +2227,8 @@ const runStep = async (
// Decided below, once we know whether any call needs consent.
pendingApproval: false,
});
+ // The question was removed while the model wrote: drop the answer.
+ if (!assistantRow) return "ended";
await touchConversation(conversation.id);
if (turn.toolCalls.length === 0) {
@@ -2206,12 +2262,14 @@ const closeOutOfSteps = async (ctx: Ctx, run: TurnRun): Promise => {
if (signal?.aborted) return;
let closing: ChatTurn | null = null;
+ const history = await loadHistory(conversation.id);
+ const question = questionId(history);
try {
closing = await generate(ctx, run.trace, null, {
apiKey: run.config.apiKey,
messages: [
{ role: "system", content: run.system },
- ...toWireMessages(await loadHistory(conversation.id)),
+ ...toWireMessages(history),
{ role: "user", content: OUT_OF_STEPS },
],
signal,
@@ -2225,7 +2283,7 @@ const closeOutOfSteps = async (ctx: Ctx, run: TurnRun): Promise => {
if (error instanceof OpenRouterStreamCutError) {
// A cut closing answer is a failure of its own: the person is told
// the connection closed, not that the model kept working.
- await reportCut(ctx, conversation, error, signal, onEvent);
+ await reportCut(ctx, conversation, error, signal, onEvent, question);
return;
}
}
@@ -2234,7 +2292,7 @@ const closeOutOfSteps = async (ctx: Ctx, run: TurnRun): Promise => {
// model about its own ceiling, and a later turn re-reading it as something
// the person said would be a lie about the conversation.
if (closing?.content.trim()) {
- await insertMessage(ctx, conversation.id, {
+ const row = await insertAnswer(ctx, conversation.id, question, {
role: "assistant",
content: closing.content,
model: conversation.model,
@@ -2242,7 +2300,7 @@ const closeOutOfSteps = async (ctx: Ctx, run: TurnRun): Promise => {
completionTokens: closing.completionTokens,
pendingApproval: false,
});
- await touchConversation(conversation.id);
+ if (row) await touchConversation(conversation.id);
onEvent({ type: "done" });
return;
}
@@ -2353,6 +2411,13 @@ const NOT_RUN_RESULTS = new Set([
NOT_REACHED,
]);
+/** The failures `executeTool` returns before it runs the tool. */
+const REFUSED_BEFORE_RUN = [
+ /^Unknown tool "/,
+ /^".*" is not available to this user\.$/,
+ /^The arguments were not (a JSON object|valid JSON)\.$/,
+];
+
/** Whether a tool row is a write or a destructive call that ran and stands. */
const changedData = (row: StoredMessage) => {
const kind = row.toolName ? findTool(row.toolName)?.kind : undefined;
@@ -2362,7 +2427,8 @@ const changedData = (row: StoredMessage) => {
return (
!row.undoneAt &&
!NOT_RUN_RESULTS.has(row.content) &&
- !row.content.startsWith("Error:")
+ !row.content.startsWith("Error:") &&
+ !REFUSED_BEFORE_RUN.some((pattern) => pattern.test(row.content))
);
};
From bb08b89cf024de4cb8e1c490a3bdff6c23dfaa76 Mon Sep 17 00:00:00 2001
From: Omar Zunic
Date: Wed, 11 Nov 2026 22:11:10 +0100
Subject: [PATCH 12/16] fix(web): fit the ask dialog chip and focus the field
The form was a grid with an auto column, so a long page sentence
widened the dialog and made it scroll sideways instead of truncating.
Focus also landed on the chip's remove button, not the question field.
---
.../components/assistant/ask-assistant.tsx | 21 ++++++++++++++-----
1 file changed, 16 insertions(+), 5 deletions(-)
diff --git a/apps/web/src/components/assistant/ask-assistant.tsx b/apps/web/src/components/assistant/ask-assistant.tsx
index 211b2abc..ee6b9724 100644
--- a/apps/web/src/components/assistant/ask-assistant.tsx
+++ b/apps/web/src/components/assistant/ask-assistant.tsx
@@ -8,6 +8,7 @@ import {
useContext,
useEffect,
useMemo,
+ useRef,
useState,
useSyncExternalStore,
} from "react";
@@ -111,11 +112,17 @@ type DialogProps = Omit & {
};
function AskDialog({ open, onOpenChange, ...page }: DialogProps) {
+ const inputRef = useRef(null);
return (
);
@@ -126,7 +133,11 @@ function AskForm({
timezone,
weekStartsOn,
close,
-}: Omit & { close: () => void }) {
+ inputRef,
+}: Omit & {
+ close: () => void;
+ inputRef: React.RefObject;
+}) {
const queryClient = useQueryClient();
const navigate = useNavigate();
const actions = useAssistantActions();
@@ -184,7 +195,7 @@ function AskForm({
return (