diff --git a/apps/mobile/app/assistant/index.tsx b/apps/mobile/app/assistant/index.tsx index 52bfb244..cce136db 100644 --- a/apps/mobile/app/assistant/index.tsx +++ b/apps/mobile/app/assistant/index.tsx @@ -15,6 +15,11 @@ import { } from "../../src/assistant/new-chat-action"; import { RenameDialog } from "../../src/assistant/rename-dialog"; import { useThreadRunning } from "../../src/assistant/runs"; +import { + ThreadSearchBox, + ThreadSearchResults, + useThreadSearch, +} from "../../src/assistant/thread-search"; import { ActionButton, EmptyState, @@ -97,6 +102,7 @@ export default function AssistantThreadsScreen() { const palette = usePalette(); const plain = usePlainBackground(); const threads = useAssistantThreads(); + const search = useThreadSearch(); const ready = useAssistantReady(); const rename = useRenameThread(); const remove = useDeleteThread(); @@ -137,67 +143,75 @@ export default function AssistantThreadsScreen() { }} /> - thread.id} - contentInsetAdjustmentBehavior="automatic" - refreshControl={ - - } - ListHeaderComponent={ - error ? ( - - - - ) : null - } - ListEmptyComponent={ - threads.isPending ? ( - - - - - - - - ) : threads.error ? ( - void threads.refetch()} + + {search.active ? ( + + ) : ( + thread.id} + contentInsetAdjustmentBehavior="automatic" + refreshControl={ + - ) : ( - + } + ListHeaderComponent={ + error ? ( + + + + ) : null + } + ListEmptyComponent={ + threads.isPending ? ( + + + + + + + + ) : threads.error ? ( + void threads.refetch()} + /> + ) : ( + + } + /> + ) + } + renderItem={({ item }) => ( + + router.push({ + pathname: "/assistant/[id]", + params: { id: item.id }, + }) } + onRename={() => setRenaming(item)} + onDelete={() => confirmDelete(item)} /> - ) - } - renderItem={({ item }) => ( - - router.push({ - pathname: "/assistant/[id]", - params: { id: item.id }, - }) - } - onRename={() => setRenaming(item)} - onDelete={() => confirmDelete(item)} - /> - )} - /> + )} + /> + )} {/* No new chat while the gate above says why the assistant cannot answer. */} diff --git a/apps/mobile/app/assistant/shared/[id].tsx b/apps/mobile/app/assistant/shared/[id].tsx new file mode 100644 index 00000000..196c545a --- /dev/null +++ b/apps/mobile/app/assistant/shared/[id].tsx @@ -0,0 +1,38 @@ +import { Stack, useLocalSearchParams } from "expo-router"; + +import { useWorkspace } from "../../../src/api/queries"; +import { AssistantGate } from "../../../src/assistant/gate"; +import { SharedChat } from "../../../src/assistant/shared-chat"; +import { otherWorkspace } from "../../../src/assistant/shared-target"; +import { EmptyState } from "../../../src/ui/components"; + +/** A chat that its owner shared with the workspace. Read only. */ +function SharedChatOrMismatch({ id }: { id: string }) { + const { org, server } = useLocalSearchParams<{ + org?: string; + server?: string; + }>(); + const w = useWorkspace(); + const other = otherWorkspace({ org, server }, w); + if (!other) return ; + return ( + + ); +} + +export default function SharedConversationScreen() { + const { id } = useLocalSearchParams<{ id: string }>(); + return ( + <> + + + + + + ); +} diff --git a/apps/mobile/app/workspace/assistant.tsx b/apps/mobile/app/workspace/assistant.tsx index 11a4f4e0..3fb71540 100644 --- a/apps/mobile/app/workspace/assistant.tsx +++ b/apps/mobile/app/workspace/assistant.tsx @@ -1,7 +1,7 @@ import { Redirect } from "expo-router"; -/** The assistant's settings are a part of the workspace integrations, as on - * the web. This route stays for a link that points here. */ +/** The assistant's settings are a part of the workspace integrations in the + * app. This route stays for a link that points here. */ export default function AssistantSettingsScreen() { return ; } diff --git a/apps/mobile/src/api/assistant.ts b/apps/mobile/src/api/assistant.ts index 731eb5cc..89b283cc 100644 --- a/apps/mobile/src/api/assistant.ts +++ b/apps/mobile/src/api/assistant.ts @@ -134,3 +134,64 @@ export const useUpdateAssistantSettings = () => export const useDisconnectAssistant = () => useSettingsChange((w) => w.client.disconnectAssistant(w.slug)); + +/** Undo one write from its trace row. A write can change anything the + * workspace shows, so the whole workspace is stale after it. */ +export const useUndoWrite = () => { + const w = useWorkspace(); + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: ({ id, messageId }: { id: string; messageId: string }) => + w.client.undoAssistantWrite(w.slug, id, messageId), + onSuccess: () => queryClient.invalidateQueries({ queryKey: scope(w) }), + }); +}; + +/** Take back the last question. Answers with its text, to send again. */ +export const useRewindThread = () => { + const w = useWorkspace(); + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (id: string) => w.client.rewindAssistantThread(w.slug, id), + onSuccess: (_, id) => + queryClient.invalidateQueries({ queryKey: threadKey(w, id) }), + }); +}; + +/** The person's threads whose title or text match `q`. Off below two + * characters, as the server refuses them. */ +export const useSearchThreads = (q: string) => { + const w = useWorkspace(); + return useQuery({ + queryKey: [...assistantKey(w), "search", q], + queryFn: () => w.client.searchAssistantThreads(w.slug, { q }), + enabled: q.length >= 2, + }); +}; + +/** One thread that its owner shared. Read only. */ +export const useSharedThread = (id: string) => { + const w = useWorkspace(); + return useQuery({ + queryKey: [...assistantKey(w), "shared", id], + queryFn: () => w.client.getSharedAssistantThread(w.slug, id), + retry: false, + }); +}; + +/** Share a thread with the workspace, or stop sharing it. */ +export const useSetThreadShared = () => { + const w = useWorkspace(); + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: ({ id, shared }: { id: string; shared: boolean }) => + shared + ? w.client.shareAssistantThread(w.slug, id) + : w.client.unshareAssistantThread(w.slug, id), + onSuccess: (_, { id }) => + Promise.all([ + queryClient.invalidateQueries({ queryKey: threadsKey(w) }), + queryClient.invalidateQueries({ queryKey: threadKey(w, id) }), + ]), + }); +}; diff --git a/apps/mobile/src/assistant/chat.tsx b/apps/mobile/src/assistant/chat.tsx index 6d7b0309..723901f2 100644 --- a/apps/mobile/src/assistant/chat.tsx +++ b/apps/mobile/src/assistant/chat.tsx @@ -18,9 +18,14 @@ import { SPACE } from "../ui/type"; 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"; import { ToolTraceList } from "./tool-trace"; import { visibleMessages, visiblePending } from "./turn"; +import { UserMessage } from "./user-message"; const SUGGESTIONS = [ "How many hours did I log last week?", @@ -31,26 +36,6 @@ const SUGGESTIONS = [ /** Closer to the end than this, the transcript follows a new answer. */ const PIN_DISTANCE = 96; -/** One thing the person said. */ -function UserMessage({ text }: { text: string }) { - const palette = usePalette(); - return ( - - - {text} - - - ); -} - /** True while the keyboard is open, to drop the bottom inset under it. */ const useKeyboardOpen = () => { const [open, setOpen] = useState(false); @@ -89,6 +74,7 @@ export function Chat({ id: routeId }: { id: string | null }) { const [startedId, setStartedId] = useState(null); const id = routeId ?? startedId; const thread = useAssistantThread(id); + const headerActions = useChatHeaderActions(thread.data?.thread); const runId = id ?? draftId ?? ""; const run = useRun(runId); const actions = useRunActions(); @@ -109,6 +95,13 @@ export function Chat({ id: routeId }: { id: string | null }) { run.sentMessageId !== null && messages.some((message) => message.id === run.sentMessageId); const busy = run.isStreaming; + const lastUserIndex = rows.map((row) => row.role).lastIndexOf("user"); + const editBlock = busy + ? "Wait for the answer to finish." + : pending + ? "Answer the card first." + : editBlockReason(messages); + const [restore, setRestore] = useState<{ text: string } | null>(null); const send = async (text: string) => { pinned.current = true; @@ -153,15 +146,7 @@ export function Chat({ id: routeId }: { id: string | null }) { {/* The history is one tap away, so Back leaves the assistant at once. `dismissTo` goes back to the list when it is under this chat, and replaces the chat with it when it is not. */} - router.dismissTo("/assistant"), - }, - ]} - /> + ) : null} - {rows.map((message) => - message.role === "user" ? ( - - ) : ( + {rows.map((message, index) => { + if (message.role === "user") { + return ( + + + {index === lastUserIndex && id !== null ? ( + setRestore({ text })} + /> + ) : null} + + ); + } + if (message.role === "tool") { + return id === null ? null : ( + + ); + } + return ( - ), - )} + ); + })} {run.sentMessage !== null && !sentStored ? ( @@ -304,6 +314,11 @@ export function Chat({ id: routeId }: { id: string | null }) { {run.error ? : null} {draftError ? : null} + router.replace("/assistant/new")} + /> runId !== "" && actions.stop(runId)} @@ -312,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..79440d86 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,26 @@ export function Composer({ const input = useRef(null); const canSend = text.trim() !== "" && !streaming && !locked; + const giveBack = (message: string) => { + // Text typed meanwhile stays; the failed text goes below it. + setText((current) => + current === "" || current === message + ? message + : `${current}\n\n${message}`, + ); + 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/context-note.tsx b/apps/mobile/src/assistant/context-note.tsx new file mode 100644 index 00000000..5acd50a9 --- /dev/null +++ b/apps/mobile/src/assistant/context-note.tsx @@ -0,0 +1,63 @@ +import { Platform, Pressable, View } from "react-native"; + +import { Text } from "../ui/components"; +import { usePalette } from "../ui/theme"; +import { SPACE } from "../ui/type"; + +/** The note shows from this share of the model's context. */ +const NOTE_FROM = 0.7; + +/** Tells the person that a long chat fills the model's memory. */ +export function ContextNote({ + used, + limit, + onNewChat, +}: { + used: number | null | undefined; + limit: number | null | undefined; + onNewChat: () => void; +}) { + const palette = usePalette(); + if (!used || !limit || used / limit < NOTE_FROM) return null; + const percent = Math.min(100, Math.round((used / limit) * 100)); + const android = Platform.OS === "android"; + return ( + + + + This chat uses {percent}% of the model's memory. Start a new chat for + best results. + + + + + New chat + + + + ); +} 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/share.ts b/apps/mobile/src/assistant/share.ts new file mode 100644 index 00000000..57bcd832 --- /dev/null +++ b/apps/mobile/src/assistant/share.ts @@ -0,0 +1,71 @@ +import type { AssistantThread } from "@farmer/api-client"; +import { useRouter } from "expo-router"; +import { Platform, Share } from "react-native"; + +import { useSetThreadShared } from "../api/assistant"; +import { useWhoami, useWorkspace } from "../api/queries"; +import type { HeaderAction } from "../navigation/header-actions.shared"; +import { showDialog } from "../ui/dialog"; + +/** The warning of the share dialog, as on the web. */ +const warning = (orgName: string) => + `Anyone in ${orgName} with the link can read this chat. It can show data that you can see and they cannot, for example a team report. Share only what you would show them.`; + +/** The web page of a shared chat. The web page links on to the app. */ +export const sharedLink = (origin: string, slug: string, id: string) => + `${origin.replace(/\/+$/, "")}/${slug}/assistant/shared/${id}`; + +const shareLink = (link: string) => + Share.share(Platform.OS === "ios" ? { url: link } : { message: link }); + +/** + * The buttons at the end of the header of a chat: the history, and, once the + * chat has a thread, Share. Share asks first, then opens the share sheet with + * the web link. A shared chat offers the link again and Stop sharing. + */ +export const useChatHeaderActions = ( + thread: AssistantThread | undefined, +): HeaderAction[] => { + const router = useRouter(); + const w = useWorkspace(); + const setShared = useSetThreadShared(); + const orgName = useWhoami().data?.organization.name ?? "your workspace"; + const history: HeaderAction = { + icon: "chats", + label: "Chat history", + onPress: () => router.dismissTo("/assistant"), + }; + if (!thread) return [history]; + const link = sharedLink(w.origin, w.slug, thread.id); + const change = (shared: boolean) => + setShared.mutate( + { id: thread.id, shared }, + { + onSuccess: () => { + if (shared) void shareLink(link); + }, + onError: (failure) => + showDialog("The change was not saved", failure.message), + }, + ); + const open = () => + showDialog( + "Share this chat", + warning(orgName), + thread.sharedAt + ? [ + { text: "Cancel", style: "cancel" }, + { + text: "Stop sharing", + style: "destructive", + onPress: () => change(false), + }, + { text: "Share the link", onPress: () => void shareLink(link) }, + ] + : [ + { text: "Cancel", style: "cancel" }, + { text: "Share", onPress: () => change(true) }, + ], + ); + return [{ icon: "share", label: "Share this chat", onPress: open }, history]; +}; diff --git a/apps/mobile/src/assistant/shared-chat.tsx b/apps/mobile/src/assistant/shared-chat.tsx new file mode 100644 index 00000000..1cd83f2a --- /dev/null +++ b/apps/mobile/src/assistant/shared-chat.tsx @@ -0,0 +1,66 @@ +import { ScrollView, View } from "react-native"; + +import { useSharedThread } from "../api/assistant"; +import { ErrorState, Skeleton, Text } from "../ui/components"; +import { usePalette } from "../ui/theme"; +import { SPACE } from "../ui/type"; +import { Answer } from "./answer"; +import { UserMessage } from "./user-message"; + +/** + * A chat that its owner shared, as a transcript with a banner. It has no + * composer, no approval card and no undo. The banner says that the chat can + * show data that the reader cannot normally see. + */ +export function SharedChat({ id }: { id: string }) { + const palette = usePalette(); + const shared = useSharedThread(id); + if (shared.isPending) { + return ( + + + + + ); + } + if (shared.error) { + return ( + void shared.refetch()} /> + ); + } + const { sharedBy, sharedAt, messages, thread } = shared.data; + const when = new Date(sharedAt).toLocaleDateString(undefined, { + day: "numeric", + month: "short", + year: "numeric", + }); + return ( + + + + Shared by {sharedBy.name} on {when}. It can show data that you cannot + normally see. + + + {thread.title} + {messages.map((message) => { + if (message.role === "user") { + return ; + } + if (message.role === "assistant" && message.content.trim()) { + return ; + } + return null; + })} + + ); +} diff --git a/apps/mobile/src/assistant/shared-target.test.ts b/apps/mobile/src/assistant/shared-target.test.ts new file mode 100644 index 00000000..83028178 --- /dev/null +++ b/apps/mobile/src/assistant/shared-target.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, test } from "bun:test"; + +import { otherWorkspace } from "./shared-target"; + +const current = { origin: "https://farmer.example.com", slug: "acme" }; + +describe("otherWorkspace", () => { + test("matches when both params are absent or equal", () => { + expect(otherWorkspace({}, current)).toBeNull(); + expect( + otherWorkspace( + { org: "acme", server: "https://farmer.example.com/" }, + current, + ), + ).toBeNull(); + }); + + test("names the server host and the org on a mismatch", () => { + expect(otherWorkspace({ org: "beta" }, current)).toEqual({ + server: "farmer.example.com", + org: "beta", + }); + expect( + otherWorkspace({ server: "https://other.example.org:8080" }, current), + ).toEqual({ server: "other.example.org:8080", org: "acme" }); + }); +}); diff --git a/apps/mobile/src/assistant/shared-target.ts b/apps/mobile/src/assistant/shared-target.ts new file mode 100644 index 00000000..59bf7a9d --- /dev/null +++ b/apps/mobile/src/assistant/shared-target.ts @@ -0,0 +1,25 @@ +const stripSlashes = (value: string) => value.replace(/\/+$/, ""); + +// A malformed link must not throw: show the raw text. +const hostOf = (url: string) => { + try { + return new URL(url).host; + } catch { + return url; + } +}; + +/** Why a deep link points at another workspace, or null when it matches. */ +export function otherWorkspace( + link: { org?: string; server?: string }, + current: { origin: string; slug: string }, +): { server: string; org: string } | null { + const server = link.server ? stripSlashes(link.server) : undefined; + const sameServer = !server || server === stripSlashes(current.origin); + const sameOrg = !link.org || link.org === current.slug; + if (sameServer && sameOrg) return null; + return { + server: hostOf(server ?? current.origin), + org: link.org ?? current.slug, + }; +} diff --git a/apps/mobile/src/assistant/stored-turn.tsx b/apps/mobile/src/assistant/stored-turn.tsx new file mode 100644 index 00000000..a59091e1 --- /dev/null +++ b/apps/mobile/src/assistant/stored-turn.tsx @@ -0,0 +1,161 @@ +import type { AssistantMessage } from "@farmer/api-client"; +import { useState } from "react"; +import { View } from "react-native"; + +import { useRewindThread, useUndoWrite } from "../api/assistant"; +import { + ActionButton, + ErrorBanner, + Field, + IconButton, + Text, +} from "../ui/components"; +import { usePalette } from "../ui/theme"; +import { SPACE } from "../ui/type"; +import { ToolTraceList } from "./tool-trace"; + +/** The trace row of a stored write: Undo, or "Undone". */ +export function StoredWrite({ + threadId, + message, + messages, + locked, +}: { + threadId: string; + message: AssistantMessage; + messages: AssistantMessage[]; + /** A turn runs or a card waits. */ + locked: boolean; +}) { + const undo = useUndoWrite(); + const call = messages + .flatMap((row) => row.toolCalls ?? []) + .find((entry) => entry.id === message.toolCallId); + if (!call) return null; + return ( + + + undo.mutate({ id: threadId, messageId: message.id }), + }, + }, + ]} + /> + {undo.error ? : null} + + ); +} + +/** + * Edit and Retry on the last question. Both take the question back from the + * server, then send the text again as a new turn. + */ +export function LastQuestionActions({ + threadId, + 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(); + const [editing, setEditing] = useState(false); + const [draft, setDraft] = useState(text); + const [failure, setFailure] = useState(null); + + const resend = async (next: string) => { + setFailure(null); + try { + await rewind.mutateAsync(threadId); + } 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) { + return ( + + + + setEditing(false)} + /> + void resend(draft.trim())} + /> + + {failure ? : null} + + ); + } + + return ( + + + { + setDraft(text); + setEditing(true); + }} + /> + void resend(text)} + /> + + {reason ? ( + + {reason} + + ) : null} + {failure ? : null} + + ); +} diff --git a/apps/mobile/src/assistant/thread-search.tsx b/apps/mobile/src/assistant/thread-search.tsx new file mode 100644 index 00000000..dc498e65 --- /dev/null +++ b/apps/mobile/src/assistant/thread-search.tsx @@ -0,0 +1,116 @@ +import { Stack, useRouter } from "expo-router"; +import { useEffect, useState } from "react"; +import { FlatList, Platform, View } from "react-native"; + +import { useSearchThreads } from "../api/assistant"; +import { EmptyState, ErrorState, ListRow, Skeleton } from "../ui/components"; +import { SearchField } from "../ui/search-field"; +import { SPACE } from "../ui/type"; + +const DEBOUNCE_MS = 250; +const MIN_CHARS = 2; + +/** The text in the search box, and the query it settles on. */ +export const useThreadSearch = () => { + const [text, setText] = useState(""); + const [query, setQuery] = useState(""); + useEffect(() => { + const timer = setTimeout(() => setQuery(text.trim()), DEBOUNCE_MS); + return () => clearTimeout(timer); + }, [text]); + return { + text, + setText, + // A cleared box shows the list at once. + query: text.trim() === "" ? "" : query, + active: text.trim() !== "", + }; +}; + +export type ThreadSearch = ReturnType; + +/** + * The search box of the thread list. iOS uses the search bar of the system + * header. Android draws the Material search bar above the list. + */ +export function ThreadSearchBox({ search }: { search: ThreadSearch }) { + if (Platform.OS === "ios") { + return ( + search.setText(event.nativeEvent.text), + onCancelButtonPress: () => search.setText(""), + }, + }} + /> + ); + } + return ( + + + + ); +} + +/** The threads that match, in place of the list. */ +export function ThreadSearchResults({ query }: { query: string }) { + const router = useRouter(); + const hits = useSearchThreads(query); + if (query.length < MIN_CHARS) { + return ( + + ); + } + if (hits.isPending) { + return ( + + + + + ); + } + if (hits.error) { + return ( + void hits.refetch()} /> + ); + } + return ( + hit.id} + keyboardShouldPersistTaps="handled" + contentInsetAdjustmentBehavior="automatic" + ListEmptyComponent={ + + } + renderItem={({ item }) => ( + + router.push({ + pathname: "/assistant/[id]", + params: { id: item.id }, + }) + } + /> + )} + /> + ); +} diff --git a/apps/mobile/src/assistant/tool-trace.tsx b/apps/mobile/src/assistant/tool-trace.tsx index cc644438..7c43793c 100644 --- a/apps/mobile/src/assistant/tool-trace.tsx +++ b/apps/mobile/src/assistant/tool-trace.tsx @@ -1,6 +1,7 @@ import { useState } from "react"; import { Pressable, View } from "react-native"; +import { ActionButton } from "../ui/action-button"; import { Text } from "../ui/components"; import { Icon } from "../ui/icon"; import { LoadingIndicator } from "../ui/loading"; @@ -16,13 +17,16 @@ import type { ToolTrace } from "./turn"; export function ToolTraceList({ traces, working, + open = false, }: { traces: ToolTrace[]; working: boolean; + /** Start open when settled, so a stored Undo is in view. */ + open?: boolean; }) { const palette = usePalette(); const [manual, setManual] = useState(null); - const expanded = manual ?? working; + const expanded = manual ?? (working || open); if (traces.length === 0) return null; const done = traces.filter((trace) => trace.ok !== null).length; @@ -31,7 +35,7 @@ export function ToolTraceList({ setManual((current) => !(current ?? working))} + onPress={() => setManual((current) => !(current ?? (working || open)))} hitSlop={8} style={{ flexDirection: "row", alignItems: "center", gap: SPACE.s }} > @@ -105,6 +109,20 @@ export function ToolTraceList({ ) : null} + {trace.undo ? ( + trace.undo.done ? ( + + Undone + + ) : ( + + ) + ) : null} ); })} diff --git a/apps/mobile/src/assistant/turn.test.ts b/apps/mobile/src/assistant/turn.test.ts index 6328b3d2..0cd6eec9 100644 --- a/apps/mobile/src/assistant/turn.test.ts +++ b/apps/mobile/src/assistant/turn.test.ts @@ -23,6 +23,9 @@ const message = ( approvalDecision: null, approvalSummary: null, approvalPreview: null, + undoable: false, + undone: false, + changed: false, createdAt: "2026-10-06T10:00:00.000Z", ...partial, }); diff --git a/apps/mobile/src/assistant/turn.ts b/apps/mobile/src/assistant/turn.ts index 9644cb5f..95396a1e 100644 --- a/apps/mobile/src/assistant/turn.ts +++ b/apps/mobile/src/assistant/turn.ts @@ -14,6 +14,13 @@ export type ToolTrace = { ok: boolean | null; /** The raw JSON that the model sent. */ arguments: string; + /** Only on a stored write that has an inverse. */ + undo?: { + done: boolean; + busy: boolean; + disabled: boolean; + onUndo: () => void; + }; }; export type ApprovalPreview = { @@ -210,11 +217,12 @@ export const visiblePending = ( }; /** The rows of a stored thread that the transcript draws: the person's - * messages and the assistant's text. A tool row and a pure tool turn are - * not drawn. */ + * messages, the assistant's text, and the tool row of a write that can be + * undone or was undone. Other tool rows and a pure tool turn are not drawn. */ export const visibleMessages = (messages: AssistantMessage[]) => messages.filter( (message) => message.role === "user" || + (message.role === "tool" && (message.undoable || message.undone)) || (message.role === "assistant" && message.content.trim() !== ""), ); diff --git a/apps/mobile/src/assistant/user-message.tsx b/apps/mobile/src/assistant/user-message.tsx new file mode 100644 index 00000000..a8efcfdb --- /dev/null +++ b/apps/mobile/src/assistant/user-message.tsx @@ -0,0 +1,25 @@ +import { View } from "react-native"; + +import { Text } from "../ui/components"; +import { usePalette } from "../ui/theme"; +import { SPACE } from "../ui/type"; + +/** One thing the person said. */ +export function UserMessage({ text }: { text: string }) { + const palette = usePalette(); + return ( + + + {text} + + + ); +} diff --git a/apps/mobile/src/ui/icons.ts b/apps/mobile/src/ui/icons.ts index 4acfbebb..cbbd2b22 100644 --- a/apps/mobile/src/ui/icons.ts +++ b/apps/mobile/src/ui/icons.ts @@ -40,6 +40,8 @@ export const ICONS = { holiday: { md: "beach-access", sf: "beach.umbrella" }, absence: { md: "event-busy", sf: "calendar.badge.minus" }, rewind: { md: "history", sf: "clock.arrow.circlepath" }, + undo: { md: "undo", sf: "arrow.uturn.backward" }, + retry: { md: "refresh", sf: "arrow.clockwise" }, people: { md: "people-outline", sf: "person.2" }, team: { md: "group", sf: "person.3" }, client: { md: "business", sf: "building.2" }, diff --git a/apps/mobile/src/workspace/assistant-settings.tsx b/apps/mobile/src/workspace/assistant-settings.tsx index 3242ce4f..f30cc4e4 100644 --- a/apps/mobile/src/workspace/assistant-settings.tsx +++ b/apps/mobile/src/workspace/assistant-settings.tsx @@ -40,7 +40,7 @@ const connectedOn = (iso: string | null) => : "-"; /** The model of a first connection, as the web's connect form sends it - * (`settings/workspace-integrations.tsx`). The admin changes it after the + * (`settings/ai.tsx`). The admin changes it after the * connection, because the server lists the models only with a key. */ const FIRST_MODEL = "openai/gpt-4o-mini"; @@ -155,7 +155,7 @@ function HouseRules({ settings }: { settings: AssistantSettings }) { /** * The assistant's settings for the workspace, as the web shows them in the - * workspace integrations. An admin connects the OpenRouter key + * AI settings page. An admin connects the OpenRouter key * (write-only), chooses the model, pauses the assistant, writes house rules * and disconnects it. A member does not see them, as on the web. */ diff --git a/apps/mobile/src/workspace/audit/labels.ts b/apps/mobile/src/workspace/audit/labels.ts index ae71adde..030d4c86 100644 --- a/apps/mobile/src/workspace/audit/labels.ts +++ b/apps/mobile/src/workspace/audit/labels.ts @@ -21,6 +21,8 @@ const KIND_LABELS = { "org_settings.updated": "Tracking settings changed", "reminder_settings.updated": "Reminder settings changed", "assistant_settings.updated": "Assistant settings changed", + "assistant_chat.shared": "Assistant chat shared", + "assistant_chat.unshared": "Assistant chat unshared", "audit_log.retention_changed": "Audit log retention changed", "audit_log.exported": "Audit log exported", "member.invited": "Person invited", diff --git a/apps/web/CLAUDE.md b/apps/web/CLAUDE.md index df58b86d..8d8f9811 100644 --- a/apps/web/CLAUDE.md +++ b/apps/web/CLAUDE.md @@ -13,7 +13,7 @@ bun run generate-routes # tsr generate — regenerates routeTree.gen.ts - `src/routes/` — TanStack Router file-based routing. - `$orgSlug/route.tsx` is the org-scoped layout: its `beforeLoad` resolves the session, the organization and the caller's role in ONE server call (`enterOrganization`) alongside `getPublicAppConfig`, and redirects out if any check fails — every nested route inherits that guard. `enterOrganization` repoints the session only when the active org actually differs. - - Under it: `index.tsx` (home: today, plus week and month targets), `time/` (a `route.tsx` layout with the targets strip and the unfiled banner, then `index`/`week`/`month`), `projects/` (the list, and `$projectId/` with `index`/`team`/`settings`), `reports.tsx`, `audit-log.tsx` (admins only, a sidebar row under Reports; see `docs/domains/audit-log.md`), `assistant.tsx`, and `settings/` (an `index.tsx` hub plus organization, members, my-schedule, clients, tasks, recurring-blocks, holidays, hour-fund, reminders, import, integrations, preferences, `webhooks/` — the endpoint list plus one endpoint's delivery log — and the Infrastructure group, shown only to a platform admin: platform-admins plus `instance/` (sign-in, email, storage, integrations, features — one page per section of `INSTANCE_SETTINGS`, all drawn by `components/instance-settings.tsx`; see ADR 0004)). + - Under it: `index.tsx` (home: today, plus week and month targets), `time/` (a `route.tsx` layout with the targets strip and the unfiled banner, then `index`/`week`/`month`), `projects/` (the list, and `$projectId/` with `index`/`team`/`settings`), `reports.tsx`, `audit-log.tsx` (admins only, a sidebar row under Reports; see `docs/domains/audit-log.md`), `assistant.tsx`, and `settings/` (an `index.tsx` hub plus organization, members, my-schedule, clients, tasks, recurring-blocks, holidays, hour-fund, reminders, import, integrations, ai (the assistant's settings and its usage), preferences, `webhooks/` — the endpoint list plus one endpoint's delivery log — and the Infrastructure group, shown only to a platform admin: platform-admins plus `instance/` (sign-in, email, storage, integrations, features — one page per section of `INSTANCE_SETTINGS`, all drawn by `components/instance-settings.tsx`; see ADR 0004)). - Outside it: `index.tsx` (a redirect into the workspace; the public pages live in `apps/site`, see `docs/domains/deployment.md`), `login.tsx`, `choose-organization.tsx` (the workspace chooser for a link such as `/:org/settings`; see `docs/domains/authentication.md`), `accept-invite/$invitationId.tsx`, `no-access.tsx`, `device.tsx` (approves a CLI login) and `cli/` (the install scripts and binary downloads). - Server routes: `api/auth/$.ts` (better-auth), `api/login.ts`, `api/mcp-login.ts`, `api/github/setup.ts`, `api/slack/callback.ts`, `api/files/$.ts`, `api/assistant/stream.ts`, `api/mcp/$orgSlug.ts`, `[.]well-known/oauth-*.ts`, `api/v1/projects` + `api/v1/time-entries` (cookie-authed REST reads), and `api/v1/{meta,me,session}`, `api/v1/me/devices` (the mobile app's phone, see `docs/domains/mobile.md`) + `api/v1/orgs/$orgSlug/*` (the CLI's API). `api/v1/openapi[.]json.ts` serves the OpenAPI document that `lib/openapi.ts` builds, and `api-docs.tsx` renders it with Scalar. **A new `api/v1` route needs an entry in `OPERATIONS`** — `lib/openapi.test.ts` fails until the two lists match, and each response schema there is checked against its `@farmer/core/api` type at compile time. That API takes two bearer credentials — a device-flow session token and a personal API token (`fmr_…`, Preferences → API tokens, `components/api-tokens-settings.tsx`); `docs/domains/api-tokens.md` has the rules, including the read-only 403 in `serve` and the `session` scheme that lets `/api-docs` send requests as the signed-in reader (`?org=` on the OpenAPI route; never add CORS headers to `api/v1`). All of that auth lives in `server/api-auth.ts` — deliberately NOT `server/auth.ts`, see the client-bundle rule below. - `reports.tsx` is the shell. Its four tabs — Time, Overtime, Tracking (`compliance`) and Absence — are declared in `components/reports/search.ts` and live in `components/reports/`. `periodSearch` there is shared with the project page. diff --git a/apps/web/src/components/app-sidebar.tsx b/apps/web/src/components/app-sidebar.tsx index 4c333606..890aa44c 100644 --- a/apps/web/src/components/app-sidebar.tsx +++ b/apps/web/src/components/app-sidebar.tsx @@ -24,6 +24,7 @@ import type { Survey } from "posthog-js"; import { useEffect, useRef, useState } from "react"; import { toast } from "sonner"; +import { AskShortcutHint } from "#/components/assistant/ask-assistant.tsx"; import { ConversationList } from "#/components/assistant/chat-rail.tsx"; import { ContributorsCard } from "#/components/contributors-card.tsx"; import { @@ -336,6 +337,7 @@ export function AppSidebar({ {item.label} + {item.to === ASSISTANT_ITEM.to && } {badge !== undefined && badge > 0 && ( { + const url = URL.createObjectURL(blob); + const link = document.createElement("a"); + link.href = url; + link.download = name; + link.click(); + // Revoked late: some browsers read the URL after the click returns. + setTimeout(() => URL.revokeObjectURL(url), 1000); +}; + +const saveCsv = (rows: string[][], name: string) => + saveBlob( + new Blob([toCsv(rows)], { type: "text/csv;charset=utf-8" }), + `${name}.csv`, + ); + +/** The computed color of a CSS variable, as a string a canvas accepts. */ +const cssColor = (name: string) => { + const probe = document.createElement("span"); + probe.style.color = `var(${name})`; + document.body.append(probe); + const color = getComputedStyle(probe).color; + probe.remove(); + return color; +}; + +type Palette = { + bg: string; + ink: string; + ink2: string; + track: string; + bar: string; +}; + +const readPalette = (): Palette => ({ + bg: cssColor("--bg"), + ink: cssColor("--ink"), + ink2: cssColor("--ink-2"), + track: cssColor("--inset"), + bar: cssColor("--chart-1"), +}); + +const printValue = (value: number, unit?: string) => + `${Math.round(value * 100) / 100}${unit ?? ""}`; + +const SCALE = 2; +const PAD = 16; +const TITLE_H = 28; + +type Draw = { + ctx: CanvasRenderingContext2D; + spec: ChartSpec; + palette: Palette; + width: number; + top: number; + peak: number; +}; + +const drawBars = ({ ctx, spec, palette, width, top, peak }: Draw) => { + const labelW = 160; + const valueW = 64; + const trackW = width - PAD * 2 - labelW - valueW; + spec.data.forEach((point, index) => { + const y = top + index * 24; + ctx.fillStyle = palette.ink2; + ctx.textAlign = "left"; + ctx.fillText(point.label.slice(0, 24), PAD, y + 12); + ctx.fillStyle = palette.track; + ctx.fillRect(PAD + labelW, y + 6, trackW, 10); + ctx.fillStyle = palette.bar; + const share = peak === 0 ? 0 : Math.max(0, point.value / peak); + ctx.fillRect(PAD + labelW, y + 6, Math.max(trackW * share, 1), 10); + ctx.fillStyle = palette.ink; + ctx.textAlign = "right"; + ctx.fillText(printValue(point.value, spec.unit), width - PAD, y + 12); + }); +}; + +const drawColumns = ({ ctx, spec, palette, width, top, peak }: Draw) => { + const slot = (width - PAD * 2) / spec.data.length; + const trackH = 120; + spec.data.forEach((point, index) => { + const x = PAD + index * slot; + const mid = x + slot / 2; + ctx.textAlign = "center"; + ctx.fillStyle = palette.ink2; + ctx.fillText(printValue(point.value, spec.unit), mid, top + 12); + ctx.fillStyle = palette.track; + ctx.fillRect(x + 2, top + 20, slot - 4, trackH); + ctx.fillStyle = palette.bar; + const share = peak === 0 ? 0 : Math.max(0, point.value / peak); + const barH = Math.max(trackH * share, 2); + ctx.fillRect(x + 2, top + 20 + trackH - barH, slot - 4, barH); + ctx.fillStyle = palette.ink2; + ctx.fillText(point.label.slice(0, 8), mid, top + trackH + 38); + }); +}; + +/** The chart is HTML and CSS, not SVG, so it is drawn again on a canvas + * from its spec with the colors of the current theme. */ +const renderChart = (spec: ChartSpec) => { + const trend = spec.type === "trend"; + const width = trend ? Math.max(640, spec.data.length * 44 + PAD * 2) : 640; + const top = PAD + (spec.title ? TITLE_H : 0); + const body = trend ? 170 : spec.data.length * 24; + const height = top + body + PAD; + const canvas = document.createElement("canvas"); + canvas.width = width * SCALE; + canvas.height = height * SCALE; + const ctx = canvas.getContext("2d"); + if (!ctx) return null; + ctx.scale(SCALE, SCALE); + const palette = readPalette(); + ctx.fillStyle = palette.bg; + ctx.fillRect(0, 0, width, height); + const font = getComputedStyle(document.body).fontFamily; + if (spec.title) { + ctx.font = `500 13px ${font}`; + ctx.fillStyle = palette.ink; + ctx.textAlign = "left"; + ctx.fillText(spec.title, PAD, PAD + 12); + } + ctx.font = `12px ${font}`; + const peak = Math.max(...spec.data.map((point) => Math.abs(point.value)), 0); + const draw = { ctx, spec, palette, width, top, peak }; + if (trend) drawColumns(draw); + else drawBars(draw); + return canvas; +}; + +const toPng = (canvas: HTMLCanvasElement) => + new Promise((resolve) => canvas.toBlob(resolve, "image/png")); + +const downloadPng = async (spec: ChartSpec, name: string) => { + const canvas = renderChart(spec); + const blob = canvas ? await toPng(canvas) : null; + if (!blob) { + toast.error("Could not make the image"); + return; + } + saveBlob(blob, `${name}.png`); +}; + +export function TableExport({ + head, + rows, + title, +}: { + head: string[]; + rows: string[][]; + title?: string; +}) { + const all = tableRows(head, rows); + const name = exportFileName(title, "farmer-table"); + const copy = async () => { + try { + await navigator.clipboard.writeText(toTsv(all)); + toast.success("Table copied"); + } catch { + toast.error("Could not copy the table"); + } + }; + return ( +
+ + +
+ ); +} + +export function ChartExport({ spec }: { spec: ChartSpec }) { + const name = exportFileName(spec.title, "farmer-chart"); + return ( +
+ + +
+ ); +} diff --git a/apps/web/src/components/assistant/answer-export.test.ts b/apps/web/src/components/assistant/answer-export.test.ts new file mode 100644 index 00000000..b8921f8a --- /dev/null +++ b/apps/web/src/components/assistant/answer-export.test.ts @@ -0,0 +1,94 @@ +/// +import { describe, expect, test } from "bun:test"; + +import { + chartRows, + exportFileName, + plainCell, + tableRows, + toCsv, + toTsv, +} from "./answer-export.ts"; + +const body = (csv: string) => csv.slice(1); + +describe("plainCell", () => { + test("strips bold, italic, code and links", () => { + expect(plainCell("**7.5h** and *x* `y`")).toBe("7.5h and x y"); + expect(plainCell("[Docs](https://example.com/a)")).toBe("Docs"); + }); + + test("turns a day link into the date", () => { + expect(plainCell("[[2026-08-03]]")).toBe("2026-08-03"); + }); +}); + +describe("toCsv", () => { + test("starts with a BOM and uses CRLF", () => { + const csv = toCsv([ + ["a", "b"], + ["1", "2"], + ]); + expect(csv.startsWith("")).toBe(true); + expect(body(csv)).toBe("a,b\r\n1,2\r\n"); + }); + + test("quotes commas, quotes and newlines", () => { + const csv = toCsv([["a,b", 'say "hi"', "x\ny"]]); + expect(body(csv)).toBe('"a,b","say ""hi""","x\ny"\r\n'); + }); + + test("guards a formula but not a negative number", () => { + const csv = toCsv([["=1+1", "+x", "@a", "-2.5", "-x", "+3"]]); + 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"); + }); +}); + +describe("toTsv", () => { + test("joins with tabs and flattens inner tabs and newlines", () => { + expect( + toTsv([ + ["a", "b\tc"], + ["1", "x\ny"], + ]), + ).toBe("a\tb c\n1\tx y"); + }); +}); + +describe("rows and names", () => { + test("tableRows puts the header first", () => { + expect(tableRows(["h"], [["r"]])).toEqual([["h"], ["r"]]); + }); + + test("chartRows names the unit", () => { + const rows = chartRows({ + type: "bar", + unit: "h", + data: [{ label: "A", value: 3.5 }], + }); + expect(rows).toEqual([ + ["Label", "Value (h)"], + ["A", "3.5"], + ]); + }); + + test("exportFileName slugs a heading and falls back", () => { + expect(exportFileName("**Hours** by project!", "x")).toBe( + "hours-by-project", + ); + expect(exportFileName(undefined, "farmer-table")).toBe("farmer-table"); + expect(exportFileName("???", "farmer-table")).toBe("farmer-table"); + }); +}); diff --git a/apps/web/src/components/assistant/answer-export.ts b/apps/web/src/components/assistant/answer-export.ts new file mode 100644 index 00000000..f3d43219 --- /dev/null +++ b/apps/web/src/components/assistant/answer-export.ts @@ -0,0 +1,66 @@ +// Pure helpers that turn a parsed table or chart into CSV or TSV text. +// The input is the output of `parseBlocks`, never the DOM. + +import type { ChartSpec } from "./answer-chart.tsx"; + +const BOM = ""; + +/** The text of a cell without its inline markdown. A `[[date]]` becomes the + * date, a link becomes its label. */ +export const plainCell = (cell: string) => + cell + .replace(/\[\[(\d{4}-\d{2}-\d{2})\]\]/g, "$1") + .replace(/\[([^\]\n]+)\]\([^)\s]+\)/g, "$1") + .replace(/\*\*([^*]+)\*\*/g, "$1") + .replace(/\*([^*\n]+)\*/g, "$1") + .replace(/`([^`]+)`/g, "$1") + .trim(); + +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`, `-€5` or `-1:30`, stays as it is. */ +const guardFormula = (value: string) => + /^[=+\-@]/.test(value) && !isPlainNumber(value) ? `'${value}` : value; + +const cleanRow = (row: string[]) => + row.map((cell) => guardFormula(plainCell(cell))); + +const quote = (field: string) => + /[",\r\n]/.test(field) ? `"${field.replaceAll('"', '""')}"` : field; + +/** RFC 4180: CRLF line ends, and a BOM so Excel reads UTF-8. */ +export const toCsv = (rows: string[][]) => + BOM + + rows.map((row) => cleanRow(row).map(quote).join(",")).join("\r\n") + + "\r\n"; + +/** Tab-separated text for a paste into a spreadsheet. */ +export const toTsv = (rows: string[][]) => + rows + .map((row) => + cleanRow(row) + .map((field) => field.replace(/[\t\r\n]+/g, " ")) + .join("\t"), + ) + .join("\n"); + +/** The header and the body of a table as one list of rows. */ +export const tableRows = (head: string[], rows: string[][]) => [head, ...rows]; + +/** The rows of a chart: a label column and a value column. */ +export const chartRows = (spec: ChartSpec) => [ + ["Label", spec.unit ? `Value (${spec.unit})` : "Value"], + ...spec.data.map((point) => [point.label, String(point.value)]), +]; + +/** A safe file name from a heading, or the fallback. */ +export const exportFileName = (title: string | undefined, fallback: string) => { + const slug = plainCell(title ?? "") + .toLowerCase() + .replace(/[^\p{L}\p{N}]+/gu, "-") + .replace(/^-+|-+$/g, "") + .slice(0, 60); + return slug || fallback; +}; diff --git a/apps/web/src/components/assistant/answer.tsx b/apps/web/src/components/assistant/answer.tsx index 2eef81af..f745de54 100644 --- a/apps/web/src/components/assistant/answer.tsx +++ b/apps/web/src/components/assistant/answer.tsx @@ -9,7 +9,13 @@ import { useToday } from "#/hooks/use-today.ts"; import { dateSearch } from "#/lib/time-search.ts"; import { AnswerChart, ChartPlaceholder } from "./answer-chart.tsx"; -import { type Align, parseBlocks, safeHref } from "./answer-parse.ts"; +import { ChartExport, TableExport } from "./answer-export-actions.tsx"; +import { + type Align, + type Block, + parseBlocks, + safeHref, +} from "./answer-parse.ts"; import { useTypeset } from "./typeset.ts"; // A small markdown reader, so the browser does not get a markdown dependency. @@ -414,6 +420,15 @@ export function AnswerActions({ text }: { text: string }) { ); } +/** For each block, the text of the heading above it, if any. Names an export. */ +const headingBefore = (blocks: Block[]) => { + let last: string | undefined; + return blocks.map((block) => { + if (block.kind === "h") last = block.text; + return last; + }); +}; + export function Answer({ text, onFollowUp, @@ -441,9 +456,11 @@ export function Answer({ const blockIn = reveal ? { animation: "fade-up var(--dur-slow) var(--ease-out) both" } : undefined; + const blocks = parseBlocks(text, streaming); + const headings = headingBefore(blocks); return (
- {parseBlocks(text, streaming).map((block, index) => { + {blocks.map((block, index) => { const key = `${block.kind}-${index}`; if (block.kind === "code") { return ( @@ -458,12 +475,19 @@ export function Answer({ } if (block.kind === "table") { return ( -
+
+ {!streaming && ( + + )}
); } @@ -479,7 +503,7 @@ export function Answer({ // block's position and does not change when the fence closes — that // is what makes this a swap rather than a remount (see `Block` in `answer-parse.ts`). return ( -
+
{block.spec ? ( @@ -487,6 +511,7 @@ export function Answer({ )} + {!streaming && block.spec && }
); } diff --git a/apps/web/src/components/assistant/ask-assistant.tsx b/apps/web/src/components/assistant/ask-assistant.tsx new file mode 100644 index 00000000..ebb73bd8 --- /dev/null +++ b/apps/web/src/components/assistant/ask-assistant.tsx @@ -0,0 +1,230 @@ +import type { WeekStartsOn } from "@farmer/core/lib/time"; +import { XIcon } from "@phosphor-icons/react"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { useNavigate, useRouterState } from "@tanstack/react-router"; +import { useEffect, useRef, useState, useSyncExternalStore } from "react"; +import { toast } from "sonner"; + +import { useAssistantActions } from "#/components/assistant/assistant-runs.tsx"; +import { + buildPageContext, + pageSearch, + projectIdFromPath, +} from "#/components/assistant/page-context.ts"; +import { Button } from "#/components/ui/button.tsx"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "#/components/ui/dialog.tsx"; +import { Input } from "#/components/ui/input.tsx"; +import { useToday } from "#/hooks/use-today.ts"; +import { queryKeys } from "#/queries/keys.ts"; +import { projectQuery } from "#/queries/projects.ts"; +import { createConversation } from "#/server/assistant.ts"; + +// Ask the assistant from any page. The shortcut opens one small dialog. Send +// starts a new chat in the run store of the layout, so the answer keeps +// streaming after the dialog closes. + +// The server takes 10,000 characters; the rest is room for the page sentence. +const ASK_MAX_CHARS = 9000; + +const isMac = () => /Mac|iPhone|iPad/.test(navigator.userAgent); + +/** The shortcut as it is written on this platform. */ +export function useShortcutLabel() { + const mac = useSyncExternalStore( + () => () => {}, + isMac, + () => false, + ); + return mac ? "⌘K" : "Ctrl K"; +} + +/** A small kbd for the shortcut, as it is written on this platform. */ +export function AskShortcutHint() { + const label = useShortcutLabel(); + return ( + + {label} + + ); +} + +type ProviderProps = { + orgSlug: string; + timezone: string; + weekStartsOn: WeekStartsOn; + available: boolean; + children: React.ReactNode; +}; + +export function AskAssistantProvider({ + available, + children, + ...page +}: ProviderProps) { + const [isOpen, setOpen] = useState(false); + + useEffect(() => { + if (!available) return; + const onKeyDown = (event: KeyboardEvent) => { + const chord = event.metaKey || event.ctrlKey; + if (!chord || event.shiftKey || event.altKey || event.isComposing) return; + if (event.key.toLowerCase() !== "k") return; + event.preventDefault(); + setOpen((current) => !current); + }; + window.addEventListener("keydown", onKeyDown); + return () => window.removeEventListener("keydown", onKeyDown); + }, [available]); + + if (!available) return children; + return ( + <> + {children} + + + ); +} + +type DialogProps = Omit & { + open: boolean; + onOpenChange: (open: boolean) => void; +}; + +function AskDialog({ open, onOpenChange, ...page }: DialogProps) { + const inputRef = useRef(null); + return ( + + {/* Without it, focus lands on the chip's remove button. */} + + {/* Mounted only while open, so the field and the chip start fresh. */} + onOpenChange(false)} + /> + + + ); +} + +function AskForm({ + orgSlug, + timezone, + weekStartsOn, + close, + inputRef, +}: Omit & { + close: () => void; + inputRef: React.RefObject; +}) { + const queryClient = useQueryClient(); + const navigate = useNavigate(); + const actions = useAssistantActions(); + const today = useToday(timezone); + const location = useRouterState({ select: (state) => state.location }); + const projectId = projectIdFromPath(location.pathname, orgSlug); + const { data: project } = useQuery({ + ...projectQuery(orgSlug, projectId ?? ""), + enabled: Boolean(projectId), + }); + const sentence = buildPageContext({ + pathname: location.pathname, + search: pageSearch.safeParse(location.search).data ?? {}, + orgSlug, + today, + weekStartsOn, + projectName: project?.name, + }); + const [chip, setChip] = useState(true); + const [text, setText] = useState(""); + const [busy, setBusy] = useState(false); + + const send = async () => { + const question = text.trim(); + if (!question || busy) return; + setBusy(true); + try { + const conversation = await createConversation({ data: {} }); + await queryClient.invalidateQueries({ + queryKey: [...queryKeys(orgSlug).assistant, "conversations"], + }); + const message = + chip && sentence ? `${sentence}\n\n${question}` : question; + // Not awaited: the call returns when the whole answer is done. + actions.send(conversation.id, message).catch((error: unknown) => { + toast.error( + error instanceof Error + ? error.message + : "Could not send the question", + ); + }); + close(); + toast("Asking the assistant", { + action: { + label: "Open chat", + onClick: () => + void navigate({ + to: "/$orgSlug/assistant", + params: { orgSlug }, + search: { c: conversation.id }, + }), + }, + }); + } catch (error) { + toast.error( + error instanceof Error ? error.message : "Could not start a chat", + ); + setBusy(false); + } + }; + + return ( +
{ + event.preventDefault(); + void send(); + }} + > + + Ask the assistant + + It starts a new chat. The answer keeps going if you leave this page. + + + {sentence && chip && ( +
+ {sentence} + +
+ )} + setText(event.target.value)} + /> +
+ +
+
+ ); +} diff --git a/apps/web/src/components/assistant/assistant-runs.tsx b/apps/web/src/components/assistant/assistant-runs.tsx index 8be5c23b..60a4baef 100644 --- a/apps/web/src/components/assistant/assistant-runs.tsx +++ b/apps/web/src/components/assistant/assistant-runs.tsx @@ -56,6 +56,13 @@ export type ToolTrace = { ok: boolean | null; /** The call's raw arguments, as the model sent them. */ arguments: string; + /** Only on a stored write with an inverse. A live trace has none. */ + undo?: { + done: boolean; + busy: boolean; + disabled: boolean; + onUndo: () => void; + }; }; /** The rows a batch write would touch. Mirrors `ApprovalPreview` in diff --git a/apps/web/src/components/assistant/chat-rail.tsx b/apps/web/src/components/assistant/chat-rail.tsx index 09d50387..36598b06 100644 --- a/apps/web/src/components/assistant/chat-rail.tsx +++ b/apps/web/src/components/assistant/chat-rail.tsx @@ -3,6 +3,7 @@ import { ChatsIcon, PencilSimpleIcon, PlusIcon, + ShareNetworkIcon, TrashIcon, } from "@phosphor-icons/react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; @@ -25,6 +26,12 @@ import { queryKeys } from "#/queries/keys.ts"; import { deleteConversation, renameConversation } from "#/server/assistant.ts"; import { useAssistantRunning } from "./assistant-runs.tsx"; +import { + ChatSearchBox, + ChatSearchResults, + useChatSearch, +} from "./chat-search.tsx"; +import { ShareChatButton } from "./share-chat.tsx"; /** * The conversation list, and its two frames: the shell's section panel on @@ -60,6 +67,30 @@ export function ConversationList({ orgSlug: string; /** Called when a row is followed — the sheet closes on it; the sidebar has nothing to close. */ onNavigate?: () => void; +}) { + const { input, setInput, query } = useChatSearch(); + return ( +
+ + {input.trim() === "" ? ( + + ) : ( + + )} +
+ ); +} + +function ConversationRows({ + orgSlug, + onNavigate, +}: { + orgSlug: string; + onNavigate?: () => void; }) { const queryClient = useQueryClient(); const navigate = useNavigate(); @@ -263,6 +294,16 @@ export function ConversationList({ {running.includes(conversation.id) && ( , working on an answer )} + {conversation.sharedAt && ( + <> + + , shared + + )} )} {editingId !== conversation.id && ( @@ -360,15 +401,22 @@ export function MobileChatBar({ orgSlug }: { orgSlug: string }) { navigates to the screen you are already looking at. The sheet's own "New chat" row is the other, always-present way. */} {openId && ( - - - + <> + + + + + )} diff --git a/apps/web/src/components/assistant/chat-search.test.ts b/apps/web/src/components/assistant/chat-search.test.ts new file mode 100644 index 00000000..d5f2003d --- /dev/null +++ b/apps/web/src/components/assistant/chat-search.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, test } from "bun:test"; + +import { matchParts } from "./chat-search.tsx"; + +describe("matchParts", () => { + test("marks every match, ignoring case", () => { + expect(matchParts("Budget for the budget", "budget")).toEqual([ + { text: "Budget", match: true }, + { text: " for the ", match: false }, + { text: "budget", match: true }, + ]); + }); + + test("returns the whole text when nothing matches", () => { + expect(matchParts("hello", "zz")).toEqual([ + { text: "hello", match: false }, + ]); + }); +}); diff --git a/apps/web/src/components/assistant/chat-search.tsx b/apps/web/src/components/assistant/chat-search.tsx new file mode 100644 index 00000000..d1502816 --- /dev/null +++ b/apps/web/src/components/assistant/chat-search.tsx @@ -0,0 +1,149 @@ +import { MAX_SEARCH_CHARS } from "@farmer/core/schema"; +import { useQuery } from "@tanstack/react-query"; +import { Link } from "@tanstack/react-router"; +import { useEffect, useState } from "react"; + +import { SearchInput } from "#/components/ui/search-input.tsx"; +import { searchConversationsQuery } from "#/queries/assistant.ts"; + +const DEBOUNCE_MS = 250; +const MIN_CHARS = 2; + +/** The text in pieces, with the pieces that match `q` marked. */ +export function matchParts( + text: string, + q: string, +): { text: string; match: boolean }[] { + const needle = q.toLowerCase(); + const haystack = text.toLowerCase(); + const parts: { text: string; match: boolean }[] = []; + let from = 0; + for (;;) { + const hit = needle ? haystack.indexOf(needle, from) : -1; + if (hit === -1) break; + if (hit > from) parts.push({ text: text.slice(from, hit), match: false }); + parts.push({ text: text.slice(hit, hit + needle.length), match: true }); + from = hit + needle.length; + } + if (from < text.length) parts.push({ text: text.slice(from), match: false }); + return parts; +} + +function Marked({ text, q }: { text: string; q: string }) { + let offset = 0; + return matchParts(text, q).map((part) => { + offset += part.text.length; + return part.match ? ( + + {part.text} + + ) : ( + {part.text} + ); + }); +} + +/** The search box, and the query it holds once it settles. */ +export function useChatSearch() { + const [input, setInput] = useState(""); + const [settled, setSettled] = useState(""); + useEffect(() => { + const timer = setTimeout(() => setSettled(input.trim()), DEBOUNCE_MS); + return () => clearTimeout(timer); + }, [input]); + return { + input, + setInput, + // A cleared box shows the list at once, with no wait. + query: input.trim() === "" ? "" : settled, + }; +} + +export function ChatSearchBox({ + value, + onValueChange, +}: { + value: string; + onValueChange: (value: string) => void; +}) { + return ( + + ); +} + +/** The matches for `query`, in place of the list. */ +export function ChatSearchResults({ + orgSlug, + query, + onNavigate, +}: { + orgSlug: string; + query: string; + onNavigate?: () => void; +}) { + const enabled = query.length >= MIN_CHARS; + const { + data = [], + isPending, + isError, + } = useQuery({ + ...searchConversationsQuery(orgSlug, query), + enabled, + }); + if (!enabled) { + return ( +

+ Type at least {MIN_CHARS} characters. +

+ ); + } + if (isPending) { + return ( +

Searching…

+ ); + } + if (isError) { + return ( +

+ Could not search the chats. +

+ ); + } + if (data.length === 0) { + return ( +

+ No chat matches. +

+ ); + } + return ( +
    + {data.map((hit) => ( +
  • + + + + + {hit.snippet && ( + + + + )} + +
  • + ))} +
+ ); +} diff --git a/apps/web/src/components/assistant/context-meter.tsx b/apps/web/src/components/assistant/context-meter.tsx new file mode 100644 index 00000000..4d79093f --- /dev/null +++ b/apps/web/src/components/assistant/context-meter.tsx @@ -0,0 +1,74 @@ +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from "#/components/ui/tooltip.tsx"; + +/** The meter shows from this share of the model's context. */ +export const CONTEXT_METER_FROM = 0.7; + +const kTokens = (n: number) => + n >= 1000 ? `${Math.round(n / 1000)}k` : String(n); + +/** How full the chat is, as a share from 0 to 1. Null when it is unknown. */ +export const contextShare = ( + used: number | null | undefined, + limit: number | null | undefined, +) => (used && limit && limit > 0 ? used / limit : null); + +export function ContextMeter({ + used, + limit, + onNewChat, +}: { + used: number | null | undefined; + limit: number | null | undefined; + onNewChat: () => void; +}) { + const share = contextShare(used, limit); + if (share === null || !used || !limit || share < CONTEXT_METER_FROM) { + return null; + } + const percent = Math.min(100, Math.round(share * 100)); + return ( +
+ + + + {/* The native element carries the value. The ring is drawn + with a conic gradient under a mask. */} + + + + + This chat uses {percent}% of the model's memory. Start a new chat + for best results. +
+ {kTokens(used)} of {kTokens(limit)} tokens +
+
+
+
+ +
+ ); +} diff --git a/apps/web/src/components/assistant/page-context.test.ts b/apps/web/src/components/assistant/page-context.test.ts new file mode 100644 index 00000000..2864b362 --- /dev/null +++ b/apps/web/src/components/assistant/page-context.test.ts @@ -0,0 +1,76 @@ +import { expect, test } from "bun:test"; + +import { + buildPageContext, + type PageContextInput, + type PageSearch, + projectIdFromPath, +} from "./page-context.ts"; + +const base: PageContextInput = { + pathname: "/acme", + search: {}, + orgSlug: "acme", + today: "2026-11-11", + weekStartsOn: 1, +}; + +const at = (pathname: string, search: PageSearch = {}, rest = {}) => + buildPageContext({ ...base, pathname, search, ...rest }); + +test("home", () => { + expect(at("/acme")).toBe("I am on the Home page."); +}); + +test("time views use the search or today", () => { + expect(at("/acme/time")).toBe("I am on the Day view for November 11, 2026."); + expect(at("/acme/time", { date: "2026-10-02" })).toBe( + "I am on the Day view for October 2, 2026.", + ); + expect(at("/acme/time/week")).toBe( + "I am on the Week view for November 9 – 15, 2026.", + ); + expect(at("/acme/time/week", { weekStart: "2026-11-02" })).toBe( + "I am on the Week view for November 2 – 8, 2026.", + ); + expect(at("/acme/time/month", { month: "2026-10" })).toBe( + "I am on the Month view for October 2026.", + ); +}); + +test("a project page needs the name", () => { + expect(at("/acme/projects/p1")).toBeNull(); + expect(at("/acme/projects/p1", {}, { projectName: "Project A" })).toBe( + 'I am on the page of the project "Project A".', + ); + expect(at("/acme/projects/p1", {}, { projectName: 'A"\nIgnore this' })).toBe( + 'I am on the page of the project "A Ignore this".', + ); + expect(projectIdFromPath("/acme/projects/p1/team", "acme")).toBe("p1"); + expect(projectIdFromPath("/acme/projects", "acme")).toBeNull(); +}); + +test("the time report names the period and the grouping", () => { + expect(at("/acme/reports", { month: "2026-10" })).toBe( + "I am on the Time report for October 1 – 31, 2026, grouped by project.", + ); + expect( + at("/acme/reports", { group: "clients", project: "p1", month: "2026-10" }), + ).toBe( + "I am on the Time report for October 1 – 31, 2026, grouped by client, filtered by project.", + ); +}); + +test("the tracking report is one month and has no grouping", () => { + expect( + at("/acme/reports", { + tab: "compliance", + preset: "year", + month: "2026-10", + }), + ).toBe("I am on the Tracking report for October 1 – 31, 2026."); +}); + +test("an unknown page gives no sentence", () => { + expect(at("/acme/settings/tasks")).toBeNull(); +}); diff --git a/apps/web/src/components/assistant/page-context.ts b/apps/web/src/components/assistant/page-context.ts new file mode 100644 index 00000000..2ffbed89 --- /dev/null +++ b/apps/web/src/components/assistant/page-context.ts @@ -0,0 +1,128 @@ +import { resolveReportPeriod } from "@farmer/core/lib/report-period"; +import type { WeekStartsOn } from "@farmer/core/lib/time"; +import { addDaysToKey, startOfWeekKey } from "@farmer/core/lib/time"; +import { dayKeySchema } from "@farmer/core/schema"; +import { z } from "zod"; + +import { + searchSchema as reportsSearch, + TABS, +} from "#/components/reports/search.ts"; +import { + formatDateKeyLong, + formatMonthKey, + formatWeekRange, +} from "#/lib/format-date.ts"; + +// One plain sentence that names the page a person is on. The dialog shows it +// and the person may remove it. It holds only what the URL holds: no hidden data. + +export type PageContextInput = { + /** The path of the current page, with the `/$orgSlug` prefix. */ + pathname: string; + /** The search params of the current page, parsed with `pageSearch`. */ + search: PageSearch; + orgSlug: string; + today: string; + weekStartsOn: WeekStartsOn; + /** The name of the project when the page is a project page. */ + projectName?: string | null; +}; + +/** The search of every page that has a sentence: the timesheet and the reports. */ +export const pageSearch = reportsSearch.extend({ + date: dayKeySchema.optional().catch(undefined), + weekStart: dayKeySchema.optional().catch(undefined), +}); +export type PageSearch = z.infer; + +const GROUP_WORD = { + clients: "client", + projects: "project", + teammates: "teammate", +} as const; + +const FILTER_WORDS = [ + ["client", "client"], + ["project", "project"], + ["task", "task"], + ["person", "person"], +] as const; + +const pathWithin = (pathname: string, orgSlug: string) => { + const rest = pathname.startsWith(`/${orgSlug}`) + ? pathname.slice(orgSlug.length + 1) + : pathname; + return rest.replace(/\/+$/, ""); +}; + +/** The project id of a project page, or null. */ +export function projectIdFromPath(pathname: string, orgSlug: string) { + const match = /^\/projects\/([^/]+)/.exec(pathWithin(pathname, orgSlug)); + return match?.[1] ?? null; +} + +function timeSentence( + path: string, + parsed: PageSearch, + today: string, + weekStartsOn: WeekStartsOn, +) { + if (path === "/time") { + return `the Day view for ${formatDateKeyLong(parsed.date ?? today)}`; + } + if (path === "/time/week") { + const from = parsed.weekStart ?? startOfWeekKey(today, weekStartsOn); + return `the Week view for ${formatWeekRange(from, addDaysToKey(from, 6))}`; + } + if (path === "/time/month") { + return `the Month view for ${formatMonthKey(parsed.month ?? today.slice(0, 7))}`; + } + return null; +} + +function reportSentence( + parsed: PageSearch, + today: string, + weekStartsOn: WeekStartsOn, +) { + const tab = TABS.find((entry) => entry.id === parsed.tab) ?? TABS[0]; + // Tracking is always one month. + const selection = tab.id === "compliance" ? { month: parsed.month } : parsed; + const { from, to } = resolveReportPeriod(selection, today, weekStartsOn); + const parts = [`the ${tab.label} report for ${formatWeekRange(from, to)}`]; + if (tab.id === "time") { + parts.push(`grouped by ${GROUP_WORD[parsed.group ?? "projects"]}`); + } + const filters = FILTER_WORDS.filter(([key]) => parsed[key]).map( + ([, word]) => word, + ); + if (filters.length > 0) parts.push(`filtered by ${filters.join(" and ")}`); + return parts.join(", "); +} + +function projectSentence(path: string, rawName: string | null | undefined) { + // A newline or a quote in the name must not break out of the sentence. + const name = rawName?.replace(/[\r\n"]+/g, " ").trim(); + if (!name) return null; + const sub = /^\/projects\/[^/]+\/(\w+)$/.exec(path)?.[1]; + return sub + ? `the ${sub} page of the project "${name}"` + : `the page of the project "${name}"`; +} + +/** The sentence for the current page, or null when the page is not known. */ +export function buildPageContext(input: PageContextInput): string | null { + const path = pathWithin(input.pathname, input.orgSlug); + const { today, weekStartsOn } = input; + let place: string | null = null; + if (path === "") place = "the Home page"; + else if (path.startsWith("/time")) { + place = timeSentence(path, input.search, today, weekStartsOn); + } else if (path === "/reports") { + place = reportSentence(input.search, today, weekStartsOn); + } else if (path.startsWith("/projects/")) { + place = projectSentence(path, input.projectName); + } + return place ? `I am on ${place}.` : null; +} diff --git a/apps/web/src/components/assistant/primitives.tsx b/apps/web/src/components/assistant/primitives.tsx index b2b87bf3..e52e7de8 100644 --- a/apps/web/src/components/assistant/primitives.tsx +++ b/apps/web/src/components/assistant/primitives.tsx @@ -10,11 +10,21 @@ // // Sources: LoadingState.tsx, ThinkingState.tsx, ApprovalCard.tsx. +import { ArrowCounterClockwiseIcon } from "@phosphor-icons/react"; import { useQuery } from "@tanstack/react-query"; -import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; +import { + type CSSProperties, + useEffect, + useLayoutEffect, + useMemo, + useRef, + useState, +} from "react"; import { z } from "zod"; +import { MARK } from "#/components/farmer-mark.tsx"; import { PersonAvatar } from "#/components/person-avatar.tsx"; +import { Button } from "#/components/ui/button.tsx"; import { useOrgSlug } from "#/hooks/use-org-slug.ts"; import { cn } from "#/lib/utils.ts"; import { clientsQuery } from "#/queries/clients.ts"; @@ -26,35 +36,42 @@ import { MONTHS, printDayKey } from "./answer.tsx"; import type { PendingApproval, ToolTrace } from "./assistant-runs.tsx"; import { toolLabel } from "./tool-labels.ts"; -/* ── the pixel-grid loader (LoadingState) ─────────────────────────────────── */ +/* ── the sprout loader (LoadingState) ─────────────────────────────────────── */ -// A chevron wavefront: cell delay grows with the column and with distance from -// the middle row, so the front reads as driving rightwards. The 650ms cycle is -// shorter than the sweep across the grid, so two fronts are always in flight. -const CHEVRON = Array.from({ length: 9 }, (_, i) => { - const row = Math.floor(i / 3); - const column = i % 3; - return (column + Math.abs(row - 1)) * 90; -}); +// The Farmer wheat. The stalk draws, then each grain grows out of it and drops. +// The first piece of the mark is the tile. Skip it. +const [, ...GRAINS] = MARK.split(/(?<=Z)(?=M)/); +// Step along the stalk for each grain: leaf, then the pairs from base to tip. +const STEP = [0, 1, 2, 1, 3, 2, 3]; +// The edge of each grain that touches the stalk. +const KIND = ["leaf", "v", "v", "h", "v", "h", "h"]; -function LoaderGrid() { +function SproutMark() { return ( - - {CHEVRON.map((delay, index) => ( - + {GRAINS.map((d, n) => ( + ))} - + ); } @@ -92,7 +109,7 @@ export function AssistantLoader({ label = "Thinking" }: { label?: string }) { // be maintained by hand. return ( - + {label} {elapsed} @@ -303,12 +320,15 @@ const useTraceNames = (args: DetailArgs[]): TraceNames => { export function ToolTraceList({ traces, working, + open = false, }: { traces: ToolTrace[]; working: boolean; + /** Start expanded when settled, so a stored Undo button is in view. */ + open?: boolean; }) { const [manual, setManual] = useState(null); - const expanded = manual ?? working; + const expanded = manual ?? (working || open); // Parsed once per trace rather than once per render of each row: the maps // below are chosen from these, and the rows are drawn from them again. const args = useMemo( @@ -336,7 +356,7 @@ export function ToolTraceList({ + ))}
); })} diff --git a/apps/web/src/components/assistant/prompt-bar.tsx b/apps/web/src/components/assistant/prompt-bar.tsx index 629702b5..4c5df567 100644 --- a/apps/web/src/components/assistant/prompt-bar.tsx +++ b/apps/web/src/components/assistant/prompt-bar.tsx @@ -97,6 +97,7 @@ export function PromptBar({ placeholder = "Ask about your time, or log some…", autoFocus, focusKey, + restore, }: { /** * Sends the draft. Resolving FALSE means the message never reached the @@ -110,6 +111,9 @@ export function PromptBar({ autoFocus?: boolean; /** Focus the input again each time this value changes. */ focusKey?: string | null; + /** A text to put back, as after a send that never landed. A new object + * each time. */ + restore?: { text: string } | null; }) { const [draft, setDraft] = useState(""); const [dismissed, setDismissed] = useState(false); @@ -197,6 +201,16 @@ export function PromptBar({ }; const canSend = draft.trim().length > 0 && !busy && !disabled; + // Only into a composer the person has not started refilling — their own + // second thought outranks the one we are handing back. + const giveBack = (text: string) => { + setDraft((current) => (current ? current : text)); + inputRef.current?.focus(); + }; + // oxlint-disable-next-line react-hooks/exhaustive-deps -- only a new `restore` object may run it, and `giveBack` is rebuilt each render + useEffect(() => { + if (restore) giveBack(restore.text); + }, [restore]); /** * Clear on send, and put it back if the send never landed. * @@ -213,11 +227,7 @@ export function PromptBar({ setDraft(""); setDismissed(false); void onSend(text).then((delivered) => { - if (delivered) return; - // Only into a composer the person has not started refilling — their - // own second thought outranks the one we are handing back. - setDraft((current) => (current ? current : text)); - inputRef.current?.focus(); + if (!delivered) giveBack(text); }); }; diff --git a/apps/web/src/components/assistant/share-chat.tsx b/apps/web/src/components/assistant/share-chat.tsx new file mode 100644 index 00000000..9d1d465c --- /dev/null +++ b/apps/web/src/components/assistant/share-chat.tsx @@ -0,0 +1,152 @@ +import { ShareNetworkIcon } from "@phosphor-icons/react"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useRouteContext } from "@tanstack/react-router"; +import { useState } from "react"; +import { toast } from "sonner"; + +import { Button } from "#/components/ui/button.tsx"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "#/components/ui/dialog.tsx"; +import { conversationsQuery } from "#/queries/assistant.ts"; +import { queryKeys } from "#/queries/keys.ts"; +import { shareConversation, unshareConversation } from "#/server/assistant.ts"; + +const sharedUrl = (orgSlug: string, id: string) => + `${window.location.origin}/${orgSlug}/assistant/shared/${id}`; + +const copyLink = async (url: string) => { + try { + await navigator.clipboard.writeText(url); + toast.success("Link copied"); + } catch { + toast.error("Could not copy the link"); + } +}; + +/** + * The Share button of the open chat, and the dialog behind it. The warning + * comes first: a chat holds results that were read with the owner's access. + */ +export function ShareChatButton({ + orgSlug, + conversationId, + className, +}: { + orgSlug: string; + conversationId: string; + className?: string; +}) { + const [open, setOpen] = useState(false); + const { data: conversations = [] } = useQuery(conversationsQuery(orgSlug)); + const shared = Boolean( + conversations.find((c) => c.id === conversationId)?.sharedAt, + ); + return ( + <> + + + + ); +} + +function ShareDialog({ + open, + onOpenChange, + orgSlug, + conversationId, + shared, +}: { + open: boolean; + onOpenChange: (open: boolean) => void; + orgSlug: string; + conversationId: string; + shared: boolean; +}) { + const queryClient = useQueryClient(); + const orgName = useRouteContext({ + from: "/$orgSlug", + select: (context) => context.organization.name, + }); + const url = sharedUrl(orgSlug, conversationId); + const refresh = () => + queryClient.invalidateQueries({ + queryKey: [...queryKeys(orgSlug).assistant, "conversations"], + }); + + const share = useMutation({ + mutationFn: () => shareConversation({ data: { conversationId } }), + onSuccess: async () => { + await refresh(); + await copyLink(url); + onOpenChange(false); + }, + onError: (error) => toast.error(error.message ?? "Could not share"), + }); + const stop = useMutation({ + mutationFn: () => unshareConversation({ data: { conversationId } }), + onSuccess: async () => { + await refresh(); + toast.success("Sharing stopped"); + onOpenChange(false); + }, + onError: (error) => toast.error(error.message ?? "Could not stop sharing"), + }); + + return ( + + + + Share this chat + + Anyone in {orgName} with the link can read this chat. It can show + data that you can see and they cannot, for example a team report. + Share only what you would show them. + + + + {shared ? ( + <> + + + + ) : ( + + )} + + + + ); +} diff --git a/apps/web/src/components/assistant/stored-turn.tsx b/apps/web/src/components/assistant/stored-turn.tsx new file mode 100644 index 00000000..1dd0e41d --- /dev/null +++ b/apps/web/src/components/assistant/stored-turn.tsx @@ -0,0 +1,204 @@ +import { ArrowClockwiseIcon, PencilSimpleIcon } from "@phosphor-icons/react"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { useState } from "react"; +import { toast } from "sonner"; + +import { Button } from "#/components/ui/button.tsx"; +import { Textarea } from "#/components/ui/textarea.tsx"; +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from "#/components/ui/tooltip.tsx"; +import { useOrgSlug } from "#/hooks/use-org-slug.ts"; +import { conversationQuery } from "#/queries/assistant.ts"; +import { queryKeys } from "#/queries/keys.ts"; +import { + rewindAssistantThread, + undoAssistantWrite, +} from "#/server/assistant.ts"; + +import type { ToolTrace } from "./assistant-runs.tsx"; +import { ToolTraceList } from "./primitives.tsx"; + +/** A stored write that has an Undo, or that was undone. */ +export function StoredWriteTrace({ + conversationId, + messageId, + trace, + done, + locked, +}: { + conversationId: string; + messageId: string; + trace: Pick; + done: boolean; + /** A turn runs or a card waits. */ + locked: boolean; +}) { + const orgSlug = useOrgSlug(); + const queryClient = useQueryClient(); + const undo = useMutation({ + mutationFn: () => + undoAssistantWrite({ data: { conversationId, messageId } }), + onSuccess: () => + Promise.all([ + queryClient.invalidateQueries({ + queryKey: conversationQuery(orgSlug, conversationId).queryKey, + }), + queryClient.invalidateQueries({ + queryKey: queryKeys(orgSlug).timeEntries, + }), + ]), + onError: (error) => toast.error(error.message ?? "Could not undo"), + }); + return ( + undo.mutate(), + }, + }, + ]} + /> + ); +} + +/** Disabled buttons do not fire pointer events, so the span takes the hover. */ +function WithReason({ + reason, + children, +}: { + reason: string | null; + children: React.ReactNode; +}) { + if (!reason) return children; + return ( + + + }> + {children} + + {reason} + + + ); +} + +/** + * The actions on the last question: Edit and Retry. Both take the question + * back from the server (`rewindAssistantThread`), then send the text again as + * a new turn. + */ +export function LastQuestionActions({ + conversationId, + text, + reason, + onSend, + onRestore, + editing, + onEditingChange, +}: { + conversationId: string; + text: string; + /** Why the actions are off, or null. */ + reason: string | null; + onSend: (text: string) => Promise; + /** The question is gone from the thread and the send failed: put the text + * back in the composer. */ + onRestore: (text: string) => void; + editing: boolean; + onEditingChange: (editing: boolean) => void; +}) { + const orgSlug = useOrgSlug(); + const queryClient = useQueryClient(); + const [draft, setDraft] = useState(text); + const resend = useMutation({ + mutationFn: async (next: string) => { + await rewindAssistantThread({ data: { conversationId } }); + await queryClient.invalidateQueries({ + queryKey: conversationQuery(orgSlug, conversationId).queryKey, + }); + if (await onSend(next)) return; + // The rewind removed the question, so this row is about to unmount. + onEditingChange(false); + onRestore(next); + throw new Error("The message was not sent. Your text is in the box."); + }, + onSuccess: () => onEditingChange(false), + onError: (error) => toast.error(error.message ?? "Could not send again"), + }); + + if (editing) { + return ( +
+