Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
feat(notes): templates for the AI summary, and actions that run in chat or on it (#2397)
voide4fd491839e1
diff --git a/CLAUDE.md b/CLAUDE.mdindex b0232436c..7f5981d71 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -186,6 +186,7 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.- Token handling shared by the OAuth connectors (`boundLogin.js`): reads, the reconnect flag, saving a refreshed token and one refresh at a time, only ever for the login an action is bound to. Gmail's and Linear's clients share one timed POST and its body helpers (`providerHttp.js`); GitHub's uses the body helpers- Logins: one encrypted file per OpenWhispr account and connector under `userData/connectors/` (atomic writes, `0o700`, `connectorCredentials.js`). Every write names the account and the generation it started from, so an OAuth round trip, refresh or disconnect that outlives a reconnect or account switch writes nothing. Bindings carry `ownerAccountId`; receipts carry `account_id`. Signed out → every connector action is refused (`signed_out`). Pending actions also expire in main (`sweepExpired`, every minute)- **postMigrationDetector.js**: Detects users returning from the pre-Gizmo bundle ID via a `.bundle-migrated` sentinel in userData; consumed by `ipcHandlers.js` to drive the `PostMigrationOnboarding` modal+- **templatePrompts.js**: Pure compiler from a note template or action to the system prompt the model receives (see Note Templates and Actions). Shared by `actionProcessingStore.ts`, the note chat, and the live canary's note probe### React Components (src/components/)@@ -758,6 +759,16 @@ Live meeting transcription runs two streams (mic + system-audio tap) and must ke- **Regression pins**: BYOK `session.update` payload and the disconnect-commit callback (`test/helpers/openaiRealtimeStreaming.test.js`, `tinfoilRealtimeStreaming.test.js`), token-endpoint wire bodies (`test/helpers/realtimeTokenProviders.test.js`). Tests named `characterization: …` pin known oddities on purpose — flip them deliberately when changing policy- **Fixtures**: `test/helpers/harness/pcmFixtures.js` — deterministic 24 kHz PCM generators (`makeSine`, `makeSeededNoise`, `mix`, `delayBy`, `toInt16Buffer`, `chunkBuffer`, …) used by the gate and echo-detector tests+### 19. Note Templates and Actions++Rows in the `actions` table (built-ins seeded from `src/helpers/builtinActions.js`) are one of two kinds:++- **Templates** (`kind: 'template'`) write a note's AI summary (`enhanced_content`) from its notes, meeting context, and transcript, never from the summary they replace. A template is a context (`prompt`) plus ordered `sections` (`{heading, instruction}`); `compileTemplatePrompt` wraps sections in the shared notes rules. A template without sections keeps the request it always had (the generic system prompt, or the material preamble for a standalone key). The note records the template in `enhancement_template_id` (its `client_id`), which syncs with the note, and `enhancement_prompt` the compiled system prompt+- **Actions** (`kind: 'action'`) work from the AI summary when the note has one, and from its notes and transcript otherwise (`buildNoteRunInput`). An `output` of `summary` edits that summary (`requireCompleteOutput`, never split into parts; only `enhanced_content` is written), or with no summary yet writes one from the transcript and applies the action to it, run like a template (split into parts on a local model, the material hash recorded); `chat` runs in the note chat via `SendToAIOptions.requestText` (the chat shows a built-in's call to action where it has one, otherwise the action's name, and the preamble points the model at the summary or the transcript and has it answer in the chat as text in the note's language, using a tool to draft, send or post only when the action's instructions explicitly ask to send, post or file something; the note chat's tools and attendee block otherwise apply as usual, and its transcript context names speakers only on notes known to be the user's own (`ownsNote`), never listing the unfiltered invitees)+- The default template is the built-in Detailed Notes, shown as "AI Summary" and listed first (launch re-applies the built-in order). Invariant: compiled from its sections, it equals the flat 1.10.2 prompt it replaced, but for the closing rule on material with nothing to summarize (`test/helpers/templatePrompts.test.js`); a built-in's `previousPrompts` only upgrades rows that are still flat+- For material with nothing substantive (only greetings, filler or recording checks), sectioned templates, Generate Notes and a summary action writing a first summary ask the model to answer `NOTHING_TO_SUMMARIZE`; custom context-only templates and flat built-ins edited before this rule keep their own rules. A reply that is the marker (bare, fenced, emphasised or after a short sentence) outside a thinking block writes nothing; a summary that merely contains it is saved, and the runner shows `notes.actions.errors.nothingToSummarize` as a neutral notice (`notice` on the error event) instead of saving a placeholder summary+- UI: `TemplatePicker` opens from the chevron in the AI Summary tab, which names the note's template; the "Generate AI Summary" callout (runs the note's template, else the default), `ActionChips` above the ask bar (the first four actions, then All actions), a `/` menu in the note composers (`slashCommands` on `ChatInput`), the sidebar chat's quick-action pills, and `ActionManagerDialog` (Templates | Actions). A new action's output is Auto, Chat or AI summary (a saved one offers only the last two); Auto asks the note model on save (`inferActionOutput`) and stores chat or summary, falling back to chat. A run that writes the summary is undoable for 6 s instead of asking first: the runner queues the fields it overwrote (`appliedEvents`) and `BackgroundActionToastListener` shows the Undo toast+## Development Guidelines### Internationalization (i18n) — REQUIREDdiff --git a/preload.js b/preload.jsindex f37b9a6d2..43e6fa723 100644--- a/preload.js+++ b/preload.js@@ -276,8 +276,8 @@ contextBridge.exposeInMainWorld("electronAPI", {// Action functionsgetActions: () => ipcRenderer.invoke("db-get-actions"),getAction: (id) => ipcRenderer.invoke("db-get-action", id),- createAction: (name, description, prompt, icon) =>- ipcRenderer.invoke("db-create-action", name, description, prompt, icon),+ createAction: (name, description, prompt, icon, fields) =>+ ipcRenderer.invoke("db-create-action", name, description, prompt, icon, fields),updateAction: (id, updates) => ipcRenderer.invoke("db-update-action", id, updates),deleteAction: (id) => ipcRenderer.invoke("db-delete-action", id),diff --git a/scripts/lib/note-formatting-probe.mjs b/scripts/lib/note-formatting-probe.mjsindex fd6e7c148..99a17d98e 100644--- a/scripts/lib/note-formatting-probe.mjs+++ b/scripts/lib/note-formatting-probe.mjs@@ -3,11 +3,8 @@* meeting-sized transcript and the exact system prompt the note action store* sends for Detailed Notes, so the probe measures the request users make.*/-import {- BUILTIN_ACTIONS,- DETAILED_NOTES_KEY,- MEETING_INPUT_PREAMBLE,-} from "../../src/helpers/builtinActions.js";+import { BUILTIN_ACTIONS, DETAILED_NOTES_KEY } from "../../src/helpers/builtinActions.js";+import { compileTemplatePrompt } from "../../src/helpers/templatePrompts.js";/** A real 45-minute meeting lands around here; the 1.10.1 report was 2,170 words. */export const NOTE_PROBE_MIN_WORDS = 2000;@@ -124,6 +121,9 @@ export function buildNoteProbeTranscript({ minWords = NOTE_PROBE_MIN_WORDS, seed/** Exactly what actionProcessingStore sends for the built-in Detailed Notes action on a meeting note. */export function buildNoteProbeSystemPrompt() {const action = BUILTIN_ACTIONS.find((entry) => entry.translationKey === DETAILED_NOTES_KEY);- if (!action) throw new Error("Detailed Notes is no longer a built-in action");- return MEETING_INPUT_PREAMBLE + action.prompt;+ if (!action) throw new Error("Detailed Notes is no longer a built-in template");+ return compileTemplatePrompt(+ { prompt: action.prompt, sections: action.sections, translation_key: action.translationKey },+ { isMeetingNote: true }+ );}diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsxindex bd34391bb..cd4dc5854 100644--- a/src/components/chat/ChatInput.tsx+++ b/src/components/chat/ChatInput.tsx@@ -1,4 +1,4 @@-import { useState, useRef, useCallback, useEffect, useLayoutEffect } from "react";+import { useState, useRef, useCallback, useEffect, useLayoutEffect, useId, useMemo } from "react";import { ArrowRight, Mic, Square, X } from "../icons";import { useTranslation } from "react-i18next";import { cn } from "../lib/utils";@@ -9,6 +9,9 @@ import { GLASS_SURFACE } from "../ui/glass";import { useToast } from "../ui/useToast";import { formatMmSs } from "../../utils/formatDuration";import { useVoiceDraft } from "./useVoiceDraft";+import { Popover, PopoverAnchor, PopoverContent } from "../ui/popover";+import SlashCommandMenu from "./SlashCommandMenu";+import { matchSlashCommands, slashOptionId, type SlashCommand } from "./slashCommands";import type { AgentState } from "./types";// Controls stay bottom-anchored so they hold the corner while the composer expands;@@ -32,10 +35,11 @@ interface ChatInputProps {onDraftChange?: (text: string) => void;onFocus?: () => void;onEscape?: () => void;- trailingContent?: React.ReactNode;focusOnIdle?: boolean;expandOnFocus?: boolean;expandOnFocusSize?: "standard" | "compact";+ /** Offered in a menu while the draft is "/" plus an optional filter. */+ slashCommands?: SlashCommand[];}function RecordingIndicator() {@@ -81,10 +85,10 @@ export function ChatInput({onDraftChange,onFocus,onEscape,- trailingContent,focusOnIdle = true,expandOnFocus = false,expandOnFocusSize = "standard",+ slashCommands,}: ChatInputProps) {const { t } = useTranslation();const { toast } = useToast();@@ -124,6 +128,25 @@ export function ChatInput({const isBusy =agentState === "thinking" || agentState === "streaming" || agentState === "tool-executing";+ const slashMenuId = useId();+ const [isFocused, setIsFocused] = useState(false);+ const [slashIndex, setSlashIndex] = useState(0);+ const slashMatches = useMemo(+ () =>+ slashCommands && isFocused && isIdle ? matchSlashCommands(slashCommands, inputText) : [],+ [slashCommands, isFocused, isIdle, inputText]+ );+ const activeSlashIndex = Math.min(slashIndex, slashMatches.length - 1);++ const runSlashCommand = useCallback(+ (command: SlashCommand) => {+ if (command.disabled) return;+ setInputText("");+ command.run();+ },+ [setInputText]+ );+const handleSubmit = useCallback(() => {const text = inputText.trim();if (!text || !onTextSubmit || isBusy) return;@@ -141,6 +164,33 @@ export function ChatInput({const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {+ if (slashMatches.length > 0 && !e.nativeEvent.isComposing) {+ const step = e.key === "ArrowDown" ? 1 : e.key === "ArrowUp" ? -1 : 0;+ if (step !== 0) {+ e.preventDefault();+ setSlashIndex((activeSlashIndex + step + slashMatches.length) % slashMatches.length);+ return;+ }+ const command = slashMatches[activeSlashIndex];+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ runSlashCommand(command);+ return;+ }+ // Tab runs like Enter, but lets focus move on past a command that can't run.+ if (e.key === "Tab" && !e.shiftKey && !command.disabled) {+ e.preventDefault();+ runSlashCommand(command);+ return;+ }+ // Dismiss the menu, not the composer.+ if (e.key === "Escape") {+ e.preventDefault();+ e.stopPropagation();+ setInputText("");+ return;+ }+ }if (e.key === "Escape" && onEscape) {e.preventDefault();e.stopPropagation();@@ -153,7 +203,7 @@ export function ChatInput({handleSubmit();}},- [handleSubmit, onEscape]+ [handleSubmit, onEscape, slashMatches, activeSlashIndex, runSlashCommand, setInputText]);useLayoutEffect(() => {@@ -185,6 +235,27 @@ export function ChatInput({return (<div className={cn("shrink-0", className ?? "px-3 pb-3 pt-1")}>+ {slashCommands && (+ <Popover open={slashMatches.length > 0}>+ <PopoverAnchor virtualRef={composerRef} />+ <PopoverContent+ side="top"+ className="w-72 p-1"+ // Focus stays in the composer, which drives the menu from the keyboard.+ onOpenAutoFocus={(event) => event.preventDefault()}+ onCloseAutoFocus={(event) => event.preventDefault()}+ >+ <SlashCommandMenu+ id={slashMenuId}+ label={t("agentMode.input.commands")}+ commands={slashMatches}+ activeIndex={activeSlashIndex}+ onActiveIndexChange={setSlashIndex}+ onRun={runSlashCommand}+ />+ </PopoverContent>+ </Popover>+ )}<divref={composerRef}className={cn(@@ -310,9 +381,22 @@ export function ChatInput({ref={inputRef}rows={1}value={inputText}- onChange={(e) => setInputText(e.target.value)}+ onChange={(e) => {+ setInputText(e.target.value);+ setSlashIndex(0);+ }}onKeyDown={handleKeyDown}- onFocus={onFocus}+ onFocus={() => {+ setIsFocused(true);+ setSlashIndex(0);+ onFocus?.();+ }}+ onBlur={() => setIsFocused(false)}+ aria-autocomplete={slashCommands ? "list" : undefined}+ aria-controls={slashMatches.length > 0 ? slashMenuId : undefined}+ aria-activedescendant={+ slashMatches.length > 0 ? slashOptionId(slashMenuId, activeSlashIndex) : undefined+ }// Read-only, not disabled: disabling would drop focus for the length of every reply.readOnly={isBusy}autoFocus={autoFocus}@@ -326,7 +410,6 @@ export function ChatInput({isBusy && "text-muted-foreground/70 cursor-not-allowed")}/>- {isIdle && !inputText.trim() && trailingContent}{isBusy && onCancel ? (<buttontype="button"diff --git a/src/components/chat/SlashCommandMenu.tsx b/src/components/chat/SlashCommandMenu.tsxnew file mode 100644index 000000000..0eb3041b9--- /dev/null+++ b/src/components/chat/SlashCommandMenu.tsx@@ -0,0 +1,55 @@+import { cn } from "../lib/utils";+import { slashOptionId, type SlashCommand } from "./slashCommands";++interface SlashCommandMenuProps {+ id: string;+ label: string;+ commands: SlashCommand[];+ activeIndex: number;+ onActiveIndexChange: (index: number) => void;+ onRun: (command: SlashCommand) => void;+}++/** The command list the composer drives from its keyboard while its draft starts with "/". */+export default function SlashCommandMenu({+ id,+ label,+ commands,+ activeIndex,+ onActiveIndexChange,+ onRun,+}: SlashCommandMenuProps) {+ return (+ <div id={id} role="listbox" aria-label={label} className="flex flex-col">+ {commands.map((command, index) => (+ <button+ key={command.id}+ id={slashOptionId(id, index)}+ type="button"+ role="option"+ aria-selected={index === activeIndex}+ aria-disabled={command.disabled}+ tabIndex={-1}+ // Keep focus in the composer.+ onMouseDown={(event) => event.preventDefault()}+ onClick={() => onRun(command)}+ onMouseEnter={() => onActiveIndexChange(index)}+ className={cn(+ "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-start text-xs text-foreground/70 transition-colors",+ index === activeIndex && "bg-foreground/5 text-foreground",+ command.disabled ? "cursor-default opacity-40" : "cursor-pointer"+ )}+ >+ <span dir="auto" className="min-w-0 flex-1 truncate font-medium">+ {command.label}+ </span>+ {command.hint && (+ <span className="shrink-0 rounded bg-foreground/5 px-1 py-px text-[10px] font-medium text-muted-foreground/70 dark:bg-white/6">+ {command.hint}+ </span>+ )}+ </button>+ ))}+ </div>+ );+}diff --git a/src/components/chat/slashCommands.ts b/src/components/chat/slashCommands.tsnew file mode 100644index 000000000..201f16e3f--- /dev/null+++ b/src/components/chat/slashCommands.ts@@ -0,0 +1,29 @@+export interface SlashCommand {+ id: string;+ label: string;+ /** A short tag after the label, such as where the command's output goes. */+ hint?: string;+ disabled?: boolean;+ run: () => void;+}++/**+ * The commands a draft of "/" (or the full-width "/" a CJK input method types)+ * plus a filter asks for, none when it isn't one.+ * Labels with a word starting with the filter come first, so "/s" offers+ * "Shorten" before "Make to-dos"; any other match still counts, since labels+ * in languages written without spaces have no words to start.+ */+export function matchSlashCommands(commands: SlashCommand[], draft: string): SlashCommand[] {+ const query = /^[//]([^\n]*)$/.exec(draft)?.[1].trim().toLowerCase();+ if (query === undefined) return [];+ const startsAWord = (label: string) =>+ label.split(/[^\p{L}\p{N}]+/u).some((word) => word.startsWith(query));+ return commands+ .map((command) => ({ command, label: command.label.toLowerCase() }))+ .filter(({ label }) => label.includes(query))+ .sort((a, b) => Number(!startsAWord(a.label)) - Number(!startsAWord(b.label)))+ .map(({ command }) => command);+}++export const slashOptionId = (menuId: string, index: number) => `${menuId}-${index}`;diff --git a/src/components/chat/useChatStreaming.ts b/src/components/chat/useChatStreaming.tsindex 1224da645..4c01ae813 100644--- a/src/components/chat/useChatStreaming.ts+++ b/src/components/chat/useChatStreaming.ts@@ -137,6 +137,11 @@ export interface SendToAIOptions {attachment?: ChatImageAttachment;/** Agent-response selection attached to this request without changing chat history. */selectedContext?: AgentSelectionContext;+ /**+ * Sent to the model in place of this turn's visible message, which is what the+ * chat shows and saves (a note action shows its name while its prompt is sent).+ */+ requestText?: string;/** Keeps a caret-destined voice response in the compact pill while it streams. */suppressResponseContent?: boolean;/** Asks the model for plain prose because the answer will be pasted into a plain-text app. */@@ -422,8 +427,9 @@ export function useChatStreaming({}}+ // A note action is about the note in context; other notes would only add noise.const [ragContext, attendeesContext] = await Promise.all([- buildRAGContext(userText, scope),+ options?.requestText ? "" : buildRAGContext(userText, scope),connectorsOffered ? buildNoteAttendeesContext(noteMeetingRef.current) : "",]);if (cancelled() || !mountedRef.current) return;@@ -448,6 +454,11 @@ export function useChatStreaming({.slice(-20).map((m) => ({ role: m.role, content: m.content }));+ const requestText = options?.requestText;+ if (requestText) {+ transformLastUserMessage(history, (message) => ({ ...message, content: requestText }));+ }+const selectedContext = options?.selectedContext;if (selectedContext) {transformLastUserMessage(history, (message) =>diff --git a/src/components/notes/ActionChips.tsx b/src/components/notes/ActionChips.tsxnew file mode 100644index 000000000..a5c3aae1e--- /dev/null+++ b/src/components/notes/ActionChips.tsx@@ -0,0 +1,102 @@+import { useTranslation } from "react-i18next";+import { Blocks, Settings2, Sparkles, MessageSquareText } from "../icons";+import {+ DropdownMenu,+ DropdownMenuTrigger,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+} from "../ui/dropdown-menu";+import { getActionName, getActionDescription } from "../../stores/actionStore";+import type { ActionItem } from "../../types/electron";+import { ASK_PILL_CLASS } from "./shared";+import { getActionIcon } from "./actionIcons";++const VISIBLE_CHIPS = 4;++interface ActionChipsProps {+ /** Actions only; templates have their own picker. */+ actions: ActionItem[];+ canRun: (action: ActionItem) => boolean;+ onRunAction: (action: ActionItem) => void;+ onManageActions: () => void;+}++/** The first actions as one-click chips, then every action behind "All actions". */+export default function ActionChips({+ actions,+ canRun,+ onRunAction,+ onManageActions,+}: ActionChipsProps) {+ const { t } = useTranslation();++ return (+ <div className="scrollbar-hidden flex items-center justify-center-safe gap-1.5 overflow-x-auto">+ {actions.slice(0, VISIBLE_CHIPS).map((action) => {+ const Icon = getActionIcon(action);+ return (+ <button+ key={action.id}+ type="button"+ // Keep focus in the composer, so an open chat can take a follow-up right away.+ onMouseDown={(event) => event.preventDefault()}+ onClick={() => onRunAction(action)}+ disabled={!canRun(action)}+ className={ASK_PILL_CLASS}+ >+ <Icon size={11} className="shrink-0 text-foreground/45" />+ <span dir="auto">{getActionName(action, t)}</span>+ </button>+ );+ })}+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button type="button" className={ASK_PILL_CLASS}>+ <Blocks size={11} className="shrink-0 text-foreground/45" />+ {t("notes.actions.allActions")}+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" side="top" sideOffset={8} className="min-w-48">+ {actions.map((action) => {+ const editsSummary = action.output === "summary";+ const OutputIcon = editsSummary ? Sparkles : MessageSquareText;+ return (+ <DropdownMenuItem+ key={action.id}+ onClick={() => onRunAction(action)}+ disabled={!canRun(action)}+ className="text-xs gap-2.5 rounded-md px-2.5 py-1.5"+ >+ <OutputIcon size={12} className="text-accent/50 shrink-0" />+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-1.5">+ <span dir="auto" className="font-medium truncate">+ {getActionName(action, t)}+ </span>+ <span className="text-[10px] font-medium px-1 py-px rounded bg-foreground/5 dark:bg-white/6 text-muted-foreground/70 shrink-0">+ {t(+ editsSummary ? "notes.actions.output.summary" : "notes.actions.output.chat"+ )}+ </span>+ </div>+ <div className="text-xs text-muted-foreground/70 truncate">+ {getActionDescription(action, t)}+ </div>+ </div>+ </DropdownMenuItem>+ );+ })}+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={onManageActions}+ className="text-xs gap-2.5 rounded-md px-2.5 py-1.5 text-muted-foreground/70"+ >+ <Settings2 size={12} />+ {t("notes.actions.manage")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+}diff --git a/src/components/notes/ActionManagerDialog.tsx b/src/components/notes/ActionManagerDialog.tsxindex 8d6c1f487..3e6d0ef2a 100644--- a/src/components/notes/ActionManagerDialog.tsx+++ b/src/components/notes/ActionManagerDialog.tsx@@ -1,58 +1,98 @@import { useState, useEffect, useRef } from "react";import { useTranslation } from "react-i18next";-import { Sparkles, Trash2, Loader2, Plus, Zap } from "../icons";+import { Sparkles, Trash2, Loader2, Plus, Zap, ChevronUp, ChevronDown, X } from "../icons";import { Dialog, DialogContent, DialogTitle } from "../ui/dialog";import { Button } from "../ui/button";import { Input } from "../ui/input";+import { Tabs, TabsList, TabsTrigger } from "../ui/tabs";+import { useToast } from "../ui/useToast";import { cn } from "../lib/utils";-import { useActions, initializeActions, getActionName } from "../../stores/actionStore";-import type { ActionItem } from "../../types/electron";+import { useActionsOfKind, initializeActions, getActionName } from "../../stores/actionStore";+import { NOTE_ACTION_LIMITS } from "../../helpers/builtinActions";+import { normalizeSections } from "../../helpers/templatePrompts";+import type { ActionItem, ActionKind, ActionOutput, TemplateSection } from "../../types/electron";interface ActionManagerDialogProps {open: boolean;onOpenChange: (open: boolean) => void;+ initialKind: ActionKind;+ /** Picks chat or summary for an action saved with Auto. */+ onInferOutput: (prompt: string) => Promise<ActionOutput>;}-export default function ActionManagerDialog({ open, onOpenChange }: ActionManagerDialogProps) {+// Rows keep a stable key while sections are reordered or removed.+type SectionDraft = TemplateSection & { key: string };++const toDrafts = (sections: TemplateSection[] | null): SectionDraft[] =>+ (sections ?? []).map((section) => ({ ...section, key: crypto.randomUUID() }));++const TEXTAREA_CLASS = cn(+ "w-full rounded border border-border/70 bg-input px-3.5 py-3 text-sm text-foreground leading-relaxed transition-colors duration-200 outline-none resize-none",+ "placeholder:text-muted-foreground/70",+ "hover:border-border-hover",+ "focus-visible:border-primary focus-visible:ring-2 focus-visible:ring-primary/10",+ "dark:bg-surface-1 dark:border-border-subtle/60",+ "dark:focus-visible:border-border-active dark:focus-visible:ring-ring/10",+ "disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 disabled:bg-muted",+ "font-mono text-[13px]"+);++const OUTPUT_HINT_KEYS = {+ auto: "notes.actions.output.autoHint",+ chat: "notes.actions.output.chatHint",+ summary: "notes.actions.output.summaryHint",+} as const;++const ICON_BUTTON_CLASS =+ "p-1 rounded-md text-muted-foreground/70 hover:text-foreground/70 hover:bg-foreground/5 dark:hover:bg-white/6 transition-colors duration-150 disabled:opacity-30 disabled:pointer-events-none";++export default function ActionManagerDialog({+ open,+ onOpenChange,+ initialKind,+ onInferOutput,+}: ActionManagerDialogProps) {const { t } = useTranslation();- const actions = useActions();+ const { toast } = useToast();+ const [kind, setKind] = useState<ActionKind>(initialKind);+ const items = useActionsOfKind(kind);const [name, setName] = useState("");const [description, setDescription] = useState("");const [prompt, setPrompt] = useState("");+ const [sections, setSections] = useState<SectionDraft[]>([]);+ const [output, setOutput] = useState<ActionOutput | "auto">("auto");const [editingId, setEditingId] = useState<number | null>(null);const [selectedId, setSelectedId] = useState<number | null>(null);const [isSaving, setIsSaving] = useState(false);const [isCreating, setIsCreating] = useState(false);const nameInputRef = useRef<HTMLInputElement>(null);+ const isTemplate = kind === "template";const resetForm = () => {setName("");setDescription("");setPrompt("");+ setSections([]);+ setOutput("auto");setEditingId(null);};+ const showKind = (next: ActionKind) => {+ setKind(next);+ setIsCreating(false);+ setSelectedId(null);+ resetForm();+ };+useEffect(() => {if (open) {initializeActions();+ setKind(initialKind);setIsCreating(false);- setEditingId(null);setSelectedId(null);resetForm();}- }, [open]);-- // Auto-select the first action when actions load and nothing is selected- useEffect(() => {- if (open && actions.length > 0 && selectedId === null && !isCreating) {- const first = actions[0];- setSelectedId(first.id);- setEditingId(first.id);- setName(first.name);- setDescription(first.description);- setPrompt(first.prompt);- }- }, [open, actions, selectedId, isCreating]);+ }, [open, initialKind]);const handleSelectAction = (action: ActionItem) => {setSelectedId(action.id);@@ -60,9 +100,18 @@ export default function ActionManagerDialog({ open, onOpenChange }: ActionManagesetName(action.name);setDescription(action.description);setPrompt(action.prompt);+ setSections(toDrafts(action.sections));+ setOutput(action.output ?? "chat");setIsCreating(false);};+ // Auto-select the first item when the list loads and nothing is selected+ useEffect(() => {+ if (open && items.length > 0 && selectedId === null && !isCreating) {+ handleSelectAction(items[0]);+ }+ }, [open, items, selectedId, isCreating]);+const handleNewAction = () => {resetForm();setSelectedId(null);@@ -80,49 +129,102 @@ export default function ActionManagerDialog({ open, onOpenChange }: ActionManage}};+ const updateSection = (key: string, patch: Partial<TemplateSection>) =>+ setSections((current) => current.map((s) => (s.key === key ? { ...s, ...patch } : s)));++ const moveSection = (index: number, offset: number) =>+ setSections((current) => {+ const next = [...current];+ [next[index], next[index + offset]] = [next[index + offset], next[index]];+ return next;+ });++ const savedSections: TemplateSection[] = normalizeSections(sections);+ // A section without a heading isn't saved, so its instruction would be lost.+ const hasHeadlessInstruction = sections.some(+ (section) => section.instruction.trim() && normalizeSections([section]).length === 0+ );+ const canSave =+ !!name.trim() &&+ !hasHeadlessInstruction &&+ (isTemplate ? !!prompt.trim() || savedSections.length > 0 : !!prompt.trim());+const handleSave = async () => {- if (!name.trim() || !prompt.trim()) return;+ if (!canSave) return;setIsSaving(true);try {- if (editingId !== null) {- await window.electronAPI.updateAction(editingId, {- name: name.trim(),- description: description.trim(),- prompt: prompt.trim(),- });- } else {- await window.electronAPI.createAction(name.trim(), description.trim(), prompt.trim());- setIsCreating(false);+ const fields = isTemplate+ ? { sections: savedSections }+ : { output: output === "auto" ? await onInferOutput(prompt.trim()) : output };+ const result =+ editingId !== null+ ? await window.electronAPI.updateAction(editingId, {+ name: name.trim(),+ description: description.trim(),+ prompt: prompt.trim(),+ ...fields,+ })+ : await window.electronAPI.createAction(+ name.trim(),+ description.trim(),+ prompt.trim(),+ undefined,+ { kind, ...fields }+ );+ if (!result.success) {+ toast({ title: t("notes.actions.errors.saveFailed"), variant: "destructive" });+ return;}+ if (editingId === null) setIsCreating(false);} finally {setIsSaving(false);}};const showEditor = isCreating || selectedId !== null;- const selectedAction = actions.find((a) => a.id === selectedId);+ const selectedAction = items.find((a) => a.id === selectedId);const hasUnsavedChanges = isCreating- ? name.trim() !== "" || prompt.trim() !== ""+ ? name.trim() !== "" || prompt.trim() !== "" || savedSections.length > 0: selectedAction? name !== selectedAction.name ||description !== selectedAction.description ||- prompt !== selectedAction.prompt+ prompt !== selectedAction.prompt ||+ JSON.stringify(savedSections) !== JSON.stringify(selectedAction.sections ?? []) ||+ (!isTemplate && output !== selectedAction.output): false;return (<Dialog open={open} onOpenChange={onOpenChange}><DialogContent className="sm:max-w-3xl p-0 gap-0 overflow-hidden">{/* Hidden accessible title */}- <DialogTitle className="sr-only">{t("notes.actions.manageTitle")}</DialogTitle>+ <DialogTitle className="sr-only">{t("notes.templates.managerTitle")}</DialogTitle><div className="flex h-120">- {/* Left panel — action list */}- <div className="w-56 shrink-0 border-e border-border dark:border-white/10 flex flex-col bg-card/50 dark:bg-surface-1/30">+ {/* Left panel — template/action list */}+ <div+ // Auto can take a moment on save; switching away then would drop the new draft.+ inert={isSaving}+ className={cn(+ "w-56 shrink-0 border-e border-border dark:border-white/10 flex flex-col bg-card/50 dark:bg-surface-1/30",+ isSaving && "opacity-60"+ )}+ >{/* List header */}- <div className="flex items-center justify-between px-3 pt-3.5 pb-2">- <span className="text-xs font-semibold tracking-tight text-foreground/70">- {t("notes.actions.manageTitle")}- </span>+ <div className="flex items-center gap-1.5 px-3 pt-3.5 pb-2">+ <Tabs+ value={kind}+ onValueChange={(value) => showKind(value as ActionKind)}+ className="flex-1 min-w-0"+ >+ <TabsList className="h-7 w-full p-0.5">+ <TabsTrigger value="template" className="flex-1 px-2 py-0.5 text-xs">+ {t("notes.templates.tab")}+ </TabsTrigger>+ <TabsTrigger value="action" className="flex-1 px-2 py-0.5 text-xs">+ {t("notes.actions.tab")}+ </TabsTrigger>+ </TabsList>+ </Tabs><buttononClick={handleNewAction}className={cn(@@ -132,30 +234,32 @@ export default function ActionManagerDialog({ open, onOpenChange }: ActionManage"active:bg-foreground/8 dark:active:bg-white/8","transition-colors duration-150")}- aria-label={t("notes.actions.addAction")}+ aria-label={t(+ isTemplate ? "notes.templates.addTemplate" : "notes.actions.addAction"+ )}><Plus size={13} /></button></div>- {/* Action list */}+ {/* Template/action list */}<div className="flex-1 overflow-y-auto px-1.5 pb-2">- {actions.length === 0 && !isCreating ? (+ {items.length === 0 && !isCreating ? (<div className="flex flex-col items-center justify-center h-full px-4 text-center"><Zap size={20} className="text-muted-foreground/70 mb-2" /><p className="text-xs text-muted-foreground/70 leading-relaxed">- {t("notes.actions.noActions")}+ {t(isTemplate ? "notes.templates.noTemplates" : "notes.actions.noActions")}</p><buttononClick={handleNewAction}className="text-xs text-accent/60 hover:text-accent/80 mt-2 transition-colors duration-150 focus:outline-none focus-visible:ring-1 focus-visible:ring-ring/30 rounded">- {t("notes.actions.addAction")}+ {t(isTemplate ? "notes.templates.addTemplate" : "notes.actions.addAction")}</button></div>) : (<div className="space-y-0.5">- {actions.map((action) => (+ {items.map((action) => (<divkey={action.id}onClick={() => handleSelectAction(action)}@@ -227,7 +331,13 @@ export default function ActionManagerDialog({ open, onOpenChange }: ActionManage{/* Editor header — pe-12 clears the dialog close X button */}<div className="flex items-center justify-between ps-5 pe-12 pt-4 pb-3 border-b border-border/70 dark:border-white/10"><span className="text-xs font-medium text-muted-foreground/70">- {isCreating ? t("notes.actions.addAction") : t("notes.actions.editAction")}+ {isTemplate+ ? t(+ isCreating+ ? "notes.templates.addTemplate"+ : "notes.templates.editTemplate"+ )+ : t(isCreating ? "notes.actions.addAction" : "notes.actions.editAction")}</span><div className="flex items-center gap-2">{isCreating && (@@ -237,8 +347,8 @@ export default function ActionManagerDialog({ open, onOpenChange }: ActionManageonClick={() => {setIsCreating(false);resetForm();- // Re-select first action if available- if (actions.length > 0) handleSelectAction(actions[0]);+ // Re-select the first item if available+ if (items.length > 0) handleSelectAction(items[0]);}}disabled={isSaving}className="h-7 text-xs"@@ -249,7 +359,7 @@ export default function ActionManagerDialog({ open, onOpenChange }: ActionManage<Buttonsize="sm"onClick={handleSave}- disabled={isSaving || !name.trim() || !prompt.trim() || !hasUnsavedChanges}+ disabled={isSaving || !canSave || !hasUnsavedChanges}className="h-7 text-xs">{isSaving ? (@@ -270,7 +380,12 @@ export default function ActionManagerDialog({ open, onOpenChange }: ActionManageref={nameInputRef}value={name}onChange={(e) => setName(e.target.value)}- placeholder={t("notes.actions.namePlaceholder")}+ placeholder={t(+ isTemplate+ ? "notes.templates.namePlaceholder"+ : "notes.actions.namePlaceholder"+ )}+ maxLength={NOTE_ACTION_LIMITS.name}disabled={isSaving}className="h-9"/>@@ -279,48 +394,171 @@ export default function ActionManagerDialog({ open, onOpenChange }: ActionManagevalue={description}onChange={(e) => setDescription(e.target.value)}placeholder={t("notes.actions.descriptionPlaceholder")}+ maxLength={NOTE_ACTION_LIMITS.description}disabled={isSaving}className="h-9"/>- {/* Prompt — the star of the show */}+ {!isTemplate && (+ <div className="space-y-1.5">+ <Tabs+ value={output}+ onValueChange={(value) => setOutput(value as ActionOutput | "auto")}+ >+ <TabsList className="h-8 p-0.5">+ {/* A saved action keeps the output it was given, so Auto is for new ones. */}+ {editingId === null && (+ <TabsTrigger value="auto" className="px-3 py-1 text-xs">+ {t("notes.actions.output.auto")}+ </TabsTrigger>+ )}+ <TabsTrigger value="chat" className="px-3 py-1 text-xs">+ {t("notes.actions.output.chat")}+ </TabsTrigger>+ <TabsTrigger value="summary" className="px-3 py-1 text-xs">+ {t("notes.actions.output.summary")}+ </TabsTrigger>+ </TabsList>+ </Tabs>+ <p className="text-xs text-muted-foreground/70">+ {t(OUTPUT_HINT_KEYS[output])}+ </p>+ </div>+ )}++ {/* Prompt — a template's context, or what an action does */}<div className="flex flex-col flex-1 space-y-1.5 min-h-0"><label className="text-xs font-medium text-foreground/50">- {t("notes.actions.promptLabel", { defaultValue: "Prompt" })}+ {t(isTemplate ? "notes.templates.contextLabel" : "notes.actions.promptLabel")}</label><textareadir="auto"value={prompt}onChange={(e) => setPrompt(e.target.value)}- placeholder={t("notes.actions.promptPlaceholder")}- disabled={isSaving}- className={cn(- "flex-1 min-h-50 w-full rounded border border-border/70 bg-input px-3.5 py-3 text-sm text-foreground leading-relaxed transition-colors duration-200 outline-none resize-none",- "placeholder:text-muted-foreground/70",- "hover:border-border-hover",- "focus-visible:border-primary focus-visible:ring-2 focus-visible:ring-primary/10",- "dark:bg-surface-1 dark:border-border-subtle/60",- "dark:focus-visible:border-border-active dark:focus-visible:ring-ring/10",- "disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 disabled:bg-muted",- "font-mono text-[13px]"+ placeholder={t(+ isTemplate+ ? "notes.templates.contextPlaceholder"+ : "notes.actions.promptPlaceholder")}+ maxLength={NOTE_ACTION_LIMITS.prompt}+ disabled={isSaving}+ className={cn(TEXTAREA_CLASS, "flex-1", isTemplate ? "min-h-24" : "min-h-50")}/></div>++ {isTemplate && (+ <div className="space-y-2">+ <label className="text-xs font-medium text-foreground/50">+ {t("notes.templates.sectionsLabel")}+ </label>+ {sections.length === 0 && (+ <p className="text-xs text-muted-foreground/70">+ {t("notes.templates.noSectionsHint")}+ </p>+ )}+ {sections.map((section, index) => (+ <div+ key={section.key}+ className="flex gap-2 rounded border border-border/70 p-2 dark:border-border-subtle/60"+ >+ <div className="flex-1 min-w-0 space-y-1.5">+ <Input+ dir="auto"+ value={section.heading}+ onChange={(e) =>+ updateSection(section.key, { heading: e.target.value })+ }+ placeholder={t("notes.templates.sectionHeadingPlaceholder")}+ maxLength={NOTE_ACTION_LIMITS.heading}+ disabled={isSaving}+ className="h-8"+ />+ <textarea+ dir="auto"+ rows={2}+ value={section.instruction}+ onChange={(e) =>+ updateSection(section.key, { instruction: e.target.value })+ }+ placeholder={t("notes.templates.sectionInstructionPlaceholder")}+ maxLength={NOTE_ACTION_LIMITS.instruction}+ disabled={isSaving}+ className={cn(TEXTAREA_CLASS, "py-2")}+ />+ </div>+ <div className="flex flex-col gap-0.5">+ <button+ type="button"+ onClick={() => moveSection(index, -1)}+ disabled={isSaving || index === 0}+ aria-label={t("notes.templates.moveSectionUp")}+ className={ICON_BUTTON_CLASS}+ >+ <ChevronUp size={12} />+ </button>+ <button+ type="button"+ onClick={() => moveSection(index, 1)}+ disabled={isSaving || index === sections.length - 1}+ aria-label={t("notes.templates.moveSectionDown")}+ className={ICON_BUTTON_CLASS}+ >+ <ChevronDown size={12} />+ </button>+ <button+ type="button"+ onClick={() =>+ setSections((current) =>+ current.filter((s) => s.key !== section.key)+ )+ }+ disabled={isSaving}+ aria-label={t("notes.templates.removeSection")}+ className={ICON_BUTTON_CLASS}+ >+ <X size={12} />+ </button>+ </div>+ </div>+ ))}+ <Button+ variant="outline-flat"+ size="sm"+ onClick={() =>+ setSections((current) => [+ ...current,+ { heading: "", instruction: "", key: crypto.randomUUID() },+ ])+ }+ disabled={isSaving || sections.length >= NOTE_ACTION_LIMITS.sections}+ className="h-7 text-xs gap-1.5"+ >+ <Plus size={12} />+ {t("notes.templates.addSection")}+ </Button>+ </div>+ )}</div></>) : (- /* Empty state — no action selected */+ /* Empty state — nothing selected */<div className="flex-1 flex flex-col items-center justify-center text-center px-8"><div className="w-10 h-10 rounded-xl bg-accent/5 dark:bg-accent/8 flex items-center justify-center mb-3"><Sparkles size={18} className="text-accent/30" /></div><p className="text-sm font-medium text-foreground/45 mb-1">- {t("notes.actions.emptyEditorTitle", { defaultValue: "Select an action" })}+ {t(+ isTemplate+ ? "notes.templates.emptyEditorTitle"+ : "notes.actions.emptyEditorTitle"+ )}</p><p className="text-xs text-muted-foreground/70 mb-4 max-w-52 leading-relaxed">- {t("notes.actions.emptyEditorDescription", {- defaultValue: "Choose an action from the list or create a new one",- })}+ {t(+ isTemplate+ ? "notes.templates.emptyEditorDescription"+ : "notes.actions.emptyEditorDescription"+ )}</p><Buttonvariant="outline-flat"@@ -329,7 +567,7 @@ export default function ActionManagerDialog({ open, onOpenChange }: ActionManageclassName="h-7 text-xs gap-1.5"><Plus size={12} />- {t("notes.actions.addAction")}+ {t(isTemplate ? "notes.templates.addTemplate" : "notes.actions.addAction")}</Button></div>)}diff --git a/src/components/notes/ActionPicker.tsx b/src/components/notes/ActionPicker.tsxdeleted file mode 100644index bda347add..000000000--- a/src/components/notes/ActionPicker.tsx+++ /dev/null@@ -1,141 +0,0 @@-import { useState, useEffect } from "react";-import { useTranslation } from "react-i18next";-import { Sparkles, ChevronDown, Settings2 } from "../icons";-import {- DropdownMenu,- DropdownMenuTrigger,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,-} from "../ui/dropdown-menu";-import { cn } from "../lib/utils";-import {- useActions,- initializeActions,- getActionName,- getActionCta,- getActionDescription,-} from "../../stores/actionStore";-import type { ActionItem } from "../../types/electron";-import { FOLLOW_UP_EMAIL_KEY } from "../../helpers/builtinActions";--// Keyed fresh so the follow-up email default reaches installs that had-// "Generate Notes" remembered under the old key.-const ASK_BAR_ACTION_KEY = "askBarActionId";--interface ActionPickerProps {- onRunAction: (action: ActionItem) => void;- onManageActions: () => void;- disabled?: boolean;-}--export default function ActionPicker({- onRunAction,- onManageActions,- disabled,-}: ActionPickerProps) {- const { t } = useTranslation();- const actions = useActions();- const [lastUsedId, setLastUsedId] = useState<number | null>(() => {- const stored = localStorage.getItem(ASK_BAR_ACTION_KEY);- return stored ? Number(stored) : null;- });-- useEffect(() => {- initializeActions();- }, []);-- const activeAction =- actions.find((a) => a.id === lastUsedId) ??- actions.find((a) => a.translation_key === FOLLOW_UP_EMAIL_KEY) ??- actions[0] ??- null;-- const handleRun = (action: ActionItem) => {- setLastUsedId(action.id);- localStorage.setItem(ASK_BAR_ACTION_KEY, String(action.id));- onRunAction(action);- };-- if (!activeAction) return null;-- return (- <div- className={cn(- "flex items-center shrink-0 rounded-full overflow-hidden",- "bg-white/60 dark:bg-white/8",- "backdrop-blur-lg transform-gpu",- "border border-black/10 dark:border-white/14",- "shadow-(--shadow-glass)",- disabled && "opacity-40 pointer-events-none"- )}- >- <button- onClick={() => handleRun(activeAction)}- disabled={disabled}- aria-label={t("notes.actions.runAction", { name: getActionName(activeAction, t) })}- className={cn(- "flex items-center gap-1.5 h-7 ps-3 pe-1.5",- "text-accent/70 dark:text-accent/60",- "transition-colors duration-150",- "hover:bg-accent/8 dark:hover:bg-accent/12",- "hover:text-accent/90 dark:hover:text-accent/80"- )}- >- <Sparkles size={11} />- <span className="text-[11px] font-semibold tracking-tight">- {getActionCta(activeAction, t)}- </span>- </button>-- <DropdownMenu>- <DropdownMenuTrigger asChild>- <button- disabled={disabled}- aria-label={t("notes.actions.selectAction")}- className={cn(- "flex items-center justify-center h-7 w-6 pe-0.5",- "border-s border-black/6 dark:border-white/10",- "text-accent/40 dark:text-accent/30",- "transition-colors duration-150",- "hover:bg-accent/8 dark:hover:bg-accent/12",- "hover:text-accent/70"- )}- >- <ChevronDown size={10} />- </button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" side="top" sideOffset={8} className="min-w-48">- {actions.map((action) => (- <DropdownMenuItem- key={action.id}- onClick={() => handleRun(action)}- className={cn(- "text-xs gap-2.5 rounded-md px-2.5 py-1.5",- action.id === activeAction.id && "bg-accent/5"- )}- >- <Sparkles size={12} className="text-accent/50 shrink-0" />- <div className="flex-1 min-w-0">- <div className="font-medium truncate">{getActionName(action, t)}</div>- {action.description && (- <div className="text-xs text-muted-foreground/70 truncate">- {getActionDescription(action, t)}- </div>- )}- </div>- </DropdownMenuItem>- ))}- <DropdownMenuSeparator />- <DropdownMenuItem- onClick={onManageActions}- className="text-xs gap-2.5 rounded-md px-2.5 py-1.5 text-muted-foreground/70"- >- <Settings2 size={12} />- {t("notes.actions.manage")}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </div>- );-}diff --git a/src/components/notes/BackgroundActionToastListener.tsx b/src/components/notes/BackgroundActionToastListener.tsxindex c8bb090a1..d6e0adece 100644--- a/src/components/notes/BackgroundActionToastListener.tsx+++ b/src/components/notes/BackgroundActionToastListener.tsx@@ -1,28 +1,93 @@-import { useEffect } from "react";+import { useCallback, useEffect, useRef } from "react";import { useTranslation } from "react-i18next";import { useToast } from "../ui/useToast";-import { useActionProcessingStore, consumeErrorEvents } from "../../stores/actionProcessingStore";+import { ToastActionButton } from "../ui/Toast";+import {+ useActionProcessingStore,+ consumeAppliedEvents,+ consumeErrorEvents,+ selectNoteActionState,+ type ActionAppliedEvent,+} from "../../stores/actionProcessingStore";+import { getActionName } from "../../stores/actionStore";++const UNDO_WINDOW_MS = 6000;/**- * Headless. Mount once inside ToastProvider so background-action errors- * surface even after the user navigates away from the notes view.+ * Headless. Mount once inside ToastProvider so background-action results and+ * errors surface even after the user navigates away from the notes view.*/export default function BackgroundActionToastListener() {const { t } = useTranslation();- const { toast } = useToast();+ const { toast, dismiss } = useToast();const errorCount = useActionProcessingStore((s) => s.errorEvents.length);+ const appliedCount = useActionProcessingStore((s) => s.appliedEvents.length);useEffect(() => {if (errorCount === 0) return;for (const event of consumeErrorEvents()) {toast({- title: t("notes.enhance.title"),+ title: event.notice ? undefined : t("notes.enhance.title"),description: event.messageKey ? t(event.messageKey, event.messageParams) : event.message,- variant: "destructive",+ variant: event.notice ? undefined : "destructive",});}}, [errorCount, toast, t]);+ // Only a note's latest change can be undone: an older Undo would wipe out the newer run.+ const undoToastByNote = useRef(new Map<number, string>());++ // A run starting on the note retires its Undo, since the run may build on what Undo would restore.+ useEffect(+ () =>+ useActionProcessingStore.subscribe((state) => {+ for (const [noteId, toastId] of undoToastByNote.current) {+ if (selectNoteActionState(state, noteId).status !== "processing") continue;+ dismiss(toastId);+ undoToastByNote.current.delete(noteId);+ }+ }),+ [dismiss]+ );++ const offerUndo = useCallback(+ ({ noteId, action, previous }: ActionAppliedEvent) => {+ const toastId = toast({+ title: t("notes.actions.applied", { name: getActionName(action, t) }),+ duration: UNDO_WINDOW_MS,+ action: (+ <ToastActionButton+ onClick={async () => {+ // Writing to a note deleted since would bring it back.+ const note = await window.electronAPI.getNote(noteId);+ if (!note || note.deleted_at) {+ dismiss(toastId);+ return;+ }+ const result = await window.electronAPI.updateNote(noteId, previous);+ if (result?.success) dismiss(toastId);+ }}+ >+ {t("app.toasts.undo")}+ </ToastActionButton>+ ),+ });+ undoToastByNote.current.set(noteId, toastId);+ },+ [toast, dismiss, t]+ );++ // A run can finish while the app is in the background: its short Undo window+ // stays queued until the window has focus instead of running out unseen.+ useEffect(() => {+ const offerQueued = () => {+ if (document.hasFocus()) consumeAppliedEvents().forEach(offerUndo);+ };+ offerQueued();+ window.addEventListener("focus", offerQueued);+ return () => window.removeEventListener("focus", offerQueued);+ }, [appliedCount, offerUndo]);+return null;}diff --git a/src/components/notes/EmbeddedChat.tsx b/src/components/notes/EmbeddedChat.tsxindex bf0b2c4bb..52c914996 100644--- a/src/components/notes/EmbeddedChat.tsx+++ b/src/components/notes/EmbeddedChat.tsx@@ -1,9 +1,10 @@import { useEffect, useCallback } from "react";import { useTranslation } from "react-i18next";-import { X, PanelRight, Plus, AlignLeft, ClipboardCheck, FileText } from "../icons";+import { X, PanelRight, Plus, AlignLeft } from "../icons";import { cn } from "../lib/utils";import { ChatMessages } from "../chat/ChatMessages";import { ChatInput } from "../chat/ChatInput";+import type { SlashCommand } from "../chat/slashCommands";import { BrandMarkIcon } from "../dictation/BrandMarkIcon";import {DropdownMenu,@@ -13,17 +14,14 @@ import {} from "../ui/dropdown-menu";import type { Message, AgentState } from "../chat/types";import { setActiveNoteId, setActiveFolderId } from "../../stores/noteStore";+import { getActionName } from "../../stores/actionStore";+import type { ActionItem } from "../../types/electron";import type { ContainerConversationItem } from "../../hooks/useContainerChat";import { ConversationPicker } from "./ConversationPicker";+import { getActionIcon } from "./actionIcons";export type EmbeddedChatMode = "hidden" | "floating" | "sidebar";-const SIDEBAR_PROMPTS = [- { key: "embeddedChat.generateSummary", icon: AlignLeft },- { key: "embeddedChat.makeTodos", icon: ClipboardCheck },- { key: "embeddedChat.createOutline", icon: FileText },-] as const;-interface EmbeddedChatProps {mode: EmbeddedChatMode;onModeChange: (mode: EmbeddedChatMode) => void;@@ -38,6 +36,12 @@ interface EmbeddedChatProps {onSwitchConversation?: (id: number) => void;onNewChat?: () => void;active?: boolean;+ /** The note's chat actions, offered as quick actions beside the sidebar composer. */+ chatActions?: ActionItem[];+ onRunChatAction?: (action: ActionItem) => void;+ /** Writes the note's AI summary with its template; absent when it can't run now. */+ onGenerateSummary?: () => void;+ slashCommands?: SlashCommand[];}function EmptyState({ floating }: { floating: boolean }) {@@ -78,6 +82,10 @@ export default function EmbeddedChat({onSwitchConversation,onNewChat,active = true,+ chatActions = [],+ onRunChatAction,+ onGenerateSummary,+ slashCommands,}: EmbeddedChatProps) {const { t } = useTranslation();@@ -103,6 +111,25 @@ export default function EmbeddedChat({if (mode === "hidden") return null;+ const quickActions = [+ ...(onGenerateSummary+ ? [+ {+ key: "summary",+ label: t("embeddedChat.generateSummary"),+ Icon: AlignLeft,+ run: onGenerateSummary,+ },+ ]+ : []),+ ...chatActions.map((action) => ({+ key: action.client_id,+ label: getActionName(action, t),+ Icon: getActionIcon(action),+ run: () => onRunChatAction?.(action),+ })),+ ];+const hasConversationSelector =noteConversations !== undefined && onSwitchConversation !== undefined;@@ -211,26 +238,26 @@ export default function EmbeddedChat({</button></DropdownMenuTrigger><DropdownMenuContent align="start" side="top" sideOffset={8}>- {SIDEBAR_PROMPTS.map(({ key, icon: Icon }) => (- <DropdownMenuItem key={key} onClick={() => onTextSubmit(t(key))}>+ {quickActions.map(({ key, label, Icon, run }) => (+ <DropdownMenuItem key={key} onClick={run}><Icon size={15} className="text-primary" />- {t(key)}+ {label}</DropdownMenuItem>))}</DropdownMenuContent></DropdownMenu>- {SIDEBAR_PROMPTS.map(({ key, icon: Icon }) => (+ {quickActions.map(({ key, label, Icon, run }) => (<buttonkey={key}type="button"// Keep focus in the composer so it doesn't collapse and slide the pills away.onMouseDown={(event) => event.preventDefault()}- onClick={() => onTextSubmit(t(key))}+ onClick={run}disabled={agentState !== "idle"}className="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full border border-border/70 bg-background px-2.5 text-xs text-foreground/65 transition-colors hover:text-foreground disabled:opacity-40 dark:border-white/10 dark:bg-surface-2"><Icon size={14} className="text-primary" />- {t(key)}+ {label}</button>))}</div>@@ -246,6 +273,7 @@ export default function EmbeddedChat({voiceDraftfocusOnIdle={false}placeholder={t("embeddedChat.askPlaceholder")}+ slashCommands={slashCommands}/></div></div>diff --git a/src/components/notes/MeetingTranscriptChat.tsx b/src/components/notes/MeetingTranscriptChat.tsxindex 21ed45851..9df2cb0b9 100644--- a/src/components/notes/MeetingTranscriptChat.tsx+++ b/src/components/notes/MeetingTranscriptChat.tsx@@ -962,7 +962,7 @@ export function MeetingTranscriptChat({onTouchStart={handleTouchStart}onTouchMove={handleTouchMove}onTouchEnd={handleTouchEnd}- className="flex-1 min-h-0 overflow-y-auto pt-2 agent-chat-scroll pb-[var(--floating-inset,96px)]"+ className="flex-1 min-h-0 overflow-y-auto pt-2 agent-chat-scroll pb-[var(--floating-inset,132px)]"><div className={cn("px-4", contentClassName)}><div style={{ height: totalSize, width: "100%", position: "relative" }}>diff --git a/src/components/notes/NoteBottomBar.tsx b/src/components/notes/NoteBottomBar.tsxindex afdfc7fec..4e06a4530 100644--- a/src/components/notes/NoteBottomBar.tsx+++ b/src/components/notes/NoteBottomBar.tsx@@ -2,6 +2,7 @@ import { useCallback } from "react";import { useTranslation } from "react-i18next";import { ChatInput } from "../chat/ChatInput";import type { AgentState } from "../chat/types";+import type { SlashCommand } from "../chat/slashCommands";import { cn } from "../lib/utils";import { observeFloatingChatSize } from "./floatingChatLayout";@@ -14,7 +15,8 @@ interface NoteBottomBarProps {onAskSubmit: (text: string) => void;onInputFocus?: () => void;onInputEscape?: () => void;- actionPicker?: React.ReactNode;+ actionChips?: React.ReactNode;+ slashCommands?: SlashCommand[];callout?: React.ReactNode;footnote?: React.ReactNode;hideInput?: boolean;@@ -32,7 +34,8 @@ export default function NoteBottomBar({onAskSubmit,onInputFocus,onInputEscape,- actionPicker,+ actionChips,+ slashCommands,callout,footnote,hideInput = false,@@ -79,13 +82,20 @@ export default function NoteBottomBar({<divaria-hidden="true"className={cn(- "pointer-events-none absolute inset-x-0 bottom-0 h-20 bg-gradient-to-t from-background from-45% to-transparent transition-opacity duration-200",+ "pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-background from-45% to-transparent transition-opacity duration-200",+ // Taller while the action chips sit above the composer, so text fades out behind them.+ actionChips && !chatOpen && !hideInput ? "h-32" : "h-20",chatOpen && "opacity-0")}/>{callout && !chatOpen && !hideInput && (<div className="pointer-events-auto relative mb-3 flex justify-center">{callout}</div>)}+ {actionChips && !chatOpen && !hideInput && (+ <div className="pointer-events-auto relative mx-auto mb-2 w-full min-w-0 max-w-[600px] px-1">+ {actionChips}+ </div>+ )}<divref={attachPanel}data-note-chat-panel@@ -113,6 +123,7 @@ export default function NoteBottomBar({>{chatContent}</div>+ {actionChips && chatOpen && <div className="shrink-0 px-2 pt-2">{actionChips}</div>}{!hideInput && (<ChatInputclassName={cn("w-full min-w-0", chatOpen && "px-2 py-1")}@@ -129,9 +140,7 @@ export default function NoteBottomBar({focusOnIdle={chatOpen}voiceDraft={chatOpen}placeholder={t("embeddedChat.askPlaceholder")}- trailingContent={- !chatOpen && actionPicker ? <div className="shrink-0">{actionPicker}</div> : null- }+ slashCommands={slashCommands}/>)}</div>diff --git a/src/components/notes/NoteEditor.tsx b/src/components/notes/NoteEditor.tsxindex 8d6e345ef..b77a19103 100644--- a/src/components/notes/NoteEditor.tsx+++ b/src/components/notes/NoteEditor.tsx@@ -14,6 +14,7 @@ import {Search,Plus,Check,+ ChevronDown,ShieldCheck,Users,} from "../icons";@@ -61,7 +62,7 @@ import {SPLIT_BUTTON_GROUP_CLASS,SPLIT_BUTTON_SEGMENT_CLASS,} from "../ui/splitButton";-import type { NoteItem, FolderItem } from "../../types/electron";+import type { NoteItem, FolderItem, ActionItem, ActionKind } from "../../types/electron";import type { ActionProcessingState } from "../../hooks/useActionProcessing";import type { NoteActionProgress } from "../../stores/actionProcessingStore";import ActionProcessingOverlay from "./ActionProcessingOverlay";@@ -73,8 +74,24 @@ import transcriptsEmptyDark from "../../assets/empty-states/notes-transcripts-daimport { Button } from "../ui/button";import EmbeddedChat, { type EmbeddedChatMode } from "./EmbeddedChat";import { useEmbeddedChat } from "../../hooks/useEmbeddedChat";+import ActionChips from "./ActionChips";+import TemplatePicker from "./TemplatePicker";+import {+ getActionCta,+ getActionName,+ initializeActions,+ resolveTemplate,+ useActionsOfKind,+} from "../../stores/actionStore";+import { compileChatActionPrompt } from "../../helpers/templatePrompts";+import type { SlashCommand } from "../chat/slashCommands";import { formatNoteDate, formatRelativeTime, formatShortDate } from "../../utils/dateFormatting";-import { collectKnownPeople } from "../../utils/llmTranscript";+import {+ buildLlmTranscript,+ buildMeetingContext,+ collectKnownPeople,+ type MeetingIdentity,+} from "../../utils/llmTranscript";import { parseTranscriptSegments } from "../../utils/parseTranscriptSegments";import {applyTranscriptSpeakerPatch,@@ -196,9 +213,9 @@ interface NoteEditorProps {onExportNote?: (format: "md" | "txt") => void;onExportTranscript?: (format: "txt" | "srt" | "json" | "md") => void;enhancement?: Enhancement;- actionPicker?: React.ReactNode;- /** Runs the built-in Generate Notes action; enables the post-recording summary pill. */- onGenerateSummary?: () => void;+ /** Runs a template, or an action that edits the summary, on this note. */+ onRunNoteAction?: (action: ActionItem) => void;+ onManageActions?: (kind: ActionKind) => void;actionProcessingState?: ActionProcessingState;actionName?: string | null;actionProgress?: NoteActionProgress | null;@@ -232,8 +249,8 @@ export default function NoteEditor({onExportNote,onExportTranscript,enhancement,- actionPicker,- onGenerateSummary,+ onRunNoteAction,+ onManageActions,actionProcessingState,actionName,actionProgress,@@ -306,11 +323,12 @@ export default function NoteEditor({: aclRequest?.cloudId === note.cloud_id? aclRequest.state: "loading";+ const ownedByUser = ownsNote(note, user?.id);const notePermission = resolveNotePermission({cachedPermission: shareCache?.access?.my_permission,aclState,isTeamNote,- locallyOwned: ownsNote(note, user?.id),+ locallyOwned: ownedByUser,});const shareCapabilities = noteCapabilities(notePermission);const canEditNote = shareCapabilities.canEdit;@@ -415,17 +433,6 @@ export default function NoteEditor({[note.participants]);- const embeddedChat = useEmbeddedChat({- noteId: note.id,- folderId: note.folder_id,- noteTitle: note.title,- noteContent: note.content,- noteTranscript: note.transcript ?? undefined,- noteParticipants: parsedParticipants,- noteOwnedByUser: ownsNote(note, user?.id),- selfEmail: user?.email ?? null,- noteCalendarEventId: note.calendar_event_id,- });const titleRef = useRef<HTMLDivElement>(null);const prevNoteIdRef = useRef<number>(note.id);@@ -452,12 +459,31 @@ export default function NoteEditor({return parseTranscriptSegments(note.transcript || "");}, [diarizedSegments, note.transcript]);+ const templates = useActionsOfKind("template");+ const noteActions = useActionsOfKind("action");+ const chatActions = useMemo(() => noteActions.filter((a) => a.output === "chat"), [noteActions]);+ // Regenerating keeps the note's template; a first summary uses the default.+ const noteTemplate = resolveTemplate(templates, note.enhancement_template_id);+ const isActionRunning = actionProcessingState === "processing";+ const hasNoteMaterial = !!note.content.trim() || hasMeetingTranscript;+ const canRunTemplate =+ !!onRunNoteAction && !!noteTemplate && canEditNote && !isRecording && hasNoteMaterial;+ // The AI Summary tab names the template that wrote the summary, when it still exists.+ const summaryLabel =+ noteTemplate && noteTemplate.client_id === note.enhancement_template_id+ ? getActionName(noteTemplate, t)+ : t("notes.editor.aiSummary");++ useEffect(() => {+ initializeActions();+ }, []);+const hasChatSegments = displaySegments.length > 0;const showSummaryCallout =- !!onGenerateSummary &&+ canRunTemplate &&shouldOfferMeetingSummary({isRecording,- hasTranscriptSegments: hasChatSegments,+ hasTranscriptSegments: hasNoteMaterial,hasSummary: !!enhancement,canEdit: canEditNote,isProcessingAction: actionProcessingState === "processing",@@ -468,20 +494,48 @@ export default function NoteEditor({[displaySegments, speakerMappings, speakerProfiles]);+ const meetingIdentity = useMemo<MeetingIdentity>(+ () => ({+ selfName: user?.name?.trim() || null,+ selfEmail: user?.email?.trim() || null,+ participants: parsedParticipants,+ }),+ [user?.name, user?.email, parsedParticipants]+ );+const mentionPeople = useMemo(- () =>- collectKnownPeople(- {- selfName: user?.name?.trim() || null,- selfEmail: user?.email?.trim() || null,- participants: parsedParticipants,- },- speakerMappings,- displaySegments- ),- [user?.name, user?.email, parsedParticipants, speakerMappings, displaySegments]+ () => collectKnownPeople(meetingIdentity, speakerMappings, displaySegments),+ [meetingIdentity, speakerMappings, displaySegments]);+ // The chat reads the user's own meeting the way note formatting does: who the+ // user is and named speakers, not the stored segment JSON. Invitees are left to+ // the filtered attendee block that comes with connector tools (a chat without+ // them names only speakers), and a teammate's mic lines aren't the user's.+ const chatTranscript = useMemo(() => {+ if (displaySegments.length === 0 || !ownedByUser) return note.transcript ?? undefined;+ const selfLabel = meetingIdentity.selfName || t("notes.speaker.you");+ return [+ buildMeetingContext({ ...meetingIdentity, participants: [] }, selfLabel),+ buildLlmTranscript(displaySegments, speakerMappings, selfLabel, t),+ ]+ .filter(Boolean)+ .join("\n\n");+ }, [displaySegments, meetingIdentity, note.transcript, ownedByUser, speakerMappings, t]);++ const embeddedChat = useEmbeddedChat({+ noteId: note.id,+ folderId: note.folder_id,+ noteTitle: note.title,+ noteContent: note.content,+ noteTranscript: chatTranscript,+ noteSummary: enhancement?.content,+ noteParticipants: parsedParticipants,+ noteOwnedByUser: ownedByUser,+ selfEmail: user?.email ?? null,+ noteCalendarEventId: note.calendar_event_id,+ });+const refreshSpeakerProfiles = useCallback(() => {window.electronAPI?.getSpeakerProfiles?.().then((profiles) => {setSpeakerProfiles(@@ -498,7 +552,7 @@ export default function NoteEditor({const container = segmentContainerRef.current;if (!container) return;- const buttons = container.querySelectorAll<HTMLButtonElement>("[data-segment-button]");+ const buttons = container.querySelectorAll<HTMLElement>("[data-segment-button]");const activeBtn = Array.from(buttons).find((btn) => btn.dataset.segmentValue === viewMode);if (!activeBtn) {setIndicatorStyle((style) => ({ ...style, opacity: 0 }));@@ -827,6 +881,53 @@ export default function NoteEditor({[chatMode, embeddedChat]);+ // The chat shows the action's name while the model gets its prompt.+ const handleChatAction = useCallback(+ (action: ActionItem) => {+ if (embeddedChat.agentState !== "idle") return;+ if (chatMode === "hidden") {+ setChatMode("floating");+ }+ void embeddedChat.sendMessage(getActionCta(action, t), {+ requestText: compileChatActionPrompt(action, { fromSummary: !!enhancement }),+ });+ },+ [chatMode, embeddedChat, enhancement, t]+ );++ const runAction = useCallback(+ (action: ActionItem) => {+ if (action.output === "chat") {+ handleChatAction(action);+ return;+ }+ // Uncover the summary the action rewrites; a docked chat already sits beside it.+ if (chatMode === "floating") handleChatModeChange("hidden");+ onRunNoteAction?.(action);+ },+ [chatMode, handleChatAction, handleChatModeChange, onRunNoteAction]+ );+ const offersActions =+ !isRecording &&+ canEditNote &&+ !(viewMode === "transcript" && !hasMeetingTranscript && !hasChatSegments);+ // A summary action waits for a run already writing the summary; a chat action+ // for the reply the chat is still writing.+ const canRunAction = (action: ActionItem) =>+ hasNoteMaterial &&+ (action.output === "summary" ? !isActionRunning : embeddedChat.agentState === "idle");+ const actionCommands: SlashCommand[] | undefined = offersActions+ ? noteActions.map((action) => ({+ id: action.client_id,+ label: getActionName(action, t),+ hint: t(+ action.output === "summary" ? "notes.actions.output.summary" : "notes.actions.output.chat"+ ),+ disabled: !canRunAction(action),+ run: () => runAction(action),+ }))+ : undefined;+const handleChatInputFocus = useCallback(() => {if (chatMode === "hidden") {setChatMode("floating");@@ -1117,26 +1218,47 @@ export default function NoteEditor({{t("notes.editor.notes")}</button>{enhancement && (- <button+ <divdata-segment-buttondata-segment-value="enhanced"- onClick={() => setSelectedViewMode("enhanced")}className={cn(- SEGMENT_BUTTON_CLASS,+ "relative z-1 flex items-center",viewMode === "enhanced"? "text-foreground": "text-foreground/60 hover:text-foreground/80")}>- <Sparkles size={12} />- {t("notes.editor.aiSummary")}- {enhancement.isStale && (- <span- className="h-1 w-1 rounded-full bg-amber-400/60"- title={t("notes.editor.staleIndicator")}- />+ <button+ onClick={() => setSelectedViewMode("enhanced")}+ className={cn(SEGMENT_BUTTON_CLASS, canRunTemplate && "pe-1")}+ >+ <Sparkles size={12} />+ <span className="max-w-32 truncate">{summaryLabel}</span>+ {enhancement.isStale && (+ <span+ className="h-1 w-1 rounded-full bg-amber-400/60"+ title={t("notes.editor.staleIndicator")}+ />+ )}+ </button>+ {canRunTemplate && noteTemplate && (+ <TemplatePicker+ templates={templates}+ current={noteTemplate}+ onRun={(template) => onRunNoteAction?.(template)}+ onManage={() => onManageActions?.("template")}+ disabled={isActionRunning}+ >+ <button+ type="button"+ aria-label={t("notes.templates.select")}+ className={cn(SEGMENT_BUTTON_CLASS, "ps-1 pe-2")}+ >+ <ChevronDown size={12} />+ </button>+ </TemplatePicker>)}- </button>+ </div>)}</div></div>@@ -1355,17 +1477,25 @@ export default function NoteEditor({/>)}- actionPicker={- isRecording ||- !canEditNote ||- (viewMode === "transcript" && !hasMeetingTranscript && !hasChatSegments)- ? undefined- : actionPicker+ actionChips={+ offersActions && (+ <ActionChips+ actions={noteActions}+ canRun={canRunAction}+ onRunAction={runAction}+ onManageActions={() => onManageActions?.("action")}+ />+ )}+ slashCommands={actionCommands}callout={showSummaryCallout &&+ noteTemplate &&selectedSegmentIds.size === 0 && (- <Button className="h-9 gap-2 px-4 text-sm" onClick={onGenerateSummary}>+ <Button+ className="h-9 gap-2 px-4 text-sm"+ onClick={() => onRunNoteAction?.(noteTemplate)}+ ><AlignLeft size={16} />{t("notes.editor.generateSummary")}</Button>@@ -1398,6 +1528,14 @@ export default function NoteEditor({activeConversationId={embeddedChat.activeConversationId}onSwitchConversation={embeddedChat.switchConversation}onNewChat={embeddedChat.startNewChat}+ chatActions={chatActions}+ onRunChatAction={handleChatAction}+ slashCommands={actionCommands}+ onGenerateSummary={+ canRunTemplate && noteTemplate && !isActionRunning+ ? () => onRunNoteAction?.(noteTemplate)+ : undefined+ }/>)}<ShareNoteDialogdiff --git a/src/components/notes/NotesOnboarding.tsx b/src/components/notes/NotesOnboarding.tsxindex ce740b030..d734e2d7d 100644--- a/src/components/notes/NotesOnboarding.tsx+++ b/src/components/notes/NotesOnboarding.tsx@@ -10,11 +10,14 @@ import {useSettingsStore,} from "../../stores/settingsStore";import { useNotesOnboarding } from "../../hooks/useNotesOnboarding";+import { NOTE_ACTION_LIMITS } from "../../helpers/builtinActions";+import { useToast } from "../ui/useToast";import {- useActions,+ useActionsOfKind,initializeActions,getActionName,getActionDescription,+ resolveTemplate,} from "../../stores/actionStore";import { notesInputClass, notesTextareaClass } from "./shared";import { useDialogs } from "../../hooks/useDialogs";@@ -36,8 +39,9 @@ interface NotesOnboardingProps {export default function NotesOnboarding({ onComplete }: NotesOnboardingProps) {const { t } = useTranslation();+ const { toast } = useToast();const { isProUser, isProLoading, isLLMConfigured, complete } = useNotesOnboarding();- const actions = useActions();+ const templates = useActionsOfKind("template");const [llmExpanded, setLlmExpanded] = useState(!isLLMConfigured && !isProUser);const [createExpanded, setCreateExpanded] = useState(false);const [actionName, setActionName] = useState("");@@ -89,11 +93,15 @@ export default function NotesOnboarding({ onComplete }: NotesOnboardingProps) {if (!actionName.trim() || !actionPrompt.trim()) return;setIsSaving(true);try {- await window.electronAPI.createAction(+ const result = await window.electronAPI.createAction(actionName.trim(),actionDescription.trim(),actionPrompt.trim());+ if (!result.success) {+ toast({ title: t("notes.actions.errors.saveFailed"), variant: "destructive" });+ return;+ }setActionName("");setActionDescription("");setActionPrompt("");@@ -109,8 +117,9 @@ export default function NotesOnboarding({ onComplete }: NotesOnboardingProps) {onComplete();};- const builtInAction = actions.find((a) => a.is_builtin === 1);- const customActions = actions.filter((a) => a.is_builtin !== 1);+ // The template the summary button writes with, and the ones the user made.+ const builtInAction = resolveTemplate(templates, null);+ const customActions = templates.filter((a) => a.is_builtin !== 1);return (<div className="h-full overflow-y-auto">@@ -123,10 +132,10 @@ export default function NotesOnboarding({ onComplete }: NotesOnboardingProps) {<Sparkles size={20} className="text-foreground/60" /></div><h2 className="text-xl font-semibold tracking-tight text-foreground">- {t("notes.onboarding.actions.title")}+ {t("notes.onboarding.templates.title")}</h2><p className="max-w-xl text-[13px] leading-relaxed text-foreground/50 dark:text-foreground/45">- {t("notes.onboarding.actions.description")}+ {t("notes.onboarding.templates.description")}</p></div>@@ -231,7 +240,7 @@ export default function NotesOnboarding({ onComplete }: NotesOnboardingProps) {{/* Built-in action, plus any custom actions the user just created */}<div><p className="pb-2.5 text-sm text-muted-foreground">- {t("notes.onboarding.actions.builtInLabel")}+ {t("notes.onboarding.templates.builtInLabel")}</p>{(builtInAction || customActions.length > 0) && (<div@@ -287,11 +296,11 @@ export default function NotesOnboarding({ onComplete }: NotesOnboardingProps) {<div className="flex items-center gap-3"><Plus size={16} className="text-foreground/45" /><span className="text-sm font-medium text-foreground">- {t("notes.onboarding.actions.createTitle")}+ {t("notes.onboarding.templates.createTitle")}</span>{justCreated && (<span className="text-xs font-medium text-success/70">- {t("notes.onboarding.actions.created")}+ {t("notes.onboarding.templates.created")}</span>)}</div>@@ -307,15 +316,16 @@ export default function NotesOnboarding({ onComplete }: NotesOnboardingProps) {{createExpanded && (<div className="space-y-2.5 px-5 pb-5" style={{ animation: "float-up 0.2s ease-out" }}><p className="text-sm leading-relaxed text-muted-foreground">- {t("notes.onboarding.actions.createDescription")}+ {t("notes.onboarding.templates.createDescription")}</p><inputdir="auto"type="text"value={actionName}onChange={(e) => setActionName(e.target.value)}- placeholder={t("notes.actions.namePlaceholder")}- aria-label={t("notes.actions.namePlaceholder")}+ maxLength={NOTE_ACTION_LIMITS.name}+ placeholder={t("notes.templates.namePlaceholder")}+ aria-label={t("notes.templates.namePlaceholder")}disabled={isSaving}className={cn(notesInputClass, "h-9 text-sm disabled:opacity-40")}/>@@ -324,6 +334,7 @@ export default function NotesOnboarding({ onComplete }: NotesOnboardingProps) {type="text"value={actionDescription}onChange={(e) => setActionDescription(e.target.value)}+ maxLength={NOTE_ACTION_LIMITS.description}placeholder={t("notes.actions.descriptionPlaceholder")}aria-label={t("notes.actions.descriptionPlaceholder")}disabled={isSaving}@@ -333,8 +344,9 @@ export default function NotesOnboarding({ onComplete }: NotesOnboardingProps) {dir="auto"value={actionPrompt}onChange={(e) => setActionPrompt(e.target.value)}- placeholder={t("notes.actions.promptPlaceholder")}- aria-label={t("notes.actions.promptPlaceholder")}+ maxLength={NOTE_ACTION_LIMITS.prompt}+ placeholder={t("notes.templates.contextPlaceholder")}+ aria-label={t("notes.templates.contextPlaceholder")}rows={3}disabled={isSaving}className={cn(notesTextareaClass, "text-sm disabled:opacity-40")}diff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsxindex 034a3902b..98cdacf3f 100644--- a/src/components/notes/PersonalNotesView.tsx+++ b/src/components/notes/PersonalNotesView.tsx@@ -7,14 +7,13 @@ import NoteEditor from "./NoteEditor";import SpacesTree from "./SpacesTree";import { ContainerOverview } from "./overview/ContainerOverview";import NotesStructureIntroDialog from "./NotesStructureIntroDialog";-import ActionPicker from "./ActionPicker";import ActionManagerDialog from "./ActionManagerDialog";import AddNotesToFolderDialog from "./AddNotesToFolderDialog";import { useActionProcessing } from "../../hooks/useActionProcessing";import type { NoteMoveTarget } from "../../hooks/useNoteDragAndDrop";-import type { ActionItem, NoteItem } from "../../types/electron";-import { useActions } from "../../stores/actionStore";-import { DETAILED_NOTES_KEY } from "../../helpers/builtinActions";+import type { ActionItem, ActionKind, NoteItem } from "../../types/electron";+import { buildNoteRunInput } from "../../helpers/templatePrompts";+import { inferActionOutput } from "../../utils/inferActionOutput";import {useSettingsStore,selectIsCloudNoteFormattingMode,@@ -145,7 +144,7 @@ export default function PersonalNotesView({const [isSaving, setIsSaving] = useState(false);const [draft, setDraftState] = useState<NoteEditorDraft | null>(null);const draftRef = useRef<NoteEditorDraft | null>(null);- const [showActionManager, setShowActionManager] = useState(false);+ const [managerKind, setManagerKind] = useState<ActionKind | null>(null);const [showAddNotesDialog, setShowAddNotesDialog] = useState(false);const pendingDocumentRef = useRef<PendingDocumentSave | null>(null);const pendingEnhancedRef = useRef<PendingEnhancedSave | null>(null);@@ -247,7 +246,6 @@ export default function PersonalNotesView({const sessionExpectedCount = useMeetingRecordingStore((s) => s.sessionExpectedCount);const userTouchedStepper = useMeetingRecordingStore((s) => s.userTouchedStepper);const meetingRecordingAllowed = useTranscriptionContextAllowed("meeting");- const actions = useActions();const spaces = useSpaces();const folders = useFolders();@@ -568,10 +566,6 @@ export default function PersonalNotesView({cancel: cancelAction,} = useActionProcessing(activeNoteId ?? null);- // Boolean flag so actions enable during recording without re-rendering on every transcript update.- const hasLiveTranscript = useMeetingRecordingStore(- (s) => s.recordingNoteId === activeNote?.id && !!s.transcript- );const activeNoteRawTranscript = activeNote?.transcript || "";const activeDraft = draft?.noteId === activeNote?.id ? draft : null;const editorNote = activeNote@@ -687,25 +681,19 @@ export default function PersonalNotesView({}}- const parts = [- hasNotes ? noteContent : "",+ const { input, fromSummary, material } = buildNoteRunInput(action, {+ summary: editorEnhancedContent,+ notes: noteContent,meetingContext,- formattedTranscript ? `## Meeting Transcript\n${formattedTranscript}` : "",- ]- .filter(Boolean)- .join("\n\n");- runAction(action, parts, makeContentHash(`${noteContent}\n${rawTranscript}`), {+ transcript: formattedTranscript,+ });+ runAction(action, input, makeContentHash(`${noteContent}\n${rawTranscript}`), {isCloudMode,modelId: effectiveModelId,isMeetingNote,knownPeople,- // The pieces, so a recording too long for a local model can be split- // along the transcript rather than through the joined string.- material: {- notes: hasNotes ? noteContent : "",- meetingContext,- transcript: formattedTranscript,- },+ fromSummary,+ material,allowTitleGeneration: isRegenerableNoteTitle(editorNote.title,[t("notes.list.untitledNote"), t("notes.list.newNote"), t("notes.sidebar.newNote")],@@ -713,10 +701,6 @@ export default function PersonalNotesView({),});};- const generateSummary = () => {- const action = actions.find((a) => a.translation_key === DETAILED_NOTES_KEY);- if (action) void runNoteAction(action);- };if (!isOnboardingComplete) {return (@@ -739,7 +723,7 @@ export default function PersonalNotesView({<div className="w-52 shrink-0 border-e border-border dark:border-white/10 flex flex-col h-full"><div className="px-2 pt-2 pb-1 shrink-0 space-y-0.5"><button- onClick={() => setShowActionManager(true)}+ onClick={() => setManagerKind("template")}className={cn("flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-xs","text-foreground/85 hover:text-foreground hover:bg-foreground/5",@@ -748,7 +732,7 @@ export default function PersonalNotesView({)}><Sparkles size={14} className="shrink-0" />- {t("notes.sidebar.actions")}+ {t("notes.sidebar.templatesAndActions")}</button></div>@@ -804,21 +788,15 @@ export default function PersonalNotesView({actionName={actionName}actionProgress={actionProgress}onCancelAction={cancelAction}- onGenerateSummary={generateSummary}- actionPicker={- <ActionPicker- onRunAction={runNoteAction}- onManageActions={() => setShowActionManager(true)}- disabled={- (!editorNote?.content?.trim() &&- !hasLiveTranscript &&- !activeNoteRawTranscript) ||- actionProcessingState === "processing"- }- />- }+ onRunNoteAction={runNoteAction}+ onManageActions={setManagerKind}+ />+ <ActionManagerDialog+ open={managerKind !== null}+ onOpenChange={(open) => !open && setManagerKind(null)}+ initialKind={managerKind ?? "template"}+ onInferOutput={(prompt) => inferActionOutput(prompt, effectiveModelId, isCloudMode)}/>- <ActionManagerDialog open={showActionManager} onOpenChange={setShowActionManager} /></>) : activeContext && overviewSpace ? (<ContainerOverviewdiff --git a/src/components/notes/TemplatePicker.tsx b/src/components/notes/TemplatePicker.tsxnew file mode 100644index 000000000..39d062665--- /dev/null+++ b/src/components/notes/TemplatePicker.tsx@@ -0,0 +1,78 @@+import { useTranslation } from "react-i18next";+import { Check, RefreshCw, Settings2 } from "../icons";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "../ui/dropdown-menu";+import { cn } from "../lib/utils";+import { getActionDescription, getActionName } from "../../stores/actionStore";+import type { ActionItem } from "../../types/electron";++interface TemplatePickerProps {+ templates: ActionItem[];+ /** The template that wrote the note's summary, or the default. */+ current: ActionItem;+ onRun: (template: ActionItem) => void;+ onManage: () => void;+ disabled?: boolean;+ /** The trigger, rendered as is. */+ children: React.ReactNode;+}++/** The templates that write a note's AI summary, opened from the AI Summary tab. */+export default function TemplatePicker({+ templates,+ current,+ onRun,+ onManage,+ disabled,+ children,+}: TemplatePickerProps) {+ const { t } = useTranslation();++ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild disabled={disabled}>+ {children}+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" sideOffset={6} className="min-w-56">+ <DropdownMenuLabel className="px-2.5 py-1 text-[11px] font-medium text-muted-foreground/70">+ {t("notes.templates.tab")}+ </DropdownMenuLabel>+ {templates.map((template) => {+ const isCurrent = template.id === current.id;+ return (+ <DropdownMenuItem+ key={template.id}+ onClick={() => onRun(template)}+ className="gap-2.5 rounded-md px-2.5 py-1.5 text-xs"+ >+ <div className="min-w-0 flex-1">+ <div className="truncate font-medium">{getActionName(template, t)}</div>+ {template.description && (+ <div className="truncate text-xs text-muted-foreground/70">+ {getActionDescription(template, t)}+ </div>+ )}+ </div>+ {isCurrent && <RefreshCw size={12} className="shrink-0 text-foreground/50" />}+ <Check size={12} className={cn("shrink-0 text-accent", !isCurrent && "invisible")} />+ </DropdownMenuItem>+ );+ })}+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={onManage}+ className="gap-2.5 rounded-md px-2.5 py-1.5 text-xs text-muted-foreground/70"+ >+ <Settings2 size={12} />+ {t("notes.templates.manage")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/src/components/notes/actionIcons.ts b/src/components/notes/actionIcons.tsnew file mode 100644index 000000000..da71ae644--- /dev/null+++ b/src/components/notes/actionIcons.ts@@ -0,0 +1,20 @@+import {+ ClipboardCheck,+ FileText,+ Mail,+ MessageSquareText,+ Send,+ Sparkles,+ type IconComponent,+} from "../icons";++const ACTION_ICONS: Record<string, IconComponent> = {+ mail: Mail,+ "clipboard-check": ClipboardCheck,+ "file-text": FileText,+ send: Send,+ sparkles: Sparkles,+};++export const getActionIcon = (action: { icon: string }): IconComponent =>+ ACTION_ICONS[action.icon] ?? MessageSquareText;diff --git a/src/components/notes/overview/OverviewAskSection.tsx b/src/components/notes/overview/OverviewAskSection.tsxindex e16e57599..806bf6773 100644--- a/src/components/notes/overview/OverviewAskSection.tsx+++ b/src/components/notes/overview/OverviewAskSection.tsx@@ -7,6 +7,7 @@ import { observeChatComposerInset } from "../../chat/composerLayout";import type { Message, AgentState } from "../../chat/types";import type { ContainerConversationItem } from "../../../hooks/useContainerChat";import { ConversationPicker } from "../ConversationPicker";+import { ASK_PILL_CLASS } from "../shared";const PROMPT_CHIP_KEYS = ["notes.overview.ask.chips.catchUp",@@ -85,7 +86,7 @@ export function OverviewAskSection({onTextSubmit(t(key));}}disabled={agentState !== "idle"}- className="inline-flex shrink-0 items-center gap-1.5 px-2.5 h-7 whitespace-nowrap rounded-full border border-border/70 bg-card shadow-sm dark:border-white/10 text-[11px] text-foreground/55 hover:text-foreground/80 hover:border-border/70 hover:bg-surface-3 disabled:text-foreground/30 disabled:pointer-events-none transition-colors duration-150 focus:outline-none focus-visible:ring-1 focus-visible:ring-ring/30"+ className={ASK_PILL_CLASS}><Sparkles size={10} className="text-foreground/45 shrink-0" />{t(key)}diff --git a/src/components/notes/shared.ts b/src/components/notes/shared.tsindex a559a027c..ad4636b6d 100644--- a/src/components/notes/shared.ts+++ b/src/components/notes/shared.ts@@ -113,6 +113,14 @@ export const notesTextareaClass = cn("focus:border-primary/30 transition-colors duration-150");+/** Rounded suggestion pill above an ask box: the folder overview's prompts, a note's actions. */+export const ASK_PILL_CLASS = cn(+ "inline-flex h-7 shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full px-2.5 text-[11px]",+ "border border-border/70 bg-card text-foreground/55 shadow-sm dark:border-white/10",+ "hover:bg-surface-3 hover:text-foreground/80 disabled:pointer-events-none disabled:text-foreground/30",+ "transition-colors duration-150 focus:outline-none focus-visible:ring-1 focus-visible:ring-ring/30"+);+/** Neutral capsule for note header facts (date + attendees, folder, space). */export const NOTE_META_CHIP_CLASS = cn("inline-flex h-[26px] items-center gap-2 rounded-full bg-surface-3 px-2.5 text-xs font-medium text-foreground/70",diff --git a/src/helpers/builtinActions.js b/src/helpers/builtinActions.jsindex bd60c9ae4..f531b1866 100644--- a/src/helpers/builtinActions.js+++ b/src/helpers/builtinActions.js@@ -1,13 +1,25 @@-// Built-in note actions. The database seeds any that are missing on startup and-// only rewrites a row whose prompt still equals a previous default, so a user's-// edited prompt is never touched. Generate Notes uses the generic-// system-prompt wrapper; the newer built-ins are complete-// instructions and are sent standalone (see STANDALONE_PROMPT_KEYS).+// Built-in note templates and actions. The database seeds any that are missing+// on startup and only rewrites a row whose prompt still equals a previous+// default, so a user's edited prompt is never touched. A template writes the AI+// summary: Generate Notes wraps its prompt in the generic system prompt, and+// Detailed Notes is compiled from sections (see templatePrompts.js). An action+// either edits the summary or answers in the note chat.export const GENERATE_NOTES_KEY = "notes.actions.builtin.generateNotes";export const DETAILED_NOTES_KEY = "notes.actions.builtin.detailedNotes";export const FOLLOW_UP_EMAIL_KEY = "notes.actions.builtin.followUpEmail";+// Caps on a template's or action's fields, enforced when a row is saved. Keep+// them in step with the API's schemas once custom rows sync.+export const NOTE_ACTION_LIMITS = {+ name: 200,+ description: 1000,+ prompt: 20000,+ sections: 20,+ heading: 200,+ instruction: 2000,+};+const GENERATE_NOTES_PROMPT_1_10_1 ="Transform the provided content into clean, well-structured notes in markdown. Preserve the user's intent and all substantive information. Remove filler, small talk, false starts, and redundant content. For personal notes, improve grammar and structure for readability. For meeting transcripts, extract key discussion points, decisions, action items, and follow-ups.";@@ -113,15 +125,184 @@ Unresolved questions, dependencies, and requested follow-ups.Return only the finished Markdown notes.`;+// Shipped through 1.10.2: a note with nothing to summarize got a sentence saying+// so saved as its summary.+const NON_SUBSTANTIVE_NOTES_INSTRUCTIONS_1_10_2 = `For material with no substantive discussion or notes (for example, only greetings, filler, or recording checks), return one brief factual sentence describing what was captured. If nothing meaningful can be summarized, say "No substantive content was captured." in the requested output language. This rule overrides the section structure and bullet counts above: do not return an empty response or invent topics, decisions, or action items. Consider both the transcript and any manual notes before applying this rule.`;++/** A note run's reply when the material has nothing to summarize: the runner saves nothing and says so. */+export const NOTHING_TO_SUMMARIZE = "NOTHING_TO_SUMMARIZE";+// Omitting every unsupported section can otherwise produce a blank completion.-const NON_SUBSTANTIVE_NOTES_INSTRUCTIONS = `For material with no substantive discussion or notes (for example, only greetings, filler, or recording checks), return one brief factual sentence describing what was captured. If nothing meaningful can be summarized, say "No substantive content was captured." in the requested output language. This rule overrides the section structure and bullet counts above: do not return an empty response or invent topics, decisions, or action items. Consider both the transcript and any manual notes before applying this rule.`;+const NON_SUBSTANTIVE_NOTES_INSTRUCTIONS = `For material with no substantive discussion or notes (for example, only greetings, filler, or recording checks), reply with exactly ${NOTHING_TO_SUMMARIZE} and nothing else. This rule overrides the section structure and bullet counts above: do not return an empty response or invent topics, decisions, or action items. Consider both the transcript and any manual notes before applying this rule.`;+const GENERATE_NOTES_PROMPT_1_10_2 = `${GENERATE_NOTES_PROMPT_1_10_1}\n\n${NON_SUBSTANTIVE_NOTES_INSTRUCTIONS_1_10_2}`;const GENERATE_NOTES_PROMPT = `${GENERATE_NOTES_PROMPT_1_10_1}\n\n${NON_SUBSTANTIVE_NOTES_INSTRUCTIONS}`;-const DETAILED_NOTES_PROMPT = `${DETAILED_NOTES_PROMPT_1_10_1}\n\n${NON_SUBSTANTIVE_NOTES_INSTRUCTIONS}`;+// The last flat Detailed Notes prompt; a row still holding it moves to sections.+const DETAILED_NOTES_PROMPT_1_10_2 = `${DETAILED_NOTES_PROMPT_1_10_1}\n\n${NON_SUBSTANTIVE_NOTES_INSTRUCTIONS_1_10_2}`;-const FOLLOW_UP_EMAIL_PROMPT = `You are an expert at writing follow-up emails after meetings. Draft the follow-up email the user ("You") would send to the other participants, based only on the provided meeting material: meeting context, the user's manual notes, and the transcript.+// A sectioned template is compiled from these rules, the template's own context,+// the format line, its sections, and the footer. Detailed Notes' sections compile+// back to DETAILED_NOTES_PROMPT_1_10_2 exactly, but for its closing rule (pinned by+// templatePrompts.test.js).+export const SECTIONED_NOTES_INSTRUCTIONS = `Convert the provided material into accurate, comprehensive, easy-to-scan notes in Markdown. Priorities, in order: factual accuracy, preservation of specifics, complete coverage of substantive topics, clear decisions and action items, concise presentation.RULES:+- Use only information supported by the material. Never invent facts, decisions, owners, deadlines, or names.+- Keep the exact names of people, clients, companies, projects, products, tools, and acronyms, and the exact numbers, dates, deadlines, and document names. Never replace a named entity with a generic noun such as "the client" or "the project". If a name is unclear, write "[name unclear]" rather than guessing.+- Speech-to-text misspells names. When the transcript's spelling is an obvious variant of a name in the Meeting Context, the participants' email addresses, the manual notes, or the custom dictionary, use that spelling instead.+- Distinguish what was discussed, proposed, or requested from what was actually decided.+- Treat the user's manual notes as a signal of what matters most, reconciled against the transcript.+- Consolidate repeated discussion into one point. Drop greetings, filler, and false starts. Give longer meetings proportionally more detail.+- If there is no transcript, structure the user's own notes and skip the meeting-specific sections.`;++export const SECTIONED_NOTES_FORMAT = `FORMAT:+- No title, date, attendee list, preamble, table, or horizontal rule. Omit any section with nothing to say.`;++export const SECTIONED_NOTES_FOOTER = `Return only the finished Markdown notes.\n\n${NON_SUBSTANTIVE_NOTES_INSTRUCTIONS}`;++// Action items must end in "— Owner" so the editor can turn owners into+// mention chips (see tagActionItemOwners).+const ACTION_ITEMS_SECTION = {+ heading: "Action Items",+ instruction:+ 'Only actions someone committed to or was asked to do; never turn a discussion topic into an action item. One checkbox per item in the form `- [ ] Action — Owner`. Put a stated due date inside the action text, for example `- [ ] Send the revised proposal by Friday — Alice`. The owner is the person the transcript shows taking the action on or being asked to, not whoever raised the topic; name them whenever the transcript shows it. Use "You" or "Them" only when no name is available. When the transcript shows no owner, end the line after the action; never write a placeholder such as "Owner not specified".',+};++const DETAILED_NOTES_SECTIONS = [+ {+ heading: "Summary",+ instruction: "3–5 bullets: purpose, key subjects, major outcomes, immediate next steps.",+ },+ {+ heading: "Discussion",+ instruction:+ "Descriptive topic subheadings named after the actual client, project, or initiative, with enough context that someone who missed the meeting understands what happened and why.",+ },+ {+ heading: "Decisions",+ instruction: "Only decisions that were explicitly made or clearly agreed.",+ },+ ACTION_ITEMS_SECTION,+ {+ heading: "Open Questions",+ instruction: "Unresolved questions, dependencies, and requested follow-ups.",+ },+];++const ONE_ON_ONE_CONTEXT =+ "A one-on-one, usually between a manager and someone on their team. Keep each person's updates, concerns, and feedback attributed to them, and leave out personal matters unless they bear on the work.";++const ONE_ON_ONE_SECTIONS = [+ {+ heading: "Summary",+ instruction: "2–3 bullets: what the conversation covered and where it landed.",+ },+ {+ heading: "Updates",+ instruction:+ "Progress, wins, and status changes each person shared, grouped by project or topic.",+ },+ {+ heading: "Challenges and Feedback",+ instruction:+ "Blockers, concerns, and feedback given in either direction, with the context behind each.",+ },+ {+ heading: "Growth and Goals",+ instruction: "Career, development, or goal discussion, and any support that was offered.",+ },+ ACTION_ITEMS_SECTION,+];++const STAND_UP_CONTEXT =+ "A short team stand-up. Keep every update to one or two bullets and skip small talk entirely.";++const STAND_UP_SECTIONS = [+ {+ heading: "Summary",+ instruction: "1–2 bullets on the team's overall progress and anything that needs attention.",+ },+ {+ heading: "Updates by Person",+ instruction:+ "One subheading per person, named by their label, with what they finished and what they are doing next.",+ },+ {+ heading: "Blockers",+ instruction: "Each blocker, who it affects, and who offered to help.",+ },+ ACTION_ITEMS_SECTION,+];++const SALES_CALL_CONTEXT =+ "A sales conversation with a prospect or customer. Write it for the seller who has to move the deal forward, and state every number, price, and date exactly.";++const SALES_CALL_SECTIONS = [+ {+ heading: "Summary",+ instruction:+ "3–5 bullets: who the prospect is, what they want, where the deal stands, and the agreed next step.",+ },+ {+ heading: "Customer Context",+ instruction:+ "The prospect's company, the attendees and their roles when stated, and their current situation and tools.",+ },+ {+ heading: "Needs and Pain Points",+ instruction: "What they are trying to solve and why it matters to them now.",+ },+ {+ heading: "Objections",+ instruction: "Each objection or concern raised, and how it was answered if it was.",+ },+ {+ heading: "Budget, Pricing, and Timeline",+ instruction: "Budget, pricing discussed, and deadlines or buying timeline.",+ },+ {+ heading: "Decision Process",+ instruction:+ "Who decides, their evaluation criteria, competitors mentioned, and approvals still needed.",+ },+ ACTION_ITEMS_SECTION,+];++const USER_INTERVIEW_CONTEXT =+ "A user research interview. Keep what the participant said and did separate from what the interviewer suggested, and never present the interviewer's ideas as findings.";++const USER_INTERVIEW_SECTIONS = [+ {+ heading: "Summary",+ instruction: "3–5 bullets: who the participant is and the most important things learned.",+ },+ {+ heading: "Participant Background",+ instruction: "Their role, context, and experience relevant to the interview.",+ },+ {+ heading: "Current Workflow",+ instruction: "How they do the job today, including tools and workarounds.",+ },+ {+ heading: "Pain Points",+ instruction: "Problems they described, how often they hit them, and what they cost them.",+ },+ {+ heading: "Reactions and Feedback",+ instruction: "Their reactions to any ideas, designs, or features shown, including hesitations.",+ },+ {+ heading: "Notable Quotes",+ instruction: "Short verbatim quotes that capture their perspective, attributed by label.",+ },+ {+ heading: "Follow-ups",+ instruction: "Open questions to explore next and anything promised to the participant.",+ },+];++const FOLLOW_UP_EMAIL_BODY = `RULES:- Use only information supported by the material. Do not invent facts, decisions, owners, deadlines, or names.- Preserve the exact names of people, clients, projects, products, numbers, dates, and documents.- Distinguish what was decided from what was proposed or still open.@@ -149,6 +330,21 @@ Open questionsOmit any section that has no supported content. Return only the email.`;+// Shipped in 1.10.1 and 1.10.2, when the email always read the transcript.+const FOLLOW_UP_EMAIL_PROMPT_1_10_2 = `You are an expert at writing follow-up emails after meetings. Draft the follow-up email the user ("You") would send to the other participants, based only on the provided meeting material: meeting context, the user's manual notes, and the transcript.\n\n${FOLLOW_UP_EMAIL_BODY}`;++const FOLLOW_UP_EMAIL_PROMPT = `You are an expert at writing follow-up emails after meetings. Draft the follow-up email the user ("You") would send to the other participants, based only on the meeting material you are working from.\n\n${FOLLOW_UP_EMAIL_BODY}`;++const MAKE_TODOS_PROMPT = `List the to-dos in this note: every action someone committed to or was asked to do, based only on what the note supports. One checkbox per item in the form \`- [ ] Action — Owner\`, with any stated due date inside the action text. Leave the owner out when the note does not show one. If there are no to-dos, say so in one sentence.`;++const CREATE_OUTLINE_PROMPT = `Outline this note, based only on what it says. Use nested Markdown bullets: one top-level bullet per main topic in the order it came up, with its key points, decisions, and numbers beneath it. Return only the outline.`;++const SLACK_UPDATE_PROMPT = `Write a short Slack message I can post to my team about this meeting: one line on what it was about, then 3–5 bullets with the outcomes, decisions, and who is doing what next. Use Slack formatting (bold with *asterisks*, no Markdown headings), keep it under 120 words, and use only what the note supports. Return only the message.`;++const SHORTEN_PROMPT = `Make it about half as long. Keep every decision, number, date, name, and action item; cut repetition, background, and detail that would not change what anyone does next.`;++const ADD_TLDR_PROMPT = `Add a "## TL;DR" section at the very top: two or three sentences on what the meeting decided and what happens next. Leave the rest of the summary exactly as it is.`;+// System-prompt wrappers the note action store puts around a built-in or// custom action prompt. They live here, with the action prompts, so the live// canary can send the exact request the app sends.@@ -184,8 +380,8 @@ CONTENT RULES:Instructions: `;-// Standalone built-in prompts are complete instructions, so they only get told-// how the material is laid out instead of being wrapped in the generic prompts.+// Sectioned and standalone templates are complete instructions, so they only get+// told how the material is laid out instead of being wrapped in the generic prompts.export const MEETING_INPUT_PREAMBLE = `The material is laid out as follows. Transcript lines are prefixed with the speaker's label: a real name when known, otherwise "You" (the note owner), "Them", or "Speaker N". A "## Meeting Context" block may identify the note owner and the invited participants; it is reference material, never something to reproduce. Manual notes the user took may precede the transcript.`;@@ -193,6 +389,31 @@ export const NOTE_INPUT_PREAMBLE = `The material is the user's own notes, possib`;+// A summary action rewrites the summary the note already has; the rest of the+// input is only there to keep the rewrite accurate.+export const SUMMARY_ACTION_SYSTEM_PROMPT = `You revise an existing AI summary of a note. The input starts with the current summary under "## Current Summary". The user's own notes under "## My Notes" and a "## Meeting Context" block may follow; they are reference material for accuracy, never something to reproduce.++Apply the instructions below to the current summary and return the complete revised summary in Markdown, with no preamble and no code fences. Unless the instructions say otherwise, keep its facts, names, numbers, headings, and \`- [ ] Action — Owner\` items, and add nothing the summary or the reference material does not support.++Instructions: `;++// With no summary to edit, a summary action writes one from the material first.+export const SUMMARY_ACTION_FROM_MATERIAL_PROMPT = `The note has no AI summary yet. Write concise, accurate notes of the material in Markdown (no title or preamble, and only what the material supports, with action items as \`- [ ] Action — Owner\`), apply the instructions below to them, and return the result. It becomes the note's AI summary. If the material has no substantive discussion or notes (for example, only greetings, filler, or recording checks), reply with exactly ${NOTHING_TO_SUMMARIZE} and nothing else.++Instructions: `;++// A chat action is sent as the user's turn in the note chat, whose system prompt+// already carries the whole note. It works from the AI summary when there is one.+// The note chat can offer connector tools; a one-click action answers in the chat.+const CHAT_ACTION_ANSWER_RULE =+ "Write your answer here in the chat as text. Don't use a tool to draft, send or post it, unless the instructions explicitly ask you to send, post or file something. Answer in the language the note is written in, not the language of these instructions.";+export const CHAT_ACTION_ON_SUMMARY_PREAMBLE = `Work from the AI summary of the note I'm viewing (it's in your context), and use its transcript only if the instructions below ask for it. ${CHAT_ACTION_ANSWER_RULE} Follow these instructions:++`;+export const CHAT_ACTION_ON_MATERIAL_PREAMBLE = `The note I'm viewing has no AI summary yet, so work from its transcript and notes (they're in your context). ${CHAT_ACTION_ANSWER_RULE} Follow these instructions:++`;+/*** Output budget for a formatted note.*@@ -207,37 +428,168 @@ export const NOTE_INPUT_PREAMBLE = `The material is the user's own notes, possib*/export const NOTE_OUTPUT_MAX_TOKENS = 4096;+// Built-ins added once templates had sections; none has an older default to upgrade.+const builtinTemplate = ({ key, name, description, prompt, sections, sortOrder }) => ({+ translationKey: `notes.actions.builtin.${key}`,+ kind: "template",+ name,+ description,+ prompt,+ sections,+ output: null,+ previousPrompts: [],+ icon: "sparkles",+ sortOrder,+});++const builtinAction = ({+ key,+ name,+ description,+ prompt,+ output,+ icon = "sparkles",+ sortOrder,+}) => ({+ translationKey: `notes.actions.builtin.${key}`,+ kind: "action",+ name,+ description,+ prompt,+ sections: null,+ output,+ previousPrompts: [],+ icon,+ sortOrder,+});++// previousPrompts only upgrades a row that is still a flat prompt; a later change+// to a built-in's default sections needs its own history.export const BUILTIN_ACTIONS = [+ {+ translationKey: DETAILED_NOTES_KEY,+ kind: "template",+ // The default template, and the prompt AI summaries always used.+ name: "AI Summary",+ description: "Accurate, comprehensive meeting notes with decisions and action items",+ prompt: "",+ sections: DETAILED_NOTES_SECTIONS,+ output: null,+ previousPrompts: [+ DETAILED_NOTES_PROMPT_1_10_0,+ DETAILED_NOTES_PROMPT_1_10_1,+ DETAILED_NOTES_PROMPT_1_10_2,+ ],+ icon: "sparkles",+ sortOrder: 0,+ },{translationKey: GENERATE_NOTES_KEY,+ kind: "template",name: "Generate Notes",description: "Clean up, structure, and enhance your notes",prompt: GENERATE_NOTES_PROMPT,+ sections: null,+ output: null,// A pre-release build briefly shipped the detailed prompt under this key.- previousPrompts: [DETAILED_NOTES_PROMPT_1_10_0, GENERATE_NOTES_PROMPT_1_10_1],- icon: "sparkles",- sortOrder: 0,- },- {- translationKey: DETAILED_NOTES_KEY,- name: "Detailed Notes",- description: "Accurate, comprehensive meeting notes with decisions and action items",- prompt: DETAILED_NOTES_PROMPT,- previousPrompts: [DETAILED_NOTES_PROMPT_1_10_0, DETAILED_NOTES_PROMPT_1_10_1],+ previousPrompts: [+ DETAILED_NOTES_PROMPT_1_10_0,+ GENERATE_NOTES_PROMPT_1_10_1,+ GENERATE_NOTES_PROMPT_1_10_2,+ ],icon: "sparkles",sortOrder: 1,},{translationKey: FOLLOW_UP_EMAIL_KEY,+ kind: "action",name: "Follow-up email",description: "Draft a follow-up email from your notes and transcript",prompt: FOLLOW_UP_EMAIL_PROMPT,- previousPrompts: [],+ sections: null,+ output: "chat",+ previousPrompts: [FOLLOW_UP_EMAIL_PROMPT_1_10_2],icon: "mail",sortOrder: 2,},+ builtinAction({+ key: "makeTodos",+ name: "Make to-dos",+ description: "List every to-do and its owner in the chat",+ prompt: MAKE_TODOS_PROMPT,+ output: "chat",+ icon: "clipboard-check",+ sortOrder: 3,+ }),+ builtinAction({+ key: "shorten",+ name: "Shorten",+ description: "Make the summary about half as long",+ prompt: SHORTEN_PROMPT,+ output: "summary",+ sortOrder: 4,+ }),+ builtinAction({+ key: "addTldr",+ name: "Add TL;DR",+ description: "Put a two- or three-sentence TL;DR at the top of the summary",+ prompt: ADD_TLDR_PROMPT,+ output: "summary",+ sortOrder: 5,+ }),+ builtinAction({+ key: "createOutline",+ name: "Create outline",+ description: "Outline the note's topics in the chat",+ prompt: CREATE_OUTLINE_PROMPT,+ output: "chat",+ icon: "file-text",+ sortOrder: 6,+ }),+ builtinAction({+ key: "slackUpdate",+ name: "Slack update",+ description: "Write a short team update to post in Slack",+ prompt: SLACK_UPDATE_PROMPT,+ output: "chat",+ icon: "send",+ sortOrder: 7,+ }),+ builtinTemplate({+ key: "oneOnOne",+ name: "1:1",+ description: "Updates, feedback, growth, and next steps from a one-on-one",+ prompt: ONE_ON_ONE_CONTEXT,+ sections: ONE_ON_ONE_SECTIONS,+ sortOrder: 8,+ }),+ builtinTemplate({+ key: "standUp",+ name: "Stand-up",+ description: "Each person's progress, plans, and blockers",+ prompt: STAND_UP_CONTEXT,+ sections: STAND_UP_SECTIONS,+ sortOrder: 9,+ }),+ builtinTemplate({+ key: "salesCall",+ name: "Sales call",+ description: "Needs, objections, budget, and the decision process",+ prompt: SALES_CALL_CONTEXT,+ sections: SALES_CALL_SECTIONS,+ sortOrder: 10,+ }),+ builtinTemplate({+ key: "userInterview",+ name: "User interview",+ description: "Workflow, pain points, reactions, and quotes from a participant",+ prompt: USER_INTERVIEW_CONTEXT,+ sections: USER_INTERVIEW_SECTIONS,+ sortOrder: 11,+ }),];-// Built-ins whose prompt is a complete instruction set and must not be wrapped-// in the generic system prompts.-export const STANDALONE_PROMPT_KEYS = new Set([DETAILED_NOTES_KEY, FOLLOW_UP_EMAIL_KEY]);+// A flat Detailed Notes prompt (one the user edited before templates had+// sections) is a complete instruction set and must not be wrapped in the+// generic system prompts.+export const STANDALONE_PROMPT_KEYS = new Set([DETAILED_NOTES_KEY]);diff --git a/src/helpers/cloudSyncGuards.js b/src/helpers/cloudSyncGuards.jsindex ecdb3d895..cebbd27f7 100644--- a/src/helpers/cloudSyncGuards.js+++ b/src/helpers/cloudSyncGuards.js@@ -31,6 +31,7 @@ export function buildNoteUpdatePayload(note, cloudFolderId) {content: note.content,enhanced_content: note.enhanced_content,enhancement_prompt: note.enhancement_prompt,+ enhancement_template_id: note.enhancement_template_id,enhanced_at_content_hash: note.enhanced_at_content_hash,note_type: note.note_type,source_file: note.source_file,diff --git a/src/helpers/database.js b/src/helpers/database.jsindex e3db314f0..21080bbdd 100644--- a/src/helpers/database.js+++ b/src/helpers/database.js@@ -11,7 +11,13 @@ const { parseEventTime } = require("./calendarAvailability");// keeps the cloud created_at but lets timestamp default to the local pull, so// a naive value must never outrank created_at when dating a historical row.const { hasExplicitTimeZone, parseDbTimestamp, toDbTimestamp } = require("./dbTimestamp");-const { BUILTIN_ACTIONS, GENERATE_NOTES_KEY } = require("./builtinActions");+const {+ BUILTIN_ACTIONS,+ DETAILED_NOTES_KEY,+ GENERATE_NOTES_KEY,+ NOTE_ACTION_LIMITS,+} = require("./builtinActions");+const { normalizeSections } = require("./templatePrompts");const {ANALYTICS_COUNTER_VERSION,ANALYTICS_HISTORY_BACKFILL_VERSION,@@ -36,6 +42,7 @@ const NOTE_CREATE_ACK_FIELDS = ["content","enhanced_content","enhancement_prompt",+ "enhancement_template_id","enhanced_at_content_hash","note_type","source_file",@@ -68,6 +75,54 @@ const FOLDER_ACK_FIELDS = ["left_team",];+// Validates and normalizes the editable fields of a note template or action.+function resolveActionFields(kind, fields) {+ const name = (fields.name || "").trim();+ const description = (fields.description || "").trim();+ const prompt = (fields.prompt || "").trim();+ const sections = kind === "template" ? normalizeSections(fields.sections) : [];+ const output = kind === "action" ? fields.output || "chat" : null;+ if (!name) return { error: "Name is required" };+ if (kind === "action" && !prompt) return { error: "Action prompt is required" };+ if (kind === "template" && !prompt && sections.length === 0) {+ return { error: "A template needs instructions or a section" };+ }+ if (output !== null && output !== "summary" && output !== "chat") {+ return { error: "Unknown action output" };+ }+ const limits = NOTE_ACTION_LIMITS;+ if (+ name.length > limits.name ||+ description.length > limits.description ||+ prompt.length > limits.prompt ||+ sections.length > limits.sections ||+ sections.some(+ (section) =>+ section.heading.length > limits.heading || section.instruction.length > limits.instruction+ )+ ) {+ return { error: "Too long" };+ }+ return {+ name,+ description,+ prompt,+ sections: sections.length > 0 ? JSON.stringify(sections) : null,+ output,+ };+}++function toActionItem(row) {+ if (!row) return null;+ let sections = null;+ try {+ sections = row.sections ? JSON.parse(row.sections) : null;+ } catch {+ sections = null;+ }+ return { ...row, sections };+}+function rowMatchesSnapshot(row, snapshot, fields) {return fields.every((field) => {const expected = snapshot[field] === undefined ? null : snapshot[field];@@ -340,6 +395,11 @@ class DatabaseManager {} catch (err) {if (!err.message.includes("duplicate column")) throw err;}+ try {+ this.db.exec("ALTER TABLE notes ADD COLUMN enhancement_template_id TEXT");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }try {this.db.exec("ALTER TABLE notes ADD COLUMN cloud_id TEXT");} catch (err) {@@ -468,6 +528,20 @@ class DatabaseManager {} catch (err) {if (!err.message.includes("duplicate column")) throw err;}+ // Every row before these columns rewrote the AI summary from the note's+ // material, which is what a template does, so 'template' is the default.+ for (const column of [+ "client_id TEXT",+ "kind TEXT NOT NULL DEFAULT 'template'",+ "sections TEXT",+ "output TEXT",+ ]) {+ try {+ this.db.exec(`ALTER TABLE actions ADD COLUMN ${column}`);+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }+ }this.db.exec(`CREATE TABLE IF NOT EXISTS agent_conversations (@@ -560,27 +634,49 @@ class DatabaseManager {"CREATE INDEX IF NOT EXISTS idx_agent_conversations_container ON agent_conversations(space_id, folder_id)");+ const builtinKeys = BUILTIN_ACTIONS.map((action) => action.translationKey);+ // A built-in's client id is its key. An older build renames built-in keys it+ // doesn't know (below), so after a downgrade and upgrade the key comes back+ // from the client id instead of the row being seeded a second time.+ this.db+ .prepare(+ `UPDATE actions SET translation_key = client_id WHERE is_builtin = 1 AND client_id IN (${builtinKeys.map(() => "?").join(", ")}) AND translation_key IS NOT client_id`+ )+ .run(...builtinKeys);+// Pre-2026 installs carry one built-in row under an older key: rename it to// Generate Notes so the loop below recognizes and upgrades it.- const builtinKeys = BUILTIN_ACTIONS.map((action) => action.translationKey);this.db.prepare(`UPDATE actions SET translation_key = ? WHERE is_builtin = 1 AND (translation_key IS NULL OR translation_key NOT IN (${builtinKeys.map(() => "?").join(", ")}))`).run(GENERATE_NOTES_KEY, ...builtinKeys);- // Built-in actions: insert any that are missing, and roll a new default prompt- // out to rows whose prompt is still a previous default (never a user edit).+ // Detailed Notes became the default "AI Summary"; a name the user chose stays.+ this.db+ .prepare(+ "UPDATE actions SET name = 'AI Summary' WHERE is_builtin = 1 AND translation_key = ? AND name = 'Detailed Notes'"+ )+ .run(DETAILED_NOTES_KEY);++ // Built-ins: insert any that are missing, and roll a new default out to rows+ // that are still a previous flat default (never a user edit). A built-in's+ // kind is fixed, so it is settled whatever the prompt; its output is only+ // filled in, since the user may point an action at the summary instead.const selectBuiltin = this.db.prepare(- "SELECT id, prompt FROM actions WHERE is_builtin = 1 AND translation_key = ?"+ "SELECT id, prompt, sections FROM actions WHERE is_builtin = 1 AND translation_key = ?");const insertBuiltin = this.db.prepare(- "INSERT INTO actions (name, description, prompt, icon, is_builtin, sort_order, translation_key) VALUES (?, ?, ?, ?, 1, ?, ?)"+ "INSERT INTO actions (name, description, prompt, icon, is_builtin, sort_order, translation_key, client_id, kind, sections, output) VALUES (?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?)");const upgradeBuiltin = this.db.prepare(- "UPDATE actions SET name = ?, description = ?, prompt = ? WHERE id = ?"+ "UPDATE actions SET description = ?, prompt = ?, sections = ? WHERE id = ?"+ );+ const settleBuiltin = this.db.prepare(+ "UPDATE actions SET client_id = ?, kind = ?, sort_order = ?, output = COALESCE(output, ?) WHERE id = ?");for (const action of BUILTIN_ACTIONS) {+ const sections = action.sections ? JSON.stringify(action.sections) : null;const existing = selectBuiltin.get(action.translationKey);if (!existing) {insertBuiltin.run(@@ -589,13 +685,35 @@ class DatabaseManager {action.prompt,action.icon,action.sortOrder,- action.translationKey+ action.translationKey,+ action.translationKey,+ action.kind,+ sections,+ action.output);- } else if (action.previousPrompts.includes(existing.prompt)) {- upgradeBuiltin.run(action.name, action.description, action.prompt, existing.id);+ continue;+ }+ if (existing.sections === null && action.previousPrompts.includes(existing.prompt)) {+ upgradeBuiltin.run(action.description, action.prompt, sections, existing.id);}+ settleBuiltin.run(+ action.translationKey,+ action.kind,+ action.sortOrder,+ action.output,+ existing.id+ );}+ const actionsWithoutClientId = this.db+ .prepare("SELECT id FROM actions WHERE client_id IS NULL")+ .all();+ const setActionClientId = this.db.prepare("UPDATE actions SET client_id = ? WHERE id = ?");+ for (const row of actionsWithoutClientId) setActionClientId.run(randomUUID(), row.id);+ this.db.exec(+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_actions_client_id ON actions(client_id) WHERE client_id IS NOT NULL"+ );+this.db.exec(`CREATE TABLE IF NOT EXISTS google_calendar_tokens (id INTEGER PRIMARY KEY AUTOINCREMENT,@@ -3185,6 +3303,7 @@ class DatabaseManager {"content","enhanced_content","enhancement_prompt",+ "enhancement_template_id","enhanced_at_content_hash","folder_id","space_id",@@ -4136,7 +4255,10 @@ class DatabaseManager {getActions() {try {if (!this.db) throw new Error("Database not initialized");- return this.db.prepare("SELECT * FROM actions ORDER BY sort_order ASC, created_at ASC").all();+ return this.db+ .prepare("SELECT * FROM actions ORDER BY sort_order ASC, created_at ASC")+ .all()+ .map(toActionItem);} catch (error) {debugLogger.error("Error getting actions", { error: error.message }, "notes");throw error;@@ -4146,30 +4268,47 @@ class DatabaseManager {getAction(id) {try {if (!this.db) throw new Error("Database not initialized");- return this.db.prepare("SELECT * FROM actions WHERE id = ?").get(id) || null;+ return toActionItem(this.db.prepare("SELECT * FROM actions WHERE id = ?").get(id));} catch (error) {debugLogger.error("Error getting action", { error: error.message }, "notes");throw error;}}- createAction(name, description, prompt, icon = "sparkles") {+ createAction(+ name,+ description,+ prompt,+ icon = "sparkles",+ { kind = "template", sections, output } = {}+ ) {try {if (!this.db) throw new Error("Database not initialized");- const trimmedName = (name || "").trim();- const trimmedPrompt = (prompt || "").trim();- if (!trimmedName) return { success: false, error: "Action name is required" };- if (!trimmedPrompt) return { success: false, error: "Action prompt is required" };+ if (kind !== "template" && kind !== "action") {+ return { success: false, error: "Unknown action kind" };+ }+ const fields = resolveActionFields(kind, { name, description, prompt, sections, output });+ if (fields.error) return { success: false, error: fields.error };const maxOrder = this.db.prepare("SELECT MAX(sort_order) as max_order FROM actions").get();const sortOrder = (maxOrder?.max_order ?? 0) + 1;const result = this.db.prepare(- "INSERT INTO actions (name, description, prompt, icon, sort_order) VALUES (?, ?, ?, ?, ?)"+ "INSERT INTO actions (name, description, prompt, icon, sort_order, client_id, kind, sections, output) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")- .run(trimmedName, (description || "").trim(), trimmedPrompt, icon || "sparkles", sortOrder);- const action = this.db- .prepare("SELECT * FROM actions WHERE id = ?")- .get(result.lastInsertRowid);+ .run(+ fields.name,+ fields.description,+ fields.prompt,+ icon || "sparkles",+ sortOrder,+ randomUUID(),+ kind,+ fields.sections,+ fields.output+ );+ const action = toActionItem(+ this.db.prepare("SELECT * FROM actions WHERE id = ?").get(result.lastInsertRowid)+ );return { success: true, action };} catch (error) {debugLogger.error("Error creating action", { error: error.message }, "notes");@@ -4177,24 +4316,42 @@ class DatabaseManager {}}+ // A row's kind and client id never change; every other field is replaced by+ // the update or kept, then validated as a whole.updateAction(id, updates) {try {if (!this.db) throw new Error("Database not initialized");- const allowedFields = ["name", "description", "prompt", "icon", "sort_order"];- const fields = [];- const values = [];- for (const [key, value] of Object.entries(updates)) {- if (allowedFields.includes(key) && value !== undefined) {- fields.push(`${key} = ?`);- values.push(value);- }- }- if (fields.length === 0) return { success: false };- fields.push("updated_at = CURRENT_TIMESTAMP");- values.push(id);- this.db.prepare(`UPDATE actions SET ${fields.join(", ")} WHERE id = ?`).run(...values);- const action = this.db.prepare("SELECT * FROM actions WHERE id = ?").get(id);- return { success: true, action };+ const current = this.getAction(id);+ if (!current) return { success: false, error: "Action not found" };+ const merged = { ...current };+ for (const key of [+ "name",+ "description",+ "prompt",+ "icon",+ "sort_order",+ "sections",+ "output",+ ]) {+ if (updates[key] !== undefined) merged[key] = updates[key];+ }+ const fields = resolveActionFields(current.kind, merged);+ if (fields.error) return { success: false, error: fields.error };+ this.db+ .prepare(+ "UPDATE actions SET name = ?, description = ?, prompt = ?, icon = ?, sort_order = ?, sections = ?, output = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?"+ )+ .run(+ fields.name,+ fields.description,+ fields.prompt,+ merged.icon,+ merged.sort_order,+ fields.sections,+ fields.output,+ id+ );+ return { success: true, action: this.getAction(id) };} catch (error) {debugLogger.error("Error updating action", { error: error.message }, "notes");throw error;@@ -6005,16 +6162,25 @@ class DatabaseManager {const updaterUpdate = hasExplicitUpdater? "excluded.updated_by_user_id": "updated_by_user_id";+ // An API that predates template ids omits the key; keep the local one.+ const templateIdUpdate = Object.prototype.hasOwnProperty.call(+ cloudNote,+ "enhancement_template_id"+ )+ ? `CASE+ WHEN COALESCE(excluded.enhanced_content, '') = '' AND COALESCE(enhanced_content, '') <> ''+ THEN enhancement_template_id ELSE excluded.enhancement_template_id END`+ : "enhancement_template_id";// Sync must never replace non-empty local content/enhanced_content/// transcript with an empty cloud value (#1290, the #938 invariant).- // The enhancement prompt/hash travel with enhanced_content.+ // The enhancement prompt/hash/template travel with enhanced_content.const stmt = this.db.prepare(`INSERT INTO notes (client_note_id, cloud_id, title, content, enhanced_content,- enhancement_prompt, enhanced_at_content_hash, note_type, source_file,+ enhancement_prompt, enhancement_template_id, enhanced_at_content_hash, note_type, source_file,audio_duration_seconds, transcript, folder_id, space_id, participants, calendar_event_id,diarization_enabled, expected_speaker_count, updated_by_user_id, owner_user_id, created_by_user_id, sync_status, created_at, updated_at,cloud_updated_at, account_id)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'synced', ?, ?, ?, ?)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'synced', ?, ?, ?, ?)ON CONFLICT(client_note_id) DO UPDATE SETcloud_id = excluded.cloud_id,title = excluded.title,@@ -6027,6 +6193,7 @@ class DatabaseManager {enhancement_prompt = CASEWHEN COALESCE(excluded.enhanced_content, '') = '' AND COALESCE(enhanced_content, '') <> ''THEN enhancement_prompt ELSE excluded.enhancement_prompt END,+ enhancement_template_id = ${templateIdUpdate},enhanced_at_content_hash = CASEWHEN COALESCE(excluded.enhanced_content, '') = '' AND COALESCE(enhanced_content, '') <> ''THEN enhanced_at_content_hash ELSE excluded.enhanced_at_content_hash END,@@ -6055,6 +6222,7 @@ class DatabaseManager {cloudNote.content,cloudNote.enhanced_content || null,cloudNote.enhancement_prompt || null,+ cloudNote.enhancement_template_id || null,cloudNote.enhanced_at_content_hash || null,cloudNote.note_type || "personal",cloudNote.source_file || null,diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex f886c0384..fad3de9c2 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -2319,8 +2319,8 @@ class IPCHandlers {return this.databaseManager.getAction(id);});- ipcMain.handle("db-create-action", async (event, name, description, prompt, icon) => {- const result = this.databaseManager.createAction(name, description, prompt, icon);+ ipcMain.handle("db-create-action", async (event, name, description, prompt, icon, fields) => {+ const result = this.databaseManager.createAction(name, description, prompt, icon, fields);if (result?.success && result?.action) {setImmediate(() => {broadcastToWindows("action-created", result.action);diff --git a/src/helpers/modelManagerBridge.js b/src/helpers/modelManagerBridge.jsindex 6f620de3b..1ffff5075 100644--- a/src/helpers/modelManagerBridge.js+++ b/src/helpers/modelManagerBridge.js@@ -605,8 +605,12 @@ class ModelManager {// exact prompt. The MIN_OUTPUT_TOKENS floor below already keeps the prompt// clear of the edge by the same margin, so charging it twice would only// shorten the answer.+ // A caller that refuses window clips still gets no partial answer: a reply+ // that fills the trimmed allowance is refused after inference.+ const acceptsShorterOutput =+ !options.requireCompleteOutput || options.refuseClippedByWindow === true;const affordableOutput = nowUsable - exactTokens;- if (!options.requireCompleteOutput && affordableOutput >= MIN_OUTPUT_TOKENS) {+ if (acceptsShorterOutput && affordableOutput >= MIN_OUTPUT_TOKENS) {debugLogger.info("Trimming the output allowance to fit the context window", {model: modelInfo.model.id,requested: maxTokens,diff --git a/src/helpers/templatePrompts.js b/src/helpers/templatePrompts.jsnew file mode 100644index 000000000..0203cf9b8--- /dev/null+++ b/src/helpers/templatePrompts.js@@ -0,0 +1,114 @@+// Turns a note template or action into the input and system prompt the model+// receives. Pure, so the live canary and the tests can build the exact request+// the app sends.+//+// A template always writes the summary from the note's own material: the user's+// notes, the meeting context and the transcript. An action works from the AI+// summary when the note has one, and from that same material when it doesn't.++import {+ BASE_SYSTEM_PROMPT,+ CHAT_ACTION_ON_MATERIAL_PREAMBLE,+ CHAT_ACTION_ON_SUMMARY_PREAMBLE,+ MEETING_INPUT_PREAMBLE,+ MEETING_SYSTEM_PROMPT,+ NOTE_INPUT_PREAMBLE,+ SECTIONED_NOTES_FOOTER,+ SECTIONED_NOTES_FORMAT,+ SECTIONED_NOTES_INSTRUCTIONS,+ STANDALONE_PROMPT_KEYS,+ SUMMARY_ACTION_FROM_MATERIAL_PROMPT,+ SUMMARY_ACTION_SYSTEM_PROMPT,+} from "./builtinActions.js";++/**+ * Trimmed sections whose heading has text besides Markdown heading marks ("#"s+ * followed by a space); a non-list is no sections.+ */+export function normalizeSections(value) {+ if (!Array.isArray(value)) return [];+ return value+ .map((section) => ({+ heading: String(section?.heading ?? "")+ .trim()+ .replace(/^(?:#+(?:\s+|$))+/, ""),+ instruction: String(section?.instruction ?? "").trim(),+ }))+ .filter((section) => section.heading);+}++/**+ * A template with sections is compiled around the shared notes rules. One with+ * only a prompt keeps the request it always had: standalone built-ins get the+ * material preamble, everything else the generic system prompt.+ */+export function compileTemplatePrompt(template, { isMeetingNote = false } = {}) {+ const preamble = isMeetingNote ? MEETING_INPUT_PREAMBLE : NOTE_INPUT_PREAMBLE;+ const sections = normalizeSections(template.sections);+ if (sections.length > 0) {+ const context = (template.prompt ?? "").trim();+ return (+ preamble ++ [+ SECTIONED_NOTES_INSTRUCTIONS,+ context &&+ `TEMPLATE INSTRUCTIONS (follow these where they differ from the format below):\n${context}`,+ SECTIONED_NOTES_FORMAT,+ ...sections.map(({ heading, instruction }) =>+ instruction ? `## ${heading}\n${instruction}` : `## ${heading}`+ ),+ SECTIONED_NOTES_FOOTER,+ ]+ .filter(Boolean)+ .join("\n\n")+ );+ }+ if (template.translation_key && STANDALONE_PROMPT_KEYS.has(template.translation_key)) {+ return preamble + template.prompt;+ }+ return (isMeetingNote ? MEETING_SYSTEM_PROMPT : BASE_SYSTEM_PROMPT) + template.prompt;+}++export function compileSummaryActionPrompt(action, { fromSummary, isMeetingNote = false }) {+ if (fromSummary) return SUMMARY_ACTION_SYSTEM_PROMPT + action.prompt;+ const preamble = isMeetingNote ? MEETING_INPUT_PREAMBLE : NOTE_INPUT_PREAMBLE;+ return preamble + SUMMARY_ACTION_FROM_MATERIAL_PROMPT + action.prompt;+}++export function compileChatActionPrompt(action, { fromSummary }) {+ return (+ (fromSummary ? CHAT_ACTION_ON_SUMMARY_PREAMBLE : CHAT_ACTION_ON_MATERIAL_PREAMBLE) ++ action.prompt+ );+}++/**+ * What a template or a summary action reads. With a summary to work from, an+ * action gets it plus the user's notes and the meeting context for accuracy;+ * the transcript stays out, so the request always fits and is never split.+ * Otherwise the run reads the note's material, also returned in pieces so a+ * recording too long for a local model can be split along its transcript.+ */+export function buildNoteRunInput(action, { summary, notes, meetingContext, transcript }) {+ const join = (parts) => parts.filter(Boolean).join("\n\n");+ const hasNotes = notes.trim().length > 0;+ if (action.kind === "action" && summary?.trim()) {+ return {+ input: join([+ `## Current Summary\n${summary}`,+ hasNotes && `## My Notes\n${notes}`,+ meetingContext,+ ]),+ fromSummary: true,+ };+ }+ return {+ input: join([+ hasNotes && notes,+ meetingContext,+ transcript && `## Meeting Transcript\n${transcript}`,+ ]),+ fromSummary: false,+ material: { notes: hasNotes ? notes : "", meetingContext, transcript },+ };+}diff --git a/src/hooks/useActionProcessing.ts b/src/hooks/useActionProcessing.tsindex 62881864b..f5c746255 100644--- a/src/hooks/useActionProcessing.ts+++ b/src/hooks/useActionProcessing.ts@@ -10,6 +10,7 @@ import {type ActionProcessingStatus,type RunActionOptions,} from "../stores/actionProcessingStore";+import { getActionName } from "../stores/actionStore";export type ActionProcessingState = ActionProcessingStatus;@@ -26,7 +27,9 @@ export function useActionProcessing(noteId: number | null) {const runAction = useCallback((action: ActionItem, noteContent: string, contentHash: string, options: RunActionOptions) => {if (noteId == null) return;- runBackgroundAction(noteId, noteContent, contentHash, action, options, {+ // The overlay shows the run's name, so a built-in's is translated here.+ const translated = { ...action, name: getActionName(action, t) };+ runBackgroundAction(noteId, noteContent, contentHash, translated, options, {noModel: t("notes.actions.errors.noModel"),noEndpoint: t("notes.actions.errors.noEndpoint"),actionFailed: t("notes.actions.errors.actionFailed"),diff --git a/src/hooks/useEmbeddedChat.ts b/src/hooks/useEmbeddedChat.tsindex 46fc77365..2e1138b1d 100644--- a/src/hooks/useEmbeddedChat.ts+++ b/src/hooks/useEmbeddedChat.ts@@ -1,6 +1,6 @@import { useState, useCallback, useEffect, useMemo, useRef } from "react";import { useChatPersistence } from "../components/chat/useChatPersistence";-import { useChatStreaming } from "../components/chat/useChatStreaming";+import { useChatStreaming, type SendToAIOptions } from "../components/chat/useChatStreaming";import { useChatMessageSender } from "../components/chat/useChatMessageSender";import type { Message, AgentState } from "../components/chat/types";import { attendeesForUser } from "../utils/noteAttendees";@@ -25,6 +25,7 @@ interface UseEmbeddedChatOptions {selfEmail?: string | null;/** The note's calendar event, whose organizer main adds to the attendees. */noteCalendarEventId?: string | null;+ noteSummary?: string;}interface NoteConversationItem {@@ -38,7 +39,7 @@ interface NoteConversationItem {interface UseEmbeddedChatReturn {messages: Message[];agentState: AgentState;- sendMessage: (text: string) => Promise<void>;+ sendMessage: (text: string, options?: SendToAIOptions) => Promise<void>;cancelStream: () => void;noteConversations: NoteConversationItem[];activeConversationId: number | null;@@ -60,6 +61,7 @@ export function useEmbeddedChat({noteOwnedByUser = false,selfEmail = null,noteCalendarEventId = null,+ noteSummary,}: UseEmbeddedChatOptions): UseEmbeddedChatReturn {const [conversationId, setConversationId] = useState<number | null>(null);const [noteConversations, setNoteConversations] = useState<NoteConversationItem[]>([]);@@ -80,11 +82,12 @@ export function useEmbeddedChat({folderId != null ? `Folder ID: ${folderId}` : "",`Title: ${noteTitle}`,`Content:\n${noteContent}`,+ noteSummary ? `\nAI Summary:\n${noteSummary}` : "",noteTranscript ? `\nTranscript:\n${noteTranscript}` : "",].filter(Boolean).join("\n"),- [folderId, noteContent, noteId, noteTitle, noteTranscript]+ [folderId, noteContent, noteId, noteSummary, noteTitle, noteTranscript]);const noteMeeting = useMemo<NoteAttendeesRequest>(@@ -191,8 +194,8 @@ export function useEmbeddedChat({onSendingChange: setSubmissionInFlight,});const sendMessage = useCallback(- async (text: string): Promise<void> => {- await sendMessageWithResult(text);+ async (text: string, options?: SendToAIOptions): Promise<void> => {+ await sendMessageWithResult(text, options);},[sendMessageWithResult]);diff --git a/src/index.css b/src/index.cssindex 4dbb09df9..3063e2512 100644--- a/src/index.css+++ b/src/index.css@@ -1707,7 +1707,8 @@ a:hover {.rich-text-editor-content {outline: none;unicode-bidi: plaintext;- padding-block: 0.75rem 5rem;+ /* The bottom clears the note's ask bar and the action chips above it. */+ padding-block: 0.75rem 7.5rem;/* Centers the text in the page column (PAGE_CONTENT_WIDTH_CLASS) with padding, not amax-width, so the editable area spans the pane and a margin click places the caret. */padding-inline: max(1.25rem, calc((100% - var(--container-5xl)) / 2 + 1.25rem));diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.jsonindex fd9da7467..c174dcf03 100644--- a/src/locales/ar/translation.json+++ b/src/locales/ar/translation.json@@ -1700,7 +1700,8 @@"thinking": "جاري التفكير...","typeMessage": "اكتب رسالة...","send": "إرسال",- "voiceDraftStreamingOnly": "الإدخال الصوتي غير متاح مع مزود التفريغ الخاص بك: فهو يدعم الإملاء المباشر فقط. اختر مزودًا آخر في الإعدادات ← تحويل الكلام إلى نص (Speech to Text)."+ "voiceDraftStreamingOnly": "الإدخال الصوتي غير متاح مع مزود التفريغ الخاص بك: فهو يدعم الإملاء المباشر فقط. اختر مزودًا آخر في الإعدادات ← تحويل الكلام إلى نص (Speech to Text).",+ "commands": "الأوامر"},"tools": {"search_notesName": "البحث في الملاحظات",@@ -1916,7 +1917,7 @@"sidebar": {"newNote": "ملاحظة جديدة","searchNotes": "البحث في الملاحظات",- "actions": "الإجراءات"+ "templatesAndActions": "القوالب والإجراءات"},"spaces": {"privateSpaces": "ملاحظات خاصة",@@ -2314,8 +2315,8 @@"done": "تم","chunkProgress": "الجزء {{step}} من {{total}}","emptyReply": "أعاد النموذج ردًا فارغًا. حاول مرة أخرى، أو اختر نموذجًا آخر.",+ "allActions": "كل الإجراءات","manage": "إدارة الإجراءات...",- "manageTitle": "إجراءات مخصصة","addAction": "إجراء جديد","editAction": "تعديل الإجراء","namePlaceholder": "اسم الإجراء",@@ -2329,8 +2330,6 @@"promptLabel": "الموجه (Prompt)","emptyEditorTitle": "اختر إجراءً","emptyEditorDescription": "اختر إجراءً من القائمة أو أنشئ إجراءً جديدًا",- "runAction": "تشغيل {{name}}",- "selectAction": "تحديد إجراء","builtin": {"generateNotes": {"name": "إنشاء ملاحظات",@@ -2342,15 +2341,89 @@"cta": "صياغة بريد متابعة"},"detailedNotes": {- "name": "ملاحظات مفصلة",+ "name": "ملخص بالذكاء الاصطناعي","description": "ملاحظات اجتماع دقيقة وشاملة تتضمن القرارات والمهام"+ },+ "makeTodos": {+ "name": "إنشاء قائمة مهام",+ "description": "سرد كل مهمة والمسؤول عنها في الدردشة"+ },+ "createOutline": {+ "name": "إنشاء مخطط",+ "description": "تنظيم موضوعات الملاحظة في مخطط داخل الدردشة"+ },+ "oneOnOne": {+ "name": "اجتماع فردي",+ "description": "المستجدات والملاحظات والتطور والخطوات التالية من اجتماع فردي"+ },+ "standUp": {+ "name": "الاجتماع اليومي",+ "description": "تقدّم كل شخص وخططه والعوائق التي تواجهه"+ },+ "salesCall": {+ "name": "مكالمة مبيعات",+ "description": "الاحتياجات والاعتراضات والميزانية وآلية اتخاذ القرار"+ },+ "userInterview": {+ "name": "مقابلة مستخدم",+ "description": "سير العمل والمشكلات وردود الفعل والاقتباسات من أحد المشاركين"+ },+ "shorten": {+ "name": "اختصار",+ "description": "اجعل الملخص بنصف طوله تقريبًا",+ "cta": "اختصر الملخص"+ },+ "addTldr": {+ "name": "إضافة خلاصة سريعة",+ "description": "أضف خلاصة من جملتين أو ثلاث في بداية الملخص",+ "cta": "أضف خلاصة سريعة"+ },+ "slackUpdate": {+ "name": "تحديث لـ Slack",+ "description": "اكتب تحديثًا قصيرًا للفريق لنشره على Slack",+ "cta": "اكتب تحديثًا لـ Slack"}},"errors": {"noModel": "لم يتم تحديد نموذج ذكاء اصطناعي. قم بتكوين واحد في الإعدادات.","actionFailed": "فشل الإجراء",- "noEndpoint": "لم يتم تعيين عنوان URL لخادم مستضاف ذاتيًا. قم بتكوين واحد في الإعدادات."- }+ "noEndpoint": "لم يتم تعيين عنوان URL لخادم مستضاف ذاتيًا. قم بتكوين واحد في الإعدادات.",+ "outputTruncated": "نفدت المساحة لدى نموذج الذكاء الاصطناعي قبل أن ينتهي، لذا بقيت الملاحظة كما هي.",+ "nothingToSummarize": "لا يوجد في هذه الملاحظة ما يمكن تلخيصه بعد، لذا بقي الملخص بالذكاء الاصطناعي كما هو.",+ "saveFailed": "تعذّر الحفظ. تأكد من أن لا شيء أطول من اللازم ثم حاول مرة أخرى."+ },+ "tab": "الإجراءات",+ "output": {+ "auto": "تلقائي",+ "chat": "الدردشة",+ "summary": "الملخص بالذكاء الاصطناعي",+ "chatHint": "يجيب في دردشة الملاحظة ويترك الملخص بالذكاء الاصطناعي كما هو.",+ "summaryHint": "يعدّل ملخص الملاحظة بالذكاء الاصطناعي، أو يكتبه من النص المفرَّغ إن لم يكن موجودًا بعد.",+ "autoHint": "يقرأ التعليمات عند الحفظ ويختار الدردشة أو الملخص بالذكاء الاصطناعي."+ },+ "applied": "تم تحديث الملخص بالذكاء الاصطناعي باستخدام {{name}}"+ },+ "templates": {+ "tab": "القوالب",+ "managerTitle": "القوالب والإجراءات",+ "manage": "إدارة القوالب...",+ "select": "اختر قالبًا",+ "addTemplate": "قالب جديد",+ "editTemplate": "تعديل القالب",+ "namePlaceholder": "اسم القالب",+ "contextLabel": "السياق",+ "contextPlaceholder": "ما نوع هذا الاجتماع، وعلامَ يجب أن يركّز الملخص؟",+ "sectionsLabel": "الأقسام",+ "addSection": "إضافة قسم",+ "sectionHeadingPlaceholder": "عنوان القسم",+ "sectionInstructionPlaceholder": "ماذا يتضمن هذا القسم؟",+ "moveSectionUp": "نقل القسم لأعلى",+ "moveSectionDown": "نقل القسم لأسفل",+ "removeSection": "إزالة القسم",+ "noSectionsHint": "من دون أقسام، يكون السياق هو التعليمات الكاملة للملخص.",+ "noTemplates": "لا توجد قوالب بعد",+ "emptyEditorTitle": "اختر قالبًا",+ "emptyEditorDescription": "اختر قالبًا من القائمة أو أنشئ قالبًا جديدًا"},"onboarding": {"llm": {@@ -2358,12 +2431,12 @@"description": "تستخدم الإجراءات الذكاء الاصطناعي لتحويل ملاحظاتك. قم بإعداد نموذج لغة للبدء.","configured": "تم تكوين نموذج الذكاء الاصطناعي"},- "actions": {- "title": "إجراءات مدعومة بالذكاء الاصطناعي",- "description": "تعمل الإجراءات على تحويل ملاحظاتك — تنظيف النصوص المفرَّغة، وتلخيص الاجتماعات، والمزيد. استخدم الإجراءات المضمّنة أو أنشئ إجراءاتك الخاصة.",- "builtInLabel": "مضمّن",- "createTitle": "أنشئ إجراءك الخاص",- "createDescription": "حدد إجراءً مخصصًا باستخدام موجه الذكاء الاصطناعي الخاص بك. يمكنك دائمًا تعديله أو إضافة المزيد لاحقًا في الإعدادات.",+ "templates": {+ "title": "القوالب والإجراءات",+ "description": "تحدد القوالب شكل ملخصك بالذكاء الاصطناعي، من ملاحظات الاجتماعات المفصّلة إلى أقسام تحددها بنفسك. وتعمل الإجراءات على ملاحظة، مثل كتابة مسودة بريد متابعة في الدردشة.",+ "builtInLabel": "قوالبك",+ "createTitle": "أنشئ قالبك الخاص",+ "createDescription": "صِف الملخص الذي تريده. يمكنك إضافة أقسام ومزيد من القوالب والإجراءات لاحقًا.","created": "تم الإنشاء!"},"getStarted": "البدء",@@ -4742,9 +4815,7 @@"conversationSelector": "تبديل المحادثة","history": "السجل","quickActions": "إجراءات سريعة",- "generateSummary": "إنشاء ملخص",- "makeTodos": "إنشاء قائمة مهام",- "createOutline": "إنشاء مخطط"+ "generateSummary": "إنشاء ملخص"},"transcriptionPreview": {"label": "معاينة",diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex d70b7b7af..c89939715 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -3126,7 +3126,7 @@"sidebar": {"newNote": "Neue Notiz","searchNotes": "Notizen suchen",- "actions": "Aktionen"+ "templatesAndActions": "Vorlagen & Aktionen"},"spaces": {"privateSpaces": "Private Notizen",@@ -3510,8 +3510,8 @@"done": "Fertig","chunkProgress": "Teil {{step}} von {{total}}","emptyReply": "Das Modell hat eine leere Antwort zurückgegeben. Versuchen Sie es erneut oder wählen Sie ein anderes Modell.",+ "allActions": "Alle Aktionen","manage": "Aktionen verwalten...",- "manageTitle": "Benutzerdefinierte Aktionen","addAction": "Neue Aktion","editAction": "Aktion bearbeiten","namePlaceholder": "Name der Aktion",@@ -3525,8 +3525,6 @@"promptLabel": "Anweisung","emptyEditorTitle": "Aktion auswählen","emptyEditorDescription": "Wählen Sie eine Aktion aus der Liste oder erstellen Sie eine neue",- "runAction": "{{name}} ausführen",- "selectAction": "Aktion auswählen","builtin": {"generateNotes": {"name": "Notizen generieren",@@ -3538,15 +3536,89 @@"cta": "Follow-up-E-Mail entwerfen"},"detailedNotes": {- "name": "Ausführliche Notizen",+ "name": "KI-Zusammenfassung","description": "Präzise, umfassende Meeting-Notizen mit Entscheidungen und Aufgaben"+ },+ "makeTodos": {+ "name": "Aufgabenliste erstellen",+ "description": "Alle Aufgaben und ihre Verantwortlichen im Chat auflisten"+ },+ "createOutline": {+ "name": "Gliederung erstellen",+ "description": "Die Themen der Notiz im Chat gliedern"+ },+ "oneOnOne": {+ "name": "1:1",+ "description": "Updates, Feedback, Entwicklung und nächste Schritte aus einem Einzelgespräch"+ },+ "standUp": {+ "name": "Stand-up",+ "description": "Fortschritt, Pläne und Blocker jeder Person"+ },+ "salesCall": {+ "name": "Verkaufsgespräch",+ "description": "Bedarf, Einwände, Budget und Entscheidungsprozess"+ },+ "userInterview": {+ "name": "Nutzerinterview",+ "description": "Arbeitsablauf, Probleme, Reaktionen und Zitate einer teilnehmenden Person"+ },+ "shorten": {+ "name": "Kürzen",+ "description": "Die Zusammenfassung etwa halb so lang machen",+ "cta": "Zusammenfassung kürzen"+ },+ "addTldr": {+ "name": "TL;DR hinzufügen",+ "description": "Ein TL;DR aus zwei oder drei Sätzen an den Anfang der Zusammenfassung setzen",+ "cta": "TL;DR hinzufügen"+ },+ "slackUpdate": {+ "name": "Slack-Update",+ "description": "Ein kurzes Team-Update für Slack schreiben",+ "cta": "Slack-Update schreiben"}},"errors": {"noModel": "Kein KI-Modell ausgewählt. Konfigurieren Sie eins in den Einstellungen.","actionFailed": "Aktion fehlgeschlagen",- "noEndpoint": "Keine URL für den selbst gehosteten Server festgelegt. Konfigurieren Sie eine in den Einstellungen."- }+ "noEndpoint": "Keine URL für den selbst gehosteten Server festgelegt. Konfigurieren Sie eine in den Einstellungen.",+ "outputTruncated": "Dem KI-Modell ging der Platz aus, bevor es fertig war. Die Notiz bleibt daher unverändert.",+ "nothingToSummarize": "Diese Notiz enthält noch nichts zum Zusammenfassen, daher bleibt die KI-Zusammenfassung unverändert.",+ "saveFailed": "Speichern nicht möglich. Prüfen Sie, dass nichts zu lang ist, und versuchen Sie es erneut."+ },+ "tab": "Aktionen",+ "output": {+ "auto": "Automatisch",+ "chat": "Chat",+ "summary": "KI-Zusammenfassung",+ "chatHint": "Antwortet im Chat der Notiz und lässt die KI-Zusammenfassung unverändert.",+ "summaryHint": "Bearbeitet die KI-Zusammenfassung der Notiz oder erstellt sie aus dem Transkript, falls es noch keine gibt.",+ "autoHint": "Liest beim Speichern den Prompt und wählt den Chat oder die KI-Zusammenfassung."+ },+ "applied": "KI-Zusammenfassung mit {{name}} aktualisiert"+ },+ "templates": {+ "tab": "Vorlagen",+ "managerTitle": "Vorlagen & Aktionen",+ "manage": "Vorlagen verwalten...",+ "select": "Vorlage auswählen",+ "addTemplate": "Neue Vorlage",+ "editTemplate": "Vorlage bearbeiten",+ "namePlaceholder": "Name der Vorlage",+ "contextLabel": "Kontext",+ "contextPlaceholder": "Um welche Art von Besprechung geht es, und worauf soll sich die Zusammenfassung konzentrieren?",+ "sectionsLabel": "Abschnitte",+ "addSection": "Abschnitt hinzufügen",+ "sectionHeadingPlaceholder": "Überschrift des Abschnitts",+ "sectionInstructionPlaceholder": "Was gehört in diesen Abschnitt?",+ "moveSectionUp": "Abschnitt nach oben verschieben",+ "moveSectionDown": "Abschnitt nach unten verschieben",+ "removeSection": "Abschnitt entfernen",+ "noSectionsHint": "Ohne Abschnitte ist der Kontext die gesamte Anweisung für die Zusammenfassung.",+ "noTemplates": "Noch keine Vorlagen",+ "emptyEditorTitle": "Vorlage auswählen",+ "emptyEditorDescription": "Wählen Sie eine Vorlage aus der Liste oder erstellen Sie eine neue"},"onboarding": {"llm": {@@ -3554,12 +3626,12 @@"description": "Aktionen verwenden KI, um Ihre Notizen zu transformieren. Richten Sie ein Sprachmodell ein, um loszulegen.","configured": "KI-Modell konfiguriert"},- "actions": {- "title": "KI-gestützte Aktionen",- "description": "Aktionen transformieren Ihre Notizen – bereinigen Transkriptionen, fassen Besprechungen zusammen und mehr. Verwenden Sie integrierte Aktionen oder erstellen Sie eigene.",- "builtInLabel": "Integriert",- "createTitle": "Eigene Aktion erstellen",- "createDescription": "Definieren Sie eine benutzerdefinierte Aktion mit Ihrem eigenen KI-Prompt. Sie können später jederzeit weitere hinzufügen oder bearbeiten.",+ "templates": {+ "title": "Vorlagen und Aktionen",+ "description": "Vorlagen bestimmen Ihre KI-Zusammenfassung, von ausführlichen Besprechungsnotizen bis zu eigenen Abschnitten. Aktionen laufen auf einer Notiz, etwa ein Follow-up-E-Mail-Entwurf im Chat.",+ "builtInLabel": "Ihre Vorlagen",+ "createTitle": "Eigene Vorlage erstellen",+ "createDescription": "Beschreiben Sie die gewünschte Zusammenfassung. Abschnitte, weitere Vorlagen und Aktionen können Sie später hinzufügen.","created": "Erstellt!"},"getStarted": "Loslegen",@@ -3855,7 +3927,8 @@"thinking": "Denkt nach...","typeMessage": "Nachricht eingeben...","send": "Senden",- "voiceDraftStreamingOnly": "Spracheingabe ist mit Ihrem Transkriptionsanbieter nicht verfügbar: Er unterstützt nur Live-Diktat. Wählen Sie unter Einstellungen → Sprache zu Text einen anderen Anbieter."+ "voiceDraftStreamingOnly": "Spracheingabe ist mit Ihrem Transkriptionsanbieter nicht verfügbar: Er unterstützt nur Live-Diktat. Wählen Sie unter Einstellungen → Sprache zu Text einen anderen Anbieter.",+ "commands": "Befehle"},"tools": {"search_notesName": "Notizen durchsuchen",@@ -4620,9 +4693,7 @@"conversationSelector": "Unterhaltung wechseln","history": "Verlauf","quickActions": "Schnellaktionen",- "generateSummary": "Zusammenfassung erstellen",- "makeTodos": "Aufgabenliste erstellen",- "createOutline": "Gliederung erstellen"+ "generateSummary": "Zusammenfassung erstellen"},"transcriptionPreview": {"label": "Vorschau",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 5a74b4f12..1dcdb078e 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -3126,7 +3126,7 @@"sidebar": {"newNote": "New note","searchNotes": "Search notes",- "actions": "Actions"+ "templatesAndActions": "Templates & Actions"},"spaces": {"privateSpaces": "Private notes",@@ -3510,8 +3510,8 @@"done": "Done","chunkProgress": "Part {{step}} of {{total}}","emptyReply": "The model returned an empty reply. Try again, or pick a different model.",+ "allActions": "All actions","manage": "Manage Actions...",- "manageTitle": "Custom Actions","addAction": "New Action","editAction": "Edit Action","namePlaceholder": "Action name",@@ -3525,8 +3525,6 @@"promptLabel": "Prompt","emptyEditorTitle": "Select an action","emptyEditorDescription": "Choose an action from the list or create a new one",- "runAction": "Run {{name}}",- "selectAction": "Select action","builtin": {"generateNotes": {"name": "Generate Notes",@@ -3538,15 +3536,89 @@"cta": "Draft a follow-up email"},"detailedNotes": {- "name": "Detailed Notes",+ "name": "AI Summary","description": "Accurate, comprehensive meeting notes with decisions and action items"+ },+ "makeTodos": {+ "name": "Make to-dos",+ "description": "List every to-do and its owner in the chat"+ },+ "createOutline": {+ "name": "Create outline",+ "description": "Outline the note's topics in the chat"+ },+ "oneOnOne": {+ "name": "1:1",+ "description": "Updates, feedback, growth, and next steps from a one-on-one"+ },+ "standUp": {+ "name": "Stand-up",+ "description": "Each person's progress, plans, and blockers"+ },+ "salesCall": {+ "name": "Sales call",+ "description": "Needs, objections, budget, and the decision process"+ },+ "userInterview": {+ "name": "User interview",+ "description": "Workflow, pain points, reactions, and quotes from a participant"+ },+ "shorten": {+ "name": "Shorten",+ "description": "Make the summary about half as long",+ "cta": "Shorten the summary"+ },+ "addTldr": {+ "name": "Add TL;DR",+ "description": "Put a two- or three-sentence TL;DR at the top of the summary",+ "cta": "Add a TL;DR"+ },+ "slackUpdate": {+ "name": "Slack update",+ "description": "Write a short team update to post in Slack",+ "cta": "Write a Slack update"}},"errors": {"noModel": "No AI model selected. Configure one in Settings.","actionFailed": "Action failed",- "noEndpoint": "No self-hosted server URL set. Configure one in Settings."- }+ "noEndpoint": "No self-hosted server URL set. Configure one in Settings.",+ "outputTruncated": "The AI model ran out of room before it finished, so the note was left as it was.",+ "nothingToSummarize": "There's nothing to summarize in this note yet, so the AI summary was left as it was.",+ "saveFailed": "Couldn't save. Check that nothing is too long and try again."+ },+ "tab": "Actions",+ "output": {+ "auto": "Auto",+ "chat": "Chat",+ "summary": "AI summary",+ "chatHint": "Answers in the note's chat and leaves the AI summary as it is.",+ "summaryHint": "Edits the note's AI summary, or writes one from the transcript if there isn't one yet.",+ "autoHint": "Reads the prompt when you save and picks the chat or the AI summary."+ },+ "applied": "AI summary updated with {{name}}"+ },+ "templates": {+ "tab": "Templates",+ "managerTitle": "Templates & Actions",+ "manage": "Manage Templates...",+ "select": "Choose template",+ "addTemplate": "New Template",+ "editTemplate": "Edit Template",+ "namePlaceholder": "Template name",+ "contextLabel": "Context",+ "contextPlaceholder": "What kind of meeting is this, and what should the summary focus on?",+ "sectionsLabel": "Sections",+ "addSection": "Add section",+ "sectionHeadingPlaceholder": "Section heading",+ "sectionInstructionPlaceholder": "What goes in this section?",+ "moveSectionUp": "Move section up",+ "moveSectionDown": "Move section down",+ "removeSection": "Remove section",+ "noSectionsHint": "Without sections, the context is the whole instruction for the summary.",+ "noTemplates": "No templates yet",+ "emptyEditorTitle": "Select a template",+ "emptyEditorDescription": "Choose a template from the list or create a new one"},"onboarding": {"llm": {@@ -3554,12 +3626,12 @@"description": "Actions use AI to transform your notes. Set up a language model to get started.","configured": "AI model configured"},- "actions": {- "title": "AI-Powered Actions",- "description": "Actions transform your notes — clean up transcriptions, summarize meetings, and more. Use built-in actions or create your own.",- "builtInLabel": "Built-in",- "createTitle": "Create your own action",- "createDescription": "Define a custom action with your own AI prompt. You can always edit or add more later in settings.",+ "templates": {+ "title": "Templates and Actions",+ "description": "Templates shape your AI summary, from detailed meeting notes to sections you define. Actions run on a note, like drafting a follow-up email in the chat.",+ "builtInLabel": "Your templates",+ "createTitle": "Create your own template",+ "createDescription": "Describe the summary you want. You can add sections, more templates, and actions later.","created": "Created!"},"getStarted": "Get Started",@@ -3855,7 +3927,8 @@"thinking": "Thinking...","typeMessage": "Type a message...","send": "Send",- "voiceDraftStreamingOnly": "Voice input isn't available with your transcription provider: it only supports live dictation. Choose another provider in Settings → Speech to Text."+ "voiceDraftStreamingOnly": "Voice input isn't available with your transcription provider: it only supports live dictation. Choose another provider in Settings → Speech to Text.",+ "commands": "Commands"},"tools": {"search_notesName": "Search notes",@@ -4620,9 +4693,7 @@"conversationSelector": "Switch conversation","history": "History","quickActions": "Quick actions",- "generateSummary": "Generate summary",- "makeTodos": "Make to-dos",- "createOutline": "Create outline"+ "generateSummary": "Generate summary"},"transcriptionPreview": {"label": "Preview",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 9ca45391d..4c7835468 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -2827,7 +2827,7 @@"sidebar": {"newNote": "Nueva nota","searchNotes": "Buscar notas",- "actions": "Acciones"+ "templatesAndActions": "Plantillas y acciones"},"spaces": {"privateSpaces": "Notas privadas",@@ -3192,8 +3192,8 @@"showInFileManager": "Mostrar en {{manager}}"},"actions": {+ "allActions": "Todas las acciones","manage": "Gestionar acciones...",- "manageTitle": "Acciones personalizadas","addAction": "Nueva acción","editAction": "Editar acción","namePlaceholder": "Nombre de la acción",@@ -3207,8 +3207,6 @@"promptLabel": "Instrucción","emptyEditorTitle": "Seleccionar acción","emptyEditorDescription": "Elige una acción de la lista o crea una nueva",- "runAction": "Ejecutar {{name}}",- "selectAction": "Seleccionar acción","done": "Listo","chunkProgress": "Parte {{step}} de {{total}}","emptyReply": "El modelo devolvió una respuesta vacía. Vuelve a intentarlo o elige otro modelo.",@@ -3223,15 +3221,89 @@"cta": "Redactar correo de seguimiento"},"detailedNotes": {- "name": "Notas detalladas",+ "name": "Resumen con IA","description": "Notas de reunión precisas y completas con decisiones y tareas"+ },+ "makeTodos": {+ "name": "Crear tareas",+ "description": "Enumera cada tarea y su responsable en el chat"+ },+ "createOutline": {+ "name": "Crear esquema",+ "description": "Esquematiza los temas de la nota en el chat"+ },+ "oneOnOne": {+ "name": "1:1",+ "description": "Novedades, feedback, desarrollo y próximos pasos de una reunión individual"+ },+ "standUp": {+ "name": "Stand-up",+ "description": "Avances, planes y bloqueos de cada persona"+ },+ "salesCall": {+ "name": "Llamada de ventas",+ "description": "Necesidades, objeciones, presupuesto y proceso de decisión"+ },+ "userInterview": {+ "name": "Entrevista con usuario",+ "description": "Flujo de trabajo, problemas, reacciones y citas de un participante"+ },+ "shorten": {+ "name": "Acortar",+ "description": "Deja el resumen en la mitad de largo",+ "cta": "Acortar el resumen"+ },+ "addTldr": {+ "name": "Añadir TL;DR",+ "description": "Pon un TL;DR de dos o tres frases al principio del resumen",+ "cta": "Añadir un TL;DR"+ },+ "slackUpdate": {+ "name": "Actualización para Slack",+ "description": "Escribe una breve actualización para el equipo en Slack",+ "cta": "Escribir una actualización para Slack"}},"errors": {"noModel": "No hay modelo de IA seleccionado. Configura uno en Ajustes.","actionFailed": "La acción falló",- "noEndpoint": "No hay URL del servidor autoalojado configurada. Configura una en Ajustes."- }+ "noEndpoint": "No hay URL del servidor autoalojado configurada. Configura una en Ajustes.",+ "outputTruncated": "El modelo de IA se quedó sin espacio antes de terminar, así que la nota quedó como estaba.",+ "nothingToSummarize": "Esta nota aún no tiene nada que resumir, así que el resumen con IA se quedó como estaba.",+ "saveFailed": "No se pudo guardar. Comprueba que nada sea demasiado largo e inténtalo de nuevo."+ },+ "tab": "Acciones",+ "output": {+ "auto": "Automático",+ "chat": "Chat",+ "summary": "Resumen con IA",+ "chatHint": "Responde en el chat de la nota y deja el resumen con IA como está.",+ "summaryHint": "Edita el resumen con IA de la nota, o lo escribe a partir de la transcripción si aún no hay uno.",+ "autoHint": "Lee el prompt al guardar y elige el chat o el resumen con IA."+ },+ "applied": "Resumen con IA actualizado con {{name}}"+ },+ "templates": {+ "tab": "Plantillas",+ "managerTitle": "Plantillas y acciones",+ "manage": "Gestionar plantillas...",+ "select": "Elegir plantilla",+ "addTemplate": "Nueva plantilla",+ "editTemplate": "Editar plantilla",+ "namePlaceholder": "Nombre de la plantilla",+ "contextLabel": "Contexto",+ "contextPlaceholder": "¿Qué tipo de reunión es y en qué debe centrarse el resumen?",+ "sectionsLabel": "Secciones",+ "addSection": "Añadir sección",+ "sectionHeadingPlaceholder": "Título de la sección",+ "sectionInstructionPlaceholder": "¿Qué va en esta sección?",+ "moveSectionUp": "Subir sección",+ "moveSectionDown": "Bajar sección",+ "removeSection": "Quitar sección",+ "noSectionsHint": "Sin secciones, el contexto es la instrucción completa para el resumen.",+ "noTemplates": "Aún no hay plantillas",+ "emptyEditorTitle": "Seleccionar plantilla",+ "emptyEditorDescription": "Elige una plantilla de la lista o crea una nueva"},"empty": {"title": "Todavía no hay notas aquí",@@ -3255,12 +3327,12 @@"description": "Las acciones usan IA para transformar tus notas. Configura un modelo de lenguaje para comenzar.","configured": "Modelo de IA configurado"},- "actions": {- "title": "Acciones impulsadas por IA",- "description": "Las acciones transforman tus notas: corrigen transcripciones, resumen reuniones y más. Usa acciones integradas o crea las tuyas.",- "builtInLabel": "Integrada",- "createTitle": "Crea tu propia acción",- "createDescription": "Define una acción personalizada con tu propio prompt de IA. Puedes editar o agregar más después en los ajustes.",+ "templates": {+ "title": "Plantillas y acciones",+ "description": "Las plantillas dan forma a tu resumen con IA, desde notas de reunión detalladas hasta secciones que tú defines. Las acciones se ejecutan sobre una nota, como redactar un correo de seguimiento en el chat.",+ "builtInLabel": "Tus plantillas",+ "createTitle": "Crea tu propia plantilla",+ "createDescription": "Describe el resumen que quieres. Puedes añadir secciones, más plantillas y acciones después.","created": "¡Creada!"},"getStarted": "Comenzar",@@ -3737,7 +3809,8 @@"thinking": "Pensando...","typeMessage": "Escribe un mensaje...","send": "Enviar",- "voiceDraftStreamingOnly": "La entrada de voz no está disponible con tu proveedor de transcripción: solo admite dictado en directo. Elige otro proveedor en Ajustes → Voz a texto."+ "voiceDraftStreamingOnly": "La entrada de voz no está disponible con tu proveedor de transcripción: solo admite dictado en directo. Elige otro proveedor en Ajustes → Voz a texto.",+ "commands": "Comandos"},"tools": {"search_notesName": "Buscar notas",@@ -4544,9 +4617,7 @@"conversationSelector": "Cambiar conversación","history": "Historial","quickActions": "Acciones rápidas",- "generateSummary": "Generar resumen",- "makeTodos": "Crear tareas",- "createOutline": "Crear esquema"+ "generateSummary": "Generar resumen"},"transcriptionPreview": {"label": "Vista previa",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 663cae5db..2bd29242f 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -3126,7 +3126,7 @@"sidebar": {"newNote": "Nouvelle note","searchNotes": "Rechercher des notes",- "actions": "Actions"+ "templatesAndActions": "Modèles et actions"},"spaces": {"privateSpaces": "Notes privées",@@ -3510,8 +3510,8 @@"done": "Terminé","chunkProgress": "Partie {{step}} sur {{total}}","emptyReply": "Le modèle a renvoyé une réponse vide. Réessayez ou choisissez un autre modèle.",+ "allActions": "Toutes les actions","manage": "Gérer les actions...",- "manageTitle": "Actions personnalisées","addAction": "Nouvelle action","editAction": "Modifier l'action","namePlaceholder": "Nom de l'action",@@ -3525,8 +3525,6 @@"promptLabel": "Instruction","emptyEditorTitle": "Sélectionner une action","emptyEditorDescription": "Choisissez une action dans la liste ou créez-en une nouvelle",- "runAction": "Exécuter {{name}}",- "selectAction": "Sélectionner l'action","builtin": {"generateNotes": {"name": "Générer des notes",@@ -3538,15 +3536,89 @@"cta": "Rédiger un e-mail de suivi"},"detailedNotes": {- "name": "Notes détaillées",+ "name": "Résumé IA","description": "Des notes de réunion précises et complètes avec décisions et actions"+ },+ "makeTodos": {+ "name": "Créer des tâches",+ "description": "Lister chaque tâche et son responsable dans le chat"+ },+ "createOutline": {+ "name": "Créer un plan",+ "description": "Structurer les sujets de la note dans le chat"+ },+ "oneOnOne": {+ "name": "1:1",+ "description": "Points, retours, évolution et prochaines étapes d'un entretien individuel"+ },+ "standUp": {+ "name": "Stand-up",+ "description": "Avancement, plans et blocages de chacun"+ },+ "salesCall": {+ "name": "Appel commercial",+ "description": "Besoins, objections, budget et processus de décision"+ },+ "userInterview": {+ "name": "Entretien utilisateur",+ "description": "Méthode de travail, difficultés, réactions et citations d'un participant"+ },+ "shorten": {+ "name": "Raccourcir",+ "description": "Réduire le résumé de moitié environ",+ "cta": "Raccourcir le résumé"+ },+ "addTldr": {+ "name": "Ajouter un TL;DR",+ "description": "Placer un TL;DR de deux ou trois phrases en tête du résumé",+ "cta": "Ajouter un TL;DR"+ },+ "slackUpdate": {+ "name": "Point Slack",+ "description": "Rédiger un court point d'équipe à publier sur Slack",+ "cta": "Rédiger un point Slack"}},"errors": {"noModel": "Aucun modèle IA sélectionné. Configurez-en un dans les Paramètres.","actionFailed": "L'action a échoué",- "noEndpoint": "Aucune URL de serveur auto-hébergé définie. Configurez-en une dans les Paramètres."- }+ "noEndpoint": "Aucune URL de serveur auto-hébergé définie. Configurez-en une dans les Paramètres.",+ "outputTruncated": "Le modèle d'IA a manqué de place avant d'avoir fini, la note reste donc inchangée.",+ "nothingToSummarize": "Cette note n'a encore rien à résumer, donc le résumé IA est resté tel quel.",+ "saveFailed": "Enregistrement impossible. Vérifiez que rien n'est trop long, puis réessayez."+ },+ "tab": "Actions",+ "output": {+ "auto": "Auto",+ "chat": "Chat",+ "summary": "Résumé IA",+ "chatHint": "Répond dans le chat de la note et laisse le résumé IA tel quel.",+ "summaryHint": "Modifie le résumé IA de la note, ou le rédige à partir de la transcription s'il n'y en a pas encore.",+ "autoHint": "Lit le prompt à l'enregistrement et choisit le chat ou le résumé IA."+ },+ "applied": "Résumé IA mis à jour avec {{name}}"+ },+ "templates": {+ "tab": "Modèles",+ "managerTitle": "Modèles et actions",+ "manage": "Gérer les modèles...",+ "select": "Choisir un modèle",+ "addTemplate": "Nouveau modèle",+ "editTemplate": "Modifier le modèle",+ "namePlaceholder": "Nom du modèle",+ "contextLabel": "Contexte",+ "contextPlaceholder": "De quel type de réunion s'agit-il, et sur quoi le résumé doit-il se concentrer ?",+ "sectionsLabel": "Sections",+ "addSection": "Ajouter une section",+ "sectionHeadingPlaceholder": "Titre de la section",+ "sectionInstructionPlaceholder": "Que contient cette section ?",+ "moveSectionUp": "Monter la section",+ "moveSectionDown": "Descendre la section",+ "removeSection": "Supprimer la section",+ "noSectionsHint": "Sans sections, le contexte constitue toute la consigne du résumé.",+ "noTemplates": "Aucun modèle pour l'instant",+ "emptyEditorTitle": "Sélectionner un modèle",+ "emptyEditorDescription": "Choisissez un modèle dans la liste ou créez-en un nouveau"},"onboarding": {"llm": {@@ -3554,13 +3626,13 @@"description": "Les actions utilisent l'IA pour transformer vos notes. Configurez un modèle de langage pour commencer.","configured": "Modèle IA configuré"},- "actions": {- "title": "Actions alimentées par l'IA",- "description": "Les actions transforment vos notes : nettoyage des transcriptions, résumés de réunions et bien plus. Utilisez les actions intégrées ou créez les vôtres.",- "builtInLabel": "Intégrée",- "createTitle": "Créez votre propre action",- "createDescription": "Définissez une action personnalisée avec votre propre prompt IA. Vous pourrez toujours la modifier ou en ajouter d'autres dans les paramètres.",- "created": "Créée !"+ "templates": {+ "title": "Modèles et actions",+ "description": "Les modèles façonnent votre résumé IA, des notes de réunion détaillées aux sections que vous définissez. Les actions s'exécutent sur une note, comme la rédaction d'un e-mail de suivi dans le chat.",+ "builtInLabel": "Vos modèles",+ "createTitle": "Créez votre propre modèle",+ "createDescription": "Décrivez le résumé souhaité. Vous pourrez ajouter des sections, d'autres modèles et des actions plus tard.",+ "created": "Créé !"},"getStarted": "Commencer","systemAudio": {@@ -3855,7 +3927,8 @@"thinking": "Réflexion...","typeMessage": "Écrivez un message...","send": "Envoyer",- "voiceDraftStreamingOnly": "La saisie vocale n'est pas disponible avec votre fournisseur de transcription : il ne prend en charge que la dictée en direct. Choisissez un autre fournisseur dans Réglages → Parole en texte."+ "voiceDraftStreamingOnly": "La saisie vocale n'est pas disponible avec votre fournisseur de transcription : il ne prend en charge que la dictée en direct. Choisissez un autre fournisseur dans Réglages → Parole en texte.",+ "commands": "Commandes"},"tools": {"search_notesName": "Rechercher des notes",@@ -4620,9 +4693,7 @@"conversationSelector": "Changer de conversation","history": "Historique","quickActions": "Actions rapides",- "generateSummary": "Générer un résumé",- "makeTodos": "Créer des tâches",- "createOutline": "Créer un plan"+ "generateSummary": "Générer un résumé"},"transcriptionPreview": {"label": "Aperçu",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex cccf600e6..323dff24d 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -2774,7 +2774,7 @@"sidebar": {"newNote": "Nuova nota","searchNotes": "Cerca note",- "actions": "Azioni"+ "templatesAndActions": "Modelli e azioni"},"spaces": {"privateSpaces": "Note private",@@ -3139,8 +3139,8 @@"showInFileManager": "Mostra in {{manager}}"},"actions": {+ "allActions": "Tutte le azioni","manage": "Gestisci azioni...",- "manageTitle": "Azioni personalizzate","addAction": "Nuova azione","editAction": "Modifica azione","namePlaceholder": "Nome dell'azione",@@ -3154,8 +3154,6 @@"promptLabel": "Istruzione","emptyEditorTitle": "Seleziona un'azione","emptyEditorDescription": "Scegli un'azione dall'elenco o creane una nuova",- "runAction": "Esegui {{name}}",- "selectAction": "Seleziona azione","done": "Fatto","chunkProgress": "Parte {{step}} di {{total}}","emptyReply": "Il modello ha restituito una risposta vuota. Riprova o scegli un altro modello.",@@ -3170,15 +3168,89 @@"cta": "Scrivi un'email di follow-up"},"detailedNotes": {- "name": "Note dettagliate",+ "name": "Riepilogo AI","description": "Note di riunione accurate e complete con decisioni e azioni"+ },+ "makeTodos": {+ "name": "Crea attività",+ "description": "Elenca ogni attività e il suo responsabile nella chat"+ },+ "createOutline": {+ "name": "Crea scaletta",+ "description": "Organizza gli argomenti della nota nella chat"+ },+ "oneOnOne": {+ "name": "1:1",+ "description": "Aggiornamenti, feedback, crescita e prossimi passi di un incontro individuale"+ },+ "standUp": {+ "name": "Stand-up",+ "description": "Progressi, piani e blocchi di ciascuno"+ },+ "salesCall": {+ "name": "Chiamata di vendita",+ "description": "Esigenze, obiezioni, budget e processo decisionale"+ },+ "userInterview": {+ "name": "Intervista utente",+ "description": "Flusso di lavoro, problemi, reazioni e citazioni di un partecipante"+ },+ "shorten": {+ "name": "Accorcia",+ "description": "Rendi il riepilogo lungo circa la metà",+ "cta": "Accorcia il riepilogo"+ },+ "addTldr": {+ "name": "Aggiungi TL;DR",+ "description": "Metti un TL;DR di due o tre frasi all'inizio del riepilogo",+ "cta": "Aggiungi un TL;DR"+ },+ "slackUpdate": {+ "name": "Aggiornamento Slack",+ "description": "Scrivi un breve aggiornamento per il team da pubblicare su Slack",+ "cta": "Scrivi un aggiornamento Slack"}},"errors": {"noModel": "Nessun modello IA selezionato. Configurane uno nelle Impostazioni.","actionFailed": "Azione non riuscita",- "noEndpoint": "Nessun URL del server self-hosted impostato. Configurane uno nelle Impostazioni."- }+ "noEndpoint": "Nessun URL del server self-hosted impostato. Configurane uno nelle Impostazioni.",+ "outputTruncated": "Il modello AI ha esaurito lo spazio prima di finire, quindi la nota è rimasta com'era.",+ "nothingToSummarize": "Questa nota non ha ancora nulla da riassumere, quindi il riepilogo AI è rimasto invariato.",+ "saveFailed": "Impossibile salvare. Controlla che nulla sia troppo lungo e riprova."+ },+ "tab": "Azioni",+ "output": {+ "auto": "Automatico",+ "chat": "Chat",+ "summary": "Riepilogo AI",+ "chatHint": "Risponde nella chat della nota e lascia invariato il riepilogo AI.",+ "summaryHint": "Modifica il riepilogo AI della nota, oppure lo scrive dalla trascrizione se non c'è ancora.",+ "autoHint": "Legge il prompt al salvataggio e sceglie la chat o il riepilogo AI."+ },+ "applied": "Riepilogo AI aggiornato con {{name}}"+ },+ "templates": {+ "tab": "Modelli",+ "managerTitle": "Modelli e azioni",+ "manage": "Gestisci modelli...",+ "select": "Scegli modello",+ "addTemplate": "Nuovo modello",+ "editTemplate": "Modifica modello",+ "namePlaceholder": "Nome del modello",+ "contextLabel": "Contesto",+ "contextPlaceholder": "Che tipo di riunione è e su cosa deve concentrarsi il riepilogo?",+ "sectionsLabel": "Sezioni",+ "addSection": "Aggiungi sezione",+ "sectionHeadingPlaceholder": "Titolo della sezione",+ "sectionInstructionPlaceholder": "Cosa va in questa sezione?",+ "moveSectionUp": "Sposta la sezione su",+ "moveSectionDown": "Sposta la sezione giù",+ "removeSection": "Rimuovi sezione",+ "noSectionsHint": "Senza sezioni, il contesto è l'intera istruzione per il riepilogo.",+ "noTemplates": "Nessun modello ancora",+ "emptyEditorTitle": "Seleziona un modello",+ "emptyEditorDescription": "Scegli un modello dall'elenco o creane uno nuovo"},"empty": {"title": "Ancora nessuna nota qui",@@ -3202,13 +3274,13 @@"description": "Le azioni usano l'IA per trasformare le tue note. Configura un modello linguistico per iniziare.","configured": "Modello IA configurato"},- "actions": {- "title": "Azioni basate sull'IA",- "description": "Le azioni trasformano le tue note: correggono le trascrizioni, riassumono le riunioni e altro ancora. Usa le azioni integrate o creane di tue.",- "builtInLabel": "Integrata",- "createTitle": "Crea la tua azione",- "createDescription": "Definisci un'azione personalizzata con il tuo prompt IA. Puoi sempre modificarle o aggiungerne altre nelle impostazioni.",- "created": "Creata!"+ "templates": {+ "title": "Modelli e azioni",+ "description": "I modelli danno forma al tuo riepilogo AI, dalle note di riunione dettagliate alle sezioni che definisci tu. Le azioni si eseguono su una nota, come scrivere un'email di follow-up nella chat.",+ "builtInLabel": "I tuoi modelli",+ "createTitle": "Crea il tuo modello",+ "createDescription": "Descrivi il riepilogo che desideri. Puoi aggiungere sezioni, altri modelli e azioni in seguito.",+ "created": "Creato!"},"getStarted": "Inizia","systemAudio": {@@ -3684,7 +3756,8 @@"thinking": "Pensiero...","typeMessage": "Scrivi un messaggio...","send": "Invia",- "voiceDraftStreamingOnly": "L'input vocale non è disponibile con il tuo provider di trascrizione: supporta solo la dettatura dal vivo. Scegli un altro provider in Impostazioni → Da voce a testo."+ "voiceDraftStreamingOnly": "L'input vocale non è disponibile con il tuo provider di trascrizione: supporta solo la dettatura dal vivo. Scegli un altro provider in Impostazioni → Da voce a testo.",+ "commands": "Comandi"},"tools": {"search_notesName": "Cerca nelle note",@@ -4544,9 +4617,7 @@"conversationSelector": "Cambia conversazione","history": "Cronologia","quickActions": "Azioni rapide",- "generateSummary": "Genera riepilogo",- "makeTodos": "Crea attività",- "createOutline": "Crea scaletta"+ "generateSummary": "Genera riepilogo"},"transcriptionPreview": {"label": "Anteprima",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex ed6ca1205..2292c8c04 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -2702,7 +2702,7 @@"sidebar": {"newNote": "新しいノート","searchNotes": "ノートを検索",- "actions": "アクション"+ "templatesAndActions": "テンプレートとアクション"},"spaces": {"privateSpaces": "プライベートノート",@@ -2921,8 +2921,8 @@"showInFileManager": "{{manager}}で表示"},"actions": {+ "allActions": "すべてのアクション","manage": "アクションを管理...",- "manageTitle": "カスタムアクション","addAction": "新しいアクション","editAction": "アクションを編集","namePlaceholder": "アクション名",@@ -2936,8 +2936,6 @@"promptLabel": "プロンプト","emptyEditorTitle": "アクションを選択","emptyEditorDescription": "リストからアクションを選択するか、新しく作成してください",- "runAction": "{{name}} を実行",- "selectAction": "アクションを選択","done": "完了","chunkProgress": "パート {{step}} / {{total}}","emptyReply": "モデルから空の応答が返されました。もう一度お試しいただくか、別のモデルを選択してください。",@@ -2952,15 +2950,89 @@"cta": "フォローアップメールを作成"},"detailedNotes": {- "name": "詳細ノート",+ "name": "AI要約","description": "決定事項とアクションを含む正確で網羅的な会議ノート"+ },+ "makeTodos": {+ "name": "ToDoを作成",+ "description": "すべてのToDoと担当者をチャットに一覧表示"+ },+ "createOutline": {+ "name": "アウトラインを作成",+ "description": "ノートのトピックをチャットでアウトライン化"+ },+ "oneOnOne": {+ "name": "1on1",+ "description": "1on1での近況、フィードバック、成長、次のステップ"+ },+ "standUp": {+ "name": "スタンドアップ",+ "description": "各メンバーの進捗、予定、ブロッカー"+ },+ "salesCall": {+ "name": "商談",+ "description": "ニーズ、懸念点、予算、意思決定プロセス"+ },+ "userInterview": {+ "name": "ユーザーインタビュー",+ "description": "参加者のワークフロー、課題、反応、発言の引用"+ },+ "shorten": {+ "name": "短くする",+ "description": "要約を約半分の長さにします",+ "cta": "要約を短くする"+ },+ "addTldr": {+ "name": "TL;DRを追加",+ "description": "要約の先頭に2〜3文のTL;DRを追加します",+ "cta": "TL;DRを追加"+ },+ "slackUpdate": {+ "name": "Slack用の共有",+ "description": "Slackに投稿するチーム向けの短い共有文を作成します",+ "cta": "Slack用の共有を書く"}},"errors": {"noModel": "AIモデルが選択されていません。設定で構成してください。","actionFailed": "アクションに失敗しました",- "noEndpoint": "セルフホストサーバーの URL が設定されていません。設定で構成してください。"- }+ "noEndpoint": "セルフホストサーバーの URL が設定されていません。設定で構成してください。",+ "outputTruncated": "AIモデルが出力の上限に達して最後まで書けなかったため、ノートは変更されていません。",+ "nothingToSummarize": "このノートにはまだ要約できる内容がないため、AI要約はそのままです。",+ "saveFailed": "保存できませんでした。長すぎる項目がないか確認して、もう一度お試しください。"+ },+ "tab": "アクション",+ "output": {+ "auto": "自動",+ "chat": "チャット",+ "summary": "AI要約",+ "chatHint": "ノートのチャットで回答し、AI要約はそのまま残します。",+ "summaryHint": "ノートのAI要約を編集します。要約がまだない場合は文字起こしから作成します。",+ "autoHint": "保存時にプロンプトを読み取り、チャットかAI要約かを選びます。"+ },+ "applied": "{{name}}でAI要約を更新しました"+ },+ "templates": {+ "tab": "テンプレート",+ "managerTitle": "テンプレートとアクション",+ "manage": "テンプレートを管理...",+ "select": "テンプレートを選択",+ "addTemplate": "新しいテンプレート",+ "editTemplate": "テンプレートを編集",+ "namePlaceholder": "テンプレート名",+ "contextLabel": "コンテキスト",+ "contextPlaceholder": "どのような会議で、要約では何に重点を置くべきですか?",+ "sectionsLabel": "セクション",+ "addSection": "セクションを追加",+ "sectionHeadingPlaceholder": "セクションの見出し",+ "sectionInstructionPlaceholder": "このセクションに何を書きますか?",+ "moveSectionUp": "セクションを上に移動",+ "moveSectionDown": "セクションを下に移動",+ "removeSection": "セクションを削除",+ "noSectionsHint": "セクションがない場合、コンテキストが要約への指示のすべてになります。",+ "noTemplates": "テンプレートはまだありません",+ "emptyEditorTitle": "テンプレートを選択",+ "emptyEditorDescription": "リストからテンプレートを選択するか、新しく作成してください"},"empty": {"title": "まだノートがありません",@@ -3130,12 +3202,12 @@"description": "アクションは AI を使ってノートを変換します。言語モデルを設定して始めましょう。","configured": "AI モデルが設定されました"},- "actions": {- "title": "AI アクション",- "description": "アクションでノートを変換できます — 文字起こしの整理、議事録の要約など。組み込みアクションを使うか、独自のアクションを作成できます。",- "builtInLabel": "組み込み",- "createTitle": "独自のアクションを作成",- "createDescription": "独自の AI プロンプトでカスタムアクションを定義できます。設定からいつでも編集・追加できます。",+ "templates": {+ "title": "テンプレートとアクション",+ "description": "テンプレートでAI要約の形を決められます — 詳しい議事録から独自のセクションまで。アクションはノートに対して実行され、たとえばチャットでフォローアップメールを下書きできます。",+ "builtInLabel": "あなたのテンプレート",+ "createTitle": "独自のテンプレートを作成",+ "createDescription": "必要な要約を説明してください。セクションや他のテンプレート、アクションは後から追加できます。","created": "作成しました!"},"getStarted": "始める",@@ -3684,7 +3756,8 @@"thinking": "考え中...","typeMessage": "メッセージを入力...","send": "送信",- "voiceDraftStreamingOnly": "現在の文字起こしプロバイダーはライブ音声入力のみに対応しているため、音声入力は利用できません。設定 → 音声テキスト変換 で別のプロバイダーを選択してください。"+ "voiceDraftStreamingOnly": "現在の文字起こしプロバイダーはライブ音声入力のみに対応しているため、音声入力は利用できません。設定 → 音声テキスト変換 で別のプロバイダーを選択してください。",+ "commands": "コマンド"},"tools": {"search_notesName": "ノートを検索",@@ -4544,9 +4617,7 @@"conversationSelector": "会話を切り替え","history": "履歴","quickActions": "クイックアクション",- "generateSummary": "要約を作成",- "makeTodos": "ToDoを作成",- "createOutline": "アウトラインを作成"+ "generateSummary": "要約を作成"},"transcriptionPreview": {"label": "プレビュー",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex 0cfa62d87..985e120a5 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -2774,7 +2774,7 @@"sidebar": {"newNote": "Nova nota","searchNotes": "Pesquisar notas",- "actions": "Ações"+ "templatesAndActions": "Modelos e ações"},"spaces": {"privateSpaces": "Notas privadas",@@ -3139,8 +3139,8 @@"showInFileManager": "Mostrar no {{manager}}"},"actions": {+ "allActions": "Todas as ações","manage": "Gerenciar ações...",- "manageTitle": "Ações personalizadas","addAction": "Nova ação","editAction": "Editar ação","namePlaceholder": "Nome da ação",@@ -3154,8 +3154,6 @@"promptLabel": "Instrução","emptyEditorTitle": "Selecionar ação","emptyEditorDescription": "Escolha uma ação da lista ou crie uma nova",- "runAction": "Executar {{name}}",- "selectAction": "Selecionar ação","done": "Concluído","chunkProgress": "Parte {{step}} de {{total}}","emptyReply": "O modelo retornou uma resposta vazia. Tente novamente ou escolha outro modelo.",@@ -3170,15 +3168,89 @@"cta": "Redigir e-mail de acompanhamento"},"detailedNotes": {- "name": "Notas detalhadas",+ "name": "Resumo com IA","description": "Notas de reunião precisas e completas com decisões e ações"+ },+ "makeTodos": {+ "name": "Criar tarefas",+ "description": "Lista cada tarefa e seu responsável no chat"+ },+ "createOutline": {+ "name": "Criar esboço",+ "description": "Organiza os tópicos da nota no chat"+ },+ "oneOnOne": {+ "name": "1:1",+ "description": "Atualizações, feedback, desenvolvimento e próximos passos de uma reunião individual"+ },+ "standUp": {+ "name": "Stand-up",+ "description": "Progresso, planos e bloqueios de cada pessoa"+ },+ "salesCall": {+ "name": "Chamada de vendas",+ "description": "Necessidades, objeções, orçamento e processo de decisão"+ },+ "userInterview": {+ "name": "Entrevista com usuário",+ "description": "Fluxo de trabalho, dificuldades, reações e citações de um participante"+ },+ "shorten": {+ "name": "Encurtar",+ "description": "Deixe o resumo com cerca de metade do tamanho",+ "cta": "Encurtar o resumo"+ },+ "addTldr": {+ "name": "Adicionar TL;DR",+ "description": "Coloque um TL;DR de duas ou três frases no início do resumo",+ "cta": "Adicionar um TL;DR"+ },+ "slackUpdate": {+ "name": "Atualização no Slack",+ "description": "Escreva uma breve atualização para a equipe no Slack",+ "cta": "Escrever uma atualização no Slack"}},"errors": {"noModel": "Nenhum modelo de IA selecionado. Configure um nas Configurações.","actionFailed": "A ação falhou",- "noEndpoint": "Nenhum URL de servidor auto-hospedado definido. Configure um nas Configurações."- }+ "noEndpoint": "Nenhum URL de servidor auto-hospedado definido. Configure um nas Configurações.",+ "outputTruncated": "O modelo de IA ficou sem espaço antes de terminar, então a nota ficou como estava.",+ "nothingToSummarize": "Esta nota ainda não tem nada para resumir, então o resumo com IA ficou como estava.",+ "saveFailed": "Não foi possível salvar. Verifique se nada está longo demais e tente novamente."+ },+ "tab": "Ações",+ "output": {+ "auto": "Automático",+ "chat": "Chat",+ "summary": "Resumo com IA",+ "chatHint": "Responde no chat da nota e deixa o resumo com IA como está.",+ "summaryHint": "Edita o resumo com IA da nota, ou escreve um a partir da transcrição se ainda não houver.",+ "autoHint": "Lê o prompt ao salvar e escolhe o chat ou o resumo com IA."+ },+ "applied": "Resumo com IA atualizado com {{name}}"+ },+ "templates": {+ "tab": "Modelos",+ "managerTitle": "Modelos e ações",+ "manage": "Gerenciar modelos...",+ "select": "Escolher modelo",+ "addTemplate": "Novo modelo",+ "editTemplate": "Editar modelo",+ "namePlaceholder": "Nome do modelo",+ "contextLabel": "Contexto",+ "contextPlaceholder": "Que tipo de reunião é esta e em que o resumo deve se concentrar?",+ "sectionsLabel": "Seções",+ "addSection": "Adicionar seção",+ "sectionHeadingPlaceholder": "Título da seção",+ "sectionInstructionPlaceholder": "O que entra nesta seção?",+ "moveSectionUp": "Mover seção para cima",+ "moveSectionDown": "Mover seção para baixo",+ "removeSection": "Remover seção",+ "noSectionsHint": "Sem seções, o contexto é a instrução completa para o resumo.",+ "noTemplates": "Nenhum modelo ainda",+ "emptyEditorTitle": "Selecionar modelo",+ "emptyEditorDescription": "Escolha um modelo da lista ou crie um novo"},"empty": {"title": "Ainda não há notas aqui",@@ -3202,13 +3274,13 @@"description": "As ações usam IA para transformar suas notas. Configure um modelo de linguagem para começar.","configured": "Modelo de IA configurado"},- "actions": {- "title": "Ações com IA",- "description": "As ações transformam suas notas — limpam transcrições, resumem reuniões e muito mais. Use ações integradas ou crie as suas.",- "builtInLabel": "Integrada",- "createTitle": "Crie sua própria ação",- "createDescription": "Defina uma ação personalizada com seu próprio prompt de IA. Você sempre pode editar ou adicionar mais nas configurações.",- "created": "Criada!"+ "templates": {+ "title": "Modelos e ações",+ "description": "Os modelos dão forma ao seu resumo com IA, de notas de reunião detalhadas a seções que você define. As ações rodam sobre uma nota, como escrever um e-mail de acompanhamento no chat.",+ "builtInLabel": "Seus modelos",+ "createTitle": "Crie seu próprio modelo",+ "createDescription": "Descreva o resumo que você quer. Você pode adicionar seções, mais modelos e ações depois.",+ "created": "Criado!"},"getStarted": "Começar","systemAudio": {@@ -3684,7 +3756,8 @@"thinking": "Pensando...","typeMessage": "Digite uma mensagem...","send": "Enviar",- "voiceDraftStreamingOnly": "A entrada por voz não está disponível com seu provedor de transcrição: ele só suporta ditado ao vivo. Escolha outro provedor em Configurações → Fala para texto."+ "voiceDraftStreamingOnly": "A entrada por voz não está disponível com seu provedor de transcrição: ele só suporta ditado ao vivo. Escolha outro provedor em Configurações → Fala para texto.",+ "commands": "Comandos"},"tools": {"search_notesName": "Pesquisar notas",@@ -4544,9 +4617,7 @@"conversationSelector": "Trocar conversa","history": "Histórico","quickActions": "Ações rápidas",- "generateSummary": "Gerar resumo",- "makeTodos": "Criar tarefas",- "createOutline": "Criar esboço"+ "generateSummary": "Gerar resumo"},"transcriptionPreview": {"label": "Pré-visualização",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 1c4093db0..c2e198291 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -2790,7 +2790,7 @@"sidebar": {"newNote": "Новая заметка","searchNotes": "Поиск заметок",- "actions": "Действия"+ "templatesAndActions": "Шаблоны и действия"},"spaces": {"privateSpaces": "Личные заметки",@@ -3159,8 +3159,8 @@"showInFileManager": "Показать в {{manager}}"},"actions": {+ "allActions": "Все действия","manage": "Управление действиями...",- "manageTitle": "Пользовательские действия","addAction": "Новое действие","editAction": "Редактировать действие","namePlaceholder": "Название действия",@@ -3174,8 +3174,6 @@"promptLabel": "Инструкция","emptyEditorTitle": "Выберите действие","emptyEditorDescription": "Выберите действие из списка или создайте новое",- "runAction": "Запустить {{name}}",- "selectAction": "Выбрать действие","done": "Готово","chunkProgress": "Часть {{step}} из {{total}}","emptyReply": "Модель вернула пустой ответ. Попробуйте снова или выберите другую модель.",@@ -3190,15 +3188,89 @@"cta": "Составить письмо по итогам"},"detailedNotes": {- "name": "Подробные заметки",+ "name": "ИИ-сводка","description": "Точные и полные заметки по встрече с решениями и задачами"+ },+ "makeTodos": {+ "name": "Составить список дел",+ "description": "Перечислить в чате все задачи и их ответственных"+ },+ "createOutline": {+ "name": "Создать план",+ "description": "Составить в чате план тем заметки"+ },+ "oneOnOne": {+ "name": "1:1",+ "description": "Новости, обратная связь, развитие и следующие шаги из встречи один на один"+ },+ "standUp": {+ "name": "Стендап",+ "description": "Прогресс, планы и блокеры каждого"+ },+ "salesCall": {+ "name": "Звонок по продажам",+ "description": "Потребности, возражения, бюджет и процесс принятия решения"+ },+ "userInterview": {+ "name": "Интервью с пользователем",+ "description": "Рабочий процесс, проблемы, реакции и цитаты участника"+ },+ "shorten": {+ "name": "Сократить",+ "description": "Сделать сводку примерно вдвое короче",+ "cta": "Сократить сводку"+ },+ "addTldr": {+ "name": "Добавить TL;DR",+ "description": "Добавить в начало сводки TL;DR из двух-трёх предложений",+ "cta": "Добавить TL;DR"+ },+ "slackUpdate": {+ "name": "Апдейт для Slack",+ "description": "Написать короткий апдейт для команды в Slack",+ "cta": "Написать апдейт для Slack"}},"errors": {"noModel": "Модель ИИ не выбрана. Настройте её в разделе Настройки.","actionFailed": "Действие не выполнено",- "noEndpoint": "URL собственного сервера не задан. Настройте его в разделе Настройки."- }+ "noEndpoint": "URL собственного сервера не задан. Настройте его в разделе Настройки.",+ "outputTruncated": "Модели ИИ не хватило места, чтобы закончить, поэтому заметка осталась прежней.",+ "nothingToSummarize": "В этой заметке пока нечего обобщать, поэтому ИИ-сводка осталась без изменений.",+ "saveFailed": "Не удалось сохранить. Проверьте, что ничего не слишком длинное, и попробуйте снова."+ },+ "tab": "Действия",+ "output": {+ "auto": "Авто",+ "chat": "Чат",+ "summary": "ИИ-сводка",+ "chatHint": "Отвечает в чате заметки и не меняет ИИ-сводку.",+ "summaryHint": "Редактирует ИИ-сводку заметки или создаёт её из транскрипции, если сводки ещё нет.",+ "autoHint": "При сохранении читает промпт и выбирает чат или ИИ-сводку."+ },+ "applied": "ИИ-сводка обновлена с помощью «{{name}}»"+ },+ "templates": {+ "tab": "Шаблоны",+ "managerTitle": "Шаблоны и действия",+ "manage": "Управление шаблонами...",+ "select": "Выбрать шаблон",+ "addTemplate": "Новый шаблон",+ "editTemplate": "Редактировать шаблон",+ "namePlaceholder": "Название шаблона",+ "contextLabel": "Контекст",+ "contextPlaceholder": "Что это за встреча и на чём должна сосредоточиться сводка?",+ "sectionsLabel": "Разделы",+ "addSection": "Добавить раздел",+ "sectionHeadingPlaceholder": "Заголовок раздела",+ "sectionInstructionPlaceholder": "Что должно быть в этом разделе?",+ "moveSectionUp": "Переместить раздел вверх",+ "moveSectionDown": "Переместить раздел вниз",+ "removeSection": "Удалить раздел",+ "noSectionsHint": "Без разделов контекст — это вся инструкция для сводки.",+ "noTemplates": "Шаблонов пока нет",+ "emptyEditorTitle": "Выберите шаблон",+ "emptyEditorDescription": "Выберите шаблон из списка или создайте новый"},"empty": {"title": "Нет заметок",@@ -3222,12 +3294,12 @@"description": "Действия используют ИИ для обработки ваших заметок. Настройте языковую модель, чтобы начать.","configured": "Модель ИИ настроена"},- "actions": {- "title": "Действия на основе ИИ",- "description": "Действия преобразуют ваши заметки — очищают транскрипции, создают резюме встреч и многое другое. Используйте встроенные действия или создавайте свои.",- "builtInLabel": "Встроенное",- "createTitle": "Создайте своё действие",- "createDescription": "Определите пользовательское действие с собственным промптом для ИИ. Вы всегда сможете изменить или добавить новые в настройках.",+ "templates": {+ "title": "Шаблоны и действия",+ "description": "Шаблоны определяют вид ИИ-сводки — от подробных заметок о встрече до разделов, которые задаёте вы. Действия выполняются над заметкой, например черновик письма после встречи в чате.",+ "builtInLabel": "Ваши шаблоны",+ "createTitle": "Создайте свой шаблон",+ "createDescription": "Опишите, какая сводка вам нужна. Разделы, другие шаблоны и действия можно добавить позже.","created": "Создано!"},"getStarted": "Начать",@@ -3728,7 +3800,8 @@"thinking": "Думаю...","typeMessage": "Введите сообщение...","send": "Отправить",- "voiceDraftStreamingOnly": "Голосовой ввод недоступен с вашим провайдером транскрипции: он поддерживает только живую диктовку. Выберите другого провайдера в Настройках → Речь в текст."+ "voiceDraftStreamingOnly": "Голосовой ввод недоступен с вашим провайдером транскрипции: он поддерживает только живую диктовку. Выберите другого провайдера в Настройках → Речь в текст.",+ "commands": "Команды"},"tools": {"search_notesName": "Поиск заметок",@@ -4588,9 +4661,7 @@"conversationSelector": "Сменить беседу","history": "История","quickActions": "Быстрые действия",- "generateSummary": "Создать сводку",- "makeTodos": "Составить список дел",- "createOutline": "Создать план"+ "generateSummary": "Создать сводку"},"transcriptionPreview": {"label": "Предпросмотр",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 4c5ee45f6..fd4e8de1a 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -2774,7 +2774,7 @@"sidebar": {"newNote": "新建笔记","searchNotes": "搜索笔记",- "actions": "操作"+ "templatesAndActions": "模板和操作"},"spaces": {"privateSpaces": "私人笔记",@@ -3139,8 +3139,8 @@"showInFileManager": "在{{manager}}中显示"},"actions": {+ "allActions": "全部操作","manage": "管理操作...",- "manageTitle": "自定义操作","addAction": "新建操作","editAction": "编辑操作","namePlaceholder": "操作名称",@@ -3154,8 +3154,6 @@"promptLabel": "提示词","emptyEditorTitle": "选择操作","emptyEditorDescription": "从列表中选择一个操作或创建新操作",- "runAction": "运行 {{name}}",- "selectAction": "选择操作","done": "完成","chunkProgress": "第 {{step}} 部分,共 {{total}} 部分","emptyReply": "模型返回了空回复。请重试,或选择其他模型。",@@ -3170,15 +3168,89 @@"cta": "草拟跟进邮件"},"detailedNotes": {- "name": "详细笔记",+ "name": "AI 摘要","description": "准确、全面的会议笔记,包含决策和行动项"+ },+ "makeTodos": {+ "name": "创建待办事项",+ "description": "在聊天中列出每项待办及其负责人"+ },+ "createOutline": {+ "name": "创建大纲",+ "description": "在聊天中为笔记的主题列出大纲"+ },+ "oneOnOne": {+ "name": "1 对 1",+ "description": "一对一会议中的近况、反馈、成长和后续步骤"+ },+ "standUp": {+ "name": "站会",+ "description": "每个人的进展、计划和阻碍"+ },+ "salesCall": {+ "name": "销售通话",+ "description": "需求、异议、预算和决策流程"+ },+ "userInterview": {+ "name": "用户访谈",+ "description": "参与者的工作流程、痛点、反应和原话"+ },+ "shorten": {+ "name": "精简",+ "description": "把摘要缩短到大约一半",+ "cta": "精简摘要"+ },+ "addTldr": {+ "name": "添加 TL;DR",+ "description": "在摘要开头加上两三句话的 TL;DR",+ "cta": "添加 TL;DR"+ },+ "slackUpdate": {+ "name": "Slack 更新",+ "description": "写一条发到 Slack 的简短团队更新",+ "cta": "写一条 Slack 更新"}},"errors": {"noModel": "未选择 AI 模型。请在设置中配置。","actionFailed": "操作失败",- "noEndpoint": "未设置自托管服务器 URL。请在设置中配置。"- }+ "noEndpoint": "未设置自托管服务器 URL。请在设置中配置。",+ "outputTruncated": "AI 模型在完成之前就用完了输出空间,因此笔记保持不变。",+ "nothingToSummarize": "这条笔记还没有可以总结的内容,因此 AI 摘要保持不变。",+ "saveFailed": "无法保存。请检查是否有内容过长,然后重试。"+ },+ "tab": "操作",+ "output": {+ "auto": "自动",+ "chat": "聊天",+ "summary": "AI 摘要",+ "chatHint": "在笔记的聊天中回复,AI 摘要保持不变。",+ "summaryHint": "编辑笔记的 AI 摘要;如果还没有摘要,就根据转录内容生成一份。",+ "autoHint": "保存时读取提示词,并选择聊天或 AI 摘要。"+ },+ "applied": "已使用 {{name}} 更新 AI 摘要"+ },+ "templates": {+ "tab": "模板",+ "managerTitle": "模板和操作",+ "manage": "管理模板...",+ "select": "选择模板",+ "addTemplate": "新建模板",+ "editTemplate": "编辑模板",+ "namePlaceholder": "模板名称",+ "contextLabel": "背景",+ "contextPlaceholder": "这是什么类型的会议?摘要应侧重什么?",+ "sectionsLabel": "章节",+ "addSection": "添加章节",+ "sectionHeadingPlaceholder": "章节标题",+ "sectionInstructionPlaceholder": "这个章节写什么?",+ "moveSectionUp": "上移章节",+ "moveSectionDown": "下移章节",+ "removeSection": "移除章节",+ "noSectionsHint": "没有章节时,背景就是摘要的全部指令。",+ "noTemplates": "暂无模板",+ "emptyEditorTitle": "选择模板",+ "emptyEditorDescription": "从列表中选择一个模板或创建新模板"},"empty": {"title": "这里还没有笔记",@@ -3202,12 +3274,12 @@"description": "操作使用 AI 来处理你的笔记。设置一个语言模型以开始使用。","configured": "AI 模型已配置"},- "actions": {- "title": "AI 驱动的操作",- "description": "操作可以处理你的笔记——整理转录、总结会议等。使用内置操作或创建你自己的。",- "builtInLabel": "内置",- "createTitle": "创建你的操作",- "createDescription": "使用你自己的 AI 提示词定义自定义操作。你可以随时在设置中编辑或添加更多。",+ "templates": {+ "title": "模板和操作",+ "description": "模板决定 AI 摘要的样式,从详细的会议记录到你自定义的章节。操作在笔记上运行,例如在聊天中起草跟进邮件。",+ "builtInLabel": "你的模板",+ "createTitle": "创建你的模板",+ "createDescription": "描述你想要的摘要。你之后可以添加章节、更多模板和操作。","created": "已创建!"},"getStarted": "开始使用",@@ -3684,7 +3756,8 @@"thinking": "正在思考...","typeMessage": "输入消息...","send": "发送",- "voiceDraftStreamingOnly": "当前转录服务商仅支持实时听写,因此无法使用语音输入。请在“设置 → 语音转文字”中选择其他服务商。"+ "voiceDraftStreamingOnly": "当前转录服务商仅支持实时听写,因此无法使用语音输入。请在“设置 → 语音转文字”中选择其他服务商。",+ "commands": "命令"},"tools": {"search_notesName": "搜索笔记",@@ -4544,9 +4617,7 @@"conversationSelector": "切换对话","history": "历史记录","quickActions": "快捷操作",- "generateSummary": "生成摘要",- "makeTodos": "创建待办事项",- "createOutline": "创建大纲"+ "generateSummary": "生成摘要"},"transcriptionPreview": {"label": "预览",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 2f1cf6f75..5ec7d8394 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -2774,7 +2774,7 @@"sidebar": {"newNote": "新增筆記","searchNotes": "搜尋筆記",- "actions": "動作"+ "templatesAndActions": "範本與動作"},"spaces": {"privateSpaces": "私人筆記",@@ -3139,8 +3139,8 @@"showInFileManager": "在{{manager}}中顯示"},"actions": {+ "allActions": "全部動作","manage": "管理動作...",- "manageTitle": "自訂動作","addAction": "新增動作","editAction": "編輯動作","namePlaceholder": "動作名稱",@@ -3154,8 +3154,6 @@"promptLabel": "提示詞","emptyEditorTitle": "選擇動作","emptyEditorDescription": "從列表中選擇一個動作或建立新動作",- "runAction": "執行 {{name}}",- "selectAction": "選擇動作","done": "完成","chunkProgress": "第 {{step}} 部分,共 {{total}} 部分","emptyReply": "模型傳回了空白回覆。請再試一次,或選擇其他模型。",@@ -3170,15 +3168,89 @@"cta": "草擬跟進郵件"},"detailedNotes": {- "name": "詳細筆記",+ "name": "AI 摘要","description": "準確、完整的會議筆記,包含決策和行動項目"+ },+ "makeTodos": {+ "name": "建立待辦事項",+ "description": "在聊天中列出每項待辦及其負責人"+ },+ "createOutline": {+ "name": "建立大綱",+ "description": "在聊天中為筆記的主題列出大綱"+ },+ "oneOnOne": {+ "name": "1 對 1",+ "description": "一對一會議中的近況、回饋、成長和後續步驟"+ },+ "standUp": {+ "name": "站會",+ "description": "每個人的進度、計畫和阻礙"+ },+ "salesCall": {+ "name": "銷售通話",+ "description": "需求、異議、預算和決策流程"+ },+ "userInterview": {+ "name": "使用者訪談",+ "description": "參與者的工作流程、痛點、反應和原話"+ },+ "shorten": {+ "name": "精簡",+ "description": "把摘要縮短到大約一半",+ "cta": "精簡摘要"+ },+ "addTldr": {+ "name": "新增 TL;DR",+ "description": "在摘要開頭加上兩三句話的 TL;DR",+ "cta": "新增 TL;DR"+ },+ "slackUpdate": {+ "name": "Slack 更新",+ "description": "寫一則發到 Slack 的簡短團隊更新",+ "cta": "寫一則 Slack 更新"}},"errors": {"noModel": "未選擇 AI 模型。請在設定中進行配置。","actionFailed": "操作失敗",- "noEndpoint": "未設定自架伺服器 URL。請在設定中進行配置。"- }+ "noEndpoint": "未設定自架伺服器 URL。請在設定中進行配置。",+ "outputTruncated": "AI 模型在完成之前就用完了輸出空間,因此筆記維持不變。",+ "nothingToSummarize": "這則筆記還沒有可以摘要的內容,因此 AI 摘要維持不變。",+ "saveFailed": "無法儲存。請檢查是否有內容過長,然後再試一次。"+ },+ "tab": "動作",+ "output": {+ "auto": "自動",+ "chat": "聊天",+ "summary": "AI 摘要",+ "chatHint": "在筆記的聊天中回覆,AI 摘要維持不變。",+ "summaryHint": "編輯筆記的 AI 摘要;如果還沒有摘要,就根據轉錄內容產生一份。",+ "autoHint": "儲存時讀取提示詞,並選擇聊天或 AI 摘要。"+ },+ "applied": "已使用 {{name}} 更新 AI 摘要"+ },+ "templates": {+ "tab": "範本",+ "managerTitle": "範本與動作",+ "manage": "管理範本...",+ "select": "選擇範本",+ "addTemplate": "新增範本",+ "editTemplate": "編輯範本",+ "namePlaceholder": "範本名稱",+ "contextLabel": "背景",+ "contextPlaceholder": "這是什麼類型的會議?摘要應著重在什麼?",+ "sectionsLabel": "段落",+ "addSection": "新增段落",+ "sectionHeadingPlaceholder": "段落標題",+ "sectionInstructionPlaceholder": "這個段落要寫什麼?",+ "moveSectionUp": "上移段落",+ "moveSectionDown": "下移段落",+ "removeSection": "移除段落",+ "noSectionsHint": "沒有段落時,背景就是摘要的完整指示。",+ "noTemplates": "尚無範本",+ "emptyEditorTitle": "選擇範本",+ "emptyEditorDescription": "從列表中選擇一個範本或建立新範本"},"empty": {"title": "這裡還沒有筆記",@@ -3202,12 +3274,12 @@"description": "動作使用 AI 來處理你的筆記。設定語言模型以開始使用。","configured": "AI 模型已設定"},- "actions": {- "title": "AI 驅動的動作",- "description": "動作可以處理你的筆記——整理轉錄、摘要會議等。使用內建動作或建立你自己的。",- "builtInLabel": "內建",- "createTitle": "建立你的動作",- "createDescription": "使用你自己的 AI 提示詞定義自訂動作。你隨時可以在設定中編輯或新增更多。",+ "templates": {+ "title": "範本與動作",+ "description": "範本決定 AI 摘要的樣式,從詳細的會議記錄到你自訂的段落。動作在筆記上執行,例如在聊天中草擬跟進郵件。",+ "builtInLabel": "你的範本",+ "createTitle": "建立你的範本",+ "createDescription": "描述你想要的摘要。你之後可以新增段落、更多範本與動作。","created": "已建立!"},"getStarted": "開始使用",@@ -3684,7 +3756,8 @@"thinking": "正在思考...","typeMessage": "輸入訊息...","send": "傳送",- "voiceDraftStreamingOnly": "目前的轉錄服務商僅支援即時聽寫,因此無法使用語音輸入。請在「設定 → 語音轉文字」中選擇其他服務商。"+ "voiceDraftStreamingOnly": "目前的轉錄服務商僅支援即時聽寫,因此無法使用語音輸入。請在「設定 → 語音轉文字」中選擇其他服務商。",+ "commands": "指令"},"tools": {"search_notesName": "搜尋筆記",@@ -4544,9 +4617,7 @@"conversationSelector": "切換對話","history": "歷史記錄","quickActions": "快速操作",- "generateSummary": "產生摘要",- "makeTodos": "建立待辦事項",- "createOutline": "建立大綱"+ "generateSummary": "產生摘要"},"transcriptionPreview": {"label": "預覽",diff --git a/src/services/BaseReasoningService.ts b/src/services/BaseReasoningService.tsindex 769aeb9fb..fc52be97e 100644--- a/src/services/BaseReasoningService.ts+++ b/src/services/BaseReasoningService.ts@@ -24,7 +24,8 @@ export interface ReasoningConfig {/*** Local models only: when the prompt leaves less than `maxTokens` of room and* the reply fills what is left, fail as CONTEXT_TOO_LARGE instead of- * returning a reply the context window clipped.+ * returning a reply the context window clipped. With `requireCompleteOutput`,+ * it still lets the allowance shrink to fit, where that flag alone refuses.*/refuseClippedByWindow?: boolean;/** Local models only: tags the request so `cancelLocalReasoning` can abort it. */diff --git a/src/services/NotesService.ts b/src/services/NotesService.tsindex 150ad94ed..98e3bb098 100644--- a/src/services/NotesService.ts+++ b/src/services/NotesService.ts@@ -9,6 +9,7 @@ interface NoteInput {content?: string;enhanced_content?: string | null;enhancement_prompt?: string | null;+ enhancement_template_id?: string | null;note_type?: "personal" | "meeting" | "upload";source_file?: string | null;audio_duration_seconds?: number | null;@@ -35,6 +36,8 @@ export interface CloudNote {enhanced_content: string | null;note_type: string;enhancement_prompt: string | null;+ // Absent from APIs that predate note templates.+ enhancement_template_id?: string | null;source_file: string | null;audio_duration_seconds: number | null;folder_id: string | null;diff --git a/src/services/ai/chatRequestBody.ts b/src/services/ai/chatRequestBody.tsindex 8dd2b80cf..39abe3072 100644--- a/src/services/ai/chatRequestBody.ts+++ b/src/services/ai/chatRequestBody.ts@@ -77,7 +77,7 @@ export function isTruncatedFinishReason(reason: unknown): boolean {*/export const TRUNCATED_OUTPUT_MESSAGE_KEY ="hooks.audioRecording.errorDescriptions.cleanupTruncated";-const EMPTY_OUTPUT_MESSAGE_KEY = "hooks.audioRecording.errorDescriptions.cleanupEmptyReply";+export const EMPTY_OUTPUT_MESSAGE_KEY = "hooks.audioRecording.errorDescriptions.cleanupEmptyReply";/** Output cut off at the token cap; providers may pass their own wording for the logs. */export function truncatedOutputError(diff --git a/src/stores/actionProcessingStore.ts b/src/stores/actionProcessingStore.tsindex 6c3c4bcb5..15025cbac 100644--- a/src/stores/actionProcessingStore.ts+++ b/src/stores/actionProcessingStore.ts@@ -1,22 +1,27 @@import { create } from "zustand";-import {- BASE_SYSTEM_PROMPT,- MEETING_INPUT_PREAMBLE,- MEETING_SYSTEM_PROMPT,- NOTE_INPUT_PREAMBLE,- NOTE_OUTPUT_MAX_TOKENS,- STANDALONE_PROMPT_KEYS,-} from "../helpers/builtinActions";+import { NOTE_OUTPUT_MAX_TOKENS, NOTHING_TO_SUMMARIZE } from "../helpers/builtinActions";+import { stripThinkingTags } from "../helpers/stripThinking";+import { compileSummaryActionPrompt, compileTemplatePrompt } from "../helpers/templatePrompts";import reasoningService from "../services/ReasoningService";import { getSettings, selectResolvedNoteFormatting } from "./settingsStore";import { appendDictionarySuffix } from "../config/prompts";import { generateNoteTitle } from "../utils/generateTitle";import { buildNoteFormattingOverrides } from "../helpers/noteFormattingOverrides";import { tagActionItemOwners, type MentionPerson } from "../utils/mentionMarkdown";-import type { ActionItem } from "../types/electron";+import type { ActionItem, NoteItem } from "../types/electron";import { estimateNoteTokens, planNoteChunks, splitChunkInHalf } from "../helpers/noteChunking";import type { LocalInferenceError } from "../utils/localInferenceError";import type { ReasoningConfig } from "../services/BaseReasoningService";+import {+ EMPTY_OUTPUT_MESSAGE_KEY,+ TRUNCATED_OUTPUT_MESSAGE_KEY,+} from "../services/ai/chatRequestBody";++// The providers' error keys describe dictation cleanup; a note run shows its own.+const NOTE_ERROR_KEYS: Record<string, string> = {+ [TRUNCATED_OUTPUT_MESSAGE_KEY]: "notes.actions.errors.outputTruncated",+ [EMPTY_OUTPUT_MESSAGE_KEY]: "notes.actions.emptyReply",+};// Output room reserved in each part's window when the parts are planned. The// allowance a part actually gets is its share of the room the final pass has@@ -66,17 +71,32 @@ export interface NoteMaterial {transcript: string;}+/** What a run overwrote, so Undo can put it back. */+export type NoteSummarySnapshot = Pick<+ NoteItem,+ "enhanced_content" | "enhancement_prompt" | "enhancement_template_id" | "enhanced_at_content_hash"+> & { title?: string };++export interface ActionAppliedEvent {+ noteId: number;+ action: ActionItem;+ previous: NoteSummarySnapshot;+}+export interface ActionErrorEvent {noteId: number;message: string;/** Set when the failure has a translatable form; the toast prefers it. */messageKey?: string;messageParams?: Record<string, string | number>;+ /** Not a failure: the run found nothing to write, so the toast only informs. */+ notice?: boolean;}interface ActionProcessingStoreState {noteStates: Record<number, NoteActionState>;errorEvents: ActionErrorEvent[];+ appliedEvents: ActionAppliedEvent[];}// The run a note's in-flight action belongs to. A per-note flag would be reset@@ -108,9 +128,15 @@ function pushErrorEvent(event: ActionErrorEvent) {useActionProcessingStore.setState({ errorEvents: [...errorEvents, event] });}+function pushAppliedEvent(event: ActionAppliedEvent) {+ const { appliedEvents } = useActionProcessingStore.getState();+ useActionProcessingStore.setState({ appliedEvents: [...appliedEvents, event] });+}+export const useActionProcessingStore = create<ActionProcessingStoreState>()(() => ({noteStates: {},errorEvents: [],+ appliedEvents: [],}));// One part of a recording too long for the local model's window (#2142). The@@ -168,6 +194,28 @@ async function readLocalContextBudget(modelId: string): Promise<LocalContextBudgconst emptyReplyError = () =>Object.assign(new Error("Model returned no text"), { messageKey: "notes.actions.emptyReply" });+const nothingToSummarizeError = () =>+ Object.assign(new Error("Nothing to summarize"), {+ messageKey: "notes.actions.errors.nothingToSummarize",+ notice: true,+ });++/**+ * Whether the reply is the marker itself, as models wrap it: in a fence or+ * emphasis, or after a short sentence. A summary that only contains it, such as+ * a section a small model answered with the marker, is still a summary.+ */+function isNothingToSummarizeReply(reply: string): boolean {+ const lines = stripThinkingTags(reply)+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line && !line.startsWith("```"));+ const last = lines.pop()?.replace(/^[*_`]+|[*_`.!]+$/g, "");+ if (last !== NOTHING_TO_SUMMARIZE) return false;+ const lead = lines.join("\n");+ return lead.length <= 200 && !/^(?:#|[-*+]\s|\d+[.)]\s)/m.test(lead);+}+/** The translated refusal from #2142, for material no amount of splitting can fit. */function tooLongForModel(modelName: string): LocalInferenceError {const error: LocalInferenceError = new Error(@@ -380,6 +428,8 @@ export interface RunActionOptions {knownPeople?: MentionPerson[];/** Structured pieces of `noteContent`; only its transcript is ever split into parts. */material?: NoteMaterial;+ /** An action's input is the note's AI summary rather than its notes and transcript. */+ fromSummary?: boolean;}export interface RunActionLabels {@@ -424,31 +474,39 @@ export function runBackgroundAction((async () => {try {- const standalone =- !!action.translation_key && STANDALONE_PROMPT_KEYS.has(action.translation_key);- const basePrompt = standalone- ? options.isMeetingNote- ? MEETING_INPUT_PREAMBLE- : NOTE_INPUT_PREAMBLE- : options.isMeetingNote- ? MEETING_SYSTEM_PROMPT- : BASE_SYSTEM_PROMPT;+ // Only summary actions reach the runner; chat actions run in the note chat.+ const editsSummary = action.kind === "action";+ // A summary action with no summary yet writes a first one, like a template.+ const rewritesSummary = editsSummary && !!options.fromSummary;+ const instructions = editsSummary+ ? compileSummaryActionPrompt(action, {+ fromSummary: !!options.fromSummary,+ isMeetingNote: options.isMeetingNote,+ })+ : compileTemplatePrompt(action, { isMeetingNote: options.isMeetingNote });const providerOverrides = buildNoteFormattingOverrides(noteFormatting, options.isCloudMode);const systemPrompt = appendDictionarySuffix(- basePrompt + action.prompt,+ instructions,options.isMeetingNote ? settings.customDictionary : undefined,settings.uiLanguage);const requestConfig: ReasoningConfig = {systemPrompt,- maxTokens: NOTE_OUTPUT_MAX_TOKENS,+ // A rewrite repeats a summary written under NOTE_OUTPUT_MAX_TOKENS, plus its edit.+ maxTokens: rewritesSummary ? 2 * NOTE_OUTPUT_MAX_TOKENS : NOTE_OUTPUT_MAX_TOKENS,temperature: 0.3,disableThinking: settings.noteFormattingDisableThinking,// A local model that shrinks the reply to fit the prompt refuses a reply// that fills the shrunken allowance, so a recording is summarised in// parts rather than saved clipped. A plain note has no parts route, so- // its clipped reply is saved as before. Other routes ignore the flag.- refuseClippedByWindow: hasTranscript(options.material),+ // its clipped reply is saved as before. A rewrite sets it too, so a+ // local model shortens its allowance instead of refusing up front.+ // Other routes ignore the flag.+ refuseClippedByWindow: rewritesSummary || hasTranscript(options.material),+ // Rewriting an existing summary replaces all of it, so a clipped+ // rewrite would lose content: providers refuse it (OpenWhispr Cloud+ // refuses a truncated reply for every request).+ ...(rewritesSummary && { requireCompleteOutput: true }),requestId: runId,...providerOverrides,};@@ -467,26 +525,53 @@ export function runBackgroundAction(if (!enhanced.trim()) {throw emptyReplyError();}+ // Only greetings or filler: say so rather than save that as the summary.+ if (isNothingToSummarizeReply(enhanced)) {+ throw nothingToSummarizeError();+ }if (isCancelled()) return;let title: string | undefined;- if (options.allowTitleGeneration && getSettings().autoGenerateNoteTitle) {+ if (!editsSummary && options.allowTitleGeneration && getSettings().autoGenerateNoteTitle) {const generated = await generateNoteTitle(enhanced, modelId, providerOverrides);if (generated) title = generated;}+ const before = await window.electronAPI.getNote(noteId);if (isCancelled()) return;- const updates: Record<string, string> = {- enhanced_content: options.knownPeople?.length- ? tagActionItemOwners(enhanced, options.knownPeople)- : enhanced,- enhancement_prompt: action.prompt,- enhanced_at_content_hash: contentHash,- };+ const enhancedContent = options.knownPeople?.length+ ? tagActionItemOwners(enhanced, options.knownPeople)+ : enhanced;+ // A summary action keeps the template the summary was built from. Editing+ // a summary also keeps its material hash; writing one from the material+ // records that material, so later edits to it mark the summary stale.+ const updates: Record<string, string> = !editsSummary+ ? {+ enhanced_content: enhancedContent,+ enhancement_prompt: instructions,+ enhancement_template_id: action.client_id,+ enhanced_at_content_hash: contentHash,+ }+ : options.fromSummary+ ? { enhanced_content: enhancedContent }+ : { enhanced_content: enhancedContent, enhanced_at_content_hash: contentHash };if (title) updates.title = title;- await window.electronAPI.updateNote(noteId, updates);+ const result = await window.electronAPI.updateNote(noteId, updates);+ if (!result?.success) throw new Error(labels.actionFailed);+ pushAppliedEvent({+ noteId,+ action,+ previous: {+ // "" as deleting a summary does: sync keeps the cloud copy over a null.+ enhanced_content: before?.enhanced_content ?? "",+ enhancement_prompt: before?.enhancement_prompt ?? null,+ enhancement_template_id: before?.enhancement_template_id ?? null,+ enhanced_at_content_hash: before?.enhanced_at_content_hash ?? null,+ ...(title && before && { title: before.title }),+ },+ });setNoteState(noteId, { status: "success", actionName: action.name, progress: null });@@ -501,11 +586,18 @@ export function runBackgroundAction(processingFlags.set(noteId, false);clearNoteState(noteId);const message = err instanceof Error ? err.message : labels.actionFailed;- const { messageKey, messageParams } = (err ?? {}) as {+ const { messageKey, messageParams, notice } = (err ?? {}) as {messageKey?: string;messageParams?: Record<string, string | number>;+ notice?: boolean;};- pushErrorEvent({ noteId, message, messageKey, messageParams });+ pushErrorEvent({+ noteId,+ message,+ messageKey: (messageKey && NOTE_ERROR_KEYS[messageKey]) || messageKey,+ messageParams,+ notice,+ });} finally {if (activeRuns.get(noteId) === runId) activeRuns.delete(noteId);}@@ -536,6 +628,13 @@ export function consumeErrorEvents(): ActionErrorEvent[] {return errorEvents;}+export function consumeAppliedEvents(): ActionAppliedEvent[] {+ const { appliedEvents } = useActionProcessingStore.getState();+ if (appliedEvents.length === 0) return [];+ useActionProcessingStore.setState({ appliedEvents: [] });+ return appliedEvents;+}+export function selectNoteActionState(state: ActionProcessingStoreState,noteId: number | nulldiff --git a/src/stores/actionStore.ts b/src/stores/actionStore.tsindex 4913cb772..ac895e1f6 100644--- a/src/stores/actionStore.ts+++ b/src/stores/actionStore.ts@@ -1,6 +1,8 @@import { create } from "zustand";+import { useShallow } from "zustand/react/shallow";import { TFunction } from "i18next";-import type { ActionItem } from "../types/electron";+import type { ActionItem, ActionKind } from "../types/electron";+import { DETAILED_NOTES_KEY } from "../helpers/builtinActions";interface ActionState {actions: ActionItem[];@@ -71,8 +73,25 @@ function removeActionFromStore(id: number): void {useActionStore.setState({ actions: next });}-export function useActions(): ActionItem[] {- return useActionStore((state) => state.actions);+export function useActionsOfKind(kind: ActionKind): ActionItem[] {+ return useActionStore(useShallow((state) => state.actions.filter((a) => a.kind === kind)));+}++/**+ * The template a summary is written with: the note's own, else the default AI+ * Summary. An id can outlive its template or belong to a teammate's, so it is+ * only a preference.+ */+export function resolveTemplate(+ templates: ActionItem[],+ clientId: string | null | undefined+): ActionItem | null {+ return (+ templates.find((a) => a.client_id === clientId) ??+ templates.find((a) => a.translation_key === DETAILED_NOTES_KEY) ??+ templates[0] ??+ null+ );}export function getActionName(@@ -84,7 +103,7 @@ export function getActionName(: action.name;}-/** Verb-form label for the ask bar button; falls back to the action name. */+/** Verb-form label the chat shows for a running action; falls back to the action name. */export function getActionCta(action: { name: string; translation_key?: string },t: TFunctiondiff --git a/src/stores/noteStore.ts b/src/stores/noteStore.tsindex 123f6cadd..f3cb16eba 100644--- a/src/stores/noteStore.ts+++ b/src/stores/noteStore.ts@@ -921,6 +921,7 @@ export async function startMigration(): Promise<void> {content: n.content,enhanced_content: n.enhanced_content,enhancement_prompt: n.enhancement_prompt,+ enhancement_template_id: n.enhancement_template_id,note_type: n.note_type,source_file: n.source_file,audio_duration_seconds: n.audio_duration_seconds,diff --git a/src/types/electron.ts b/src/types/electron.tsindex b1a910e36..3cbac4807 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -331,6 +331,8 @@ export interface NoteItem {content: string;enhanced_content: string | null;enhancement_prompt: string | null;+ /** The client_id of the template that produced enhanced_content. */+ enhancement_template_id: string | null;enhanced_at_content_hash: string | null;note_type: "personal" | "meeting" | "upload";source_file: string | null;@@ -379,6 +381,7 @@ export type NotePushSnapshot = Pick<| "content"| "enhanced_content"| "enhancement_prompt"+ | "enhancement_template_id"| "enhanced_at_content_hash"| "note_type"| "source_file"@@ -699,11 +702,26 @@ export interface NewWorkspaceApiKey extends WorkspaceApiKey {key: string;}+export interface TemplateSection {+ heading: string;+ instruction: string;+}++/** A template writes the AI summary; an action edits it or answers in the note chat. */+export type ActionKind = "template" | "action";+export type ActionOutput = "summary" | "chat";+export interface ActionItem {id: number;+ /** Stable across devices: a built-in's translation key, otherwise a UUID. */+ client_id: string;+ kind: ActionKind;name: string;description: string;+ /** A template's context, or an action's instructions. */prompt: string;+ sections: TemplateSection[] | null;+ output: ActionOutput | null;icon: string;is_builtin: number;sort_order: number;@@ -1484,6 +1502,7 @@ declare global {content?: string;enhanced_content?: string | null;enhancement_prompt?: string | null;+ enhancement_template_id?: string | null;enhanced_at_content_hash?: string | null;folder_id?: number | null;space_id?: number;@@ -1636,7 +1655,8 @@ declare global {name: string,description: string,prompt: string,- icon?: string+ icon?: string,+ fields?: { kind?: ActionKind; sections?: TemplateSection[]; output?: ActionOutput }) => Promise<{ success: boolean; action?: ActionItem; error?: string }>;updateAction: (id: number,@@ -1646,6 +1666,8 @@ declare global {prompt?: string;icon?: string;sort_order?: number;+ sections?: TemplateSection[];+ output?: ActionOutput;}) => Promise<{ success: boolean; action?: ActionItem; error?: string }>;deleteAction: (id: number) => Promise<{ success: boolean; id?: number; error?: string }>;diff --git a/src/utils/inferActionOutput.ts b/src/utils/inferActionOutput.tsnew file mode 100644index 000000000..1c76fd524--- /dev/null+++ b/src/utils/inferActionOutput.ts@@ -0,0 +1,28 @@+import reasoningService from "../services/ReasoningService";+import { getSettings, selectResolvedNoteFormatting } from "../stores/settingsStore";+import { buildNoteFormattingOverrides } from "../helpers/noteFormattingOverrides";+import { stripThinkingTags } from "../helpers/stripThinking";+import type { ActionOutput } from "../types/electron";++const OUTPUT_SYSTEM_PROMPT = `You sort instructions that a user runs on a meeting note. Reply SUMMARY if the instruction changes the note's AI summary itself: rewrites, shortens, expands, reformats, or translates it, or adds a section to it. Reply CHAT if it produces something separate from the summary, such as an email, a message, a list, an outline, or an answer to a question. Reply with exactly one word: SUMMARY or CHAT.`;++/** Where an action's result belongs, read from its prompt by the note model; chat when it can't tell. */+export async function inferActionOutput(+ prompt: string,+ modelId: string,+ isCloudMode: boolean+): Promise<ActionOutput> {+ try {+ const reply = await reasoningService.processText(prompt.slice(0, 2000), modelId, null, {+ systemPrompt: OUTPUT_SYSTEM_PROMPT,+ temperature: 0,+ // A one-word answer needs no thinking, and a kept <think> block would hide it.+ disableThinking: true,+ ...buildNoteFormattingOverrides(selectResolvedNoteFormatting(getSettings()), isCloudMode),+ });+ // Not every route strips a reasoning model's inline <think> block.+ return /^\W*summary\b/i.test(stripThinkingTags(reply)) ? "summary" : "chat";+ } catch {+ return "chat";+ }+}diff --git a/test/components/backgroundActionToastListener.test.js b/test/components/backgroundActionToastListener.test.jsnew file mode 100644index 000000000..9640f3af6--- /dev/null+++ b/test/components/backgroundActionToastListener.test.js@@ -0,0 +1,175 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const React = require("react");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");+const { installInteractiveDom } = require("../lib/interactiveDom");++async function mountListener(+ t,+ updateNoteResult,+ { focused = true, storedNote = { id: 4, deleted_at: null } } = {}+) {+ let root;+ t.after(async () => {+ if (root) await React.act(async () => root.unmount());+ delete globalThis.__toasts;+ delete globalThis.__dismissed;+ });+ const writes = [];+ const focusListeners = new Set();+ installBrowserGlobals(t, {+ window: {+ addEventListener: (type, listener) => type === "focus" && focusListeners.add(listener),+ removeEventListener: (type, listener) => focusListeners.delete(listener),+ electronAPI: {+ getNote: async () => storedNote,+ updateNote: async (noteId, payload) => {+ writes.push({ noteId, payload });+ return updateNoteResult;+ },+ },+ },+ });+ const container = installInteractiveDom(t);+ globalThis.document.hasFocus = () => focused;+ globalThis.__toasts = [];+ globalThis.__dismissed = [];+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-action-toast-listener-test-",+ mockModules: {+ "/ui/useToast": `+ export const useToast = () => ({+ toast: (props) => { globalThis.__toasts.push(props); return "toast-" + globalThis.__toasts.length; },+ dismiss: (id) => globalThis.__dismissed.push(id),+ });+ `,+ "/services/ReasoningService": `export default { processText: async () => "" };`,+ "/utils/generateTitle": `export const generateNoteTitle = async () => undefined;`,+ "/ui/Toast": `+ import { createElement } from "react";+ export const ToastActionButton = ({ onClick, children }) => createElement("button", { onClick }, children);+ `,+ },+ });+ const { default: Listener } = await vite.ssrLoadModule(+ "/components/notes/BackgroundActionToastListener.tsx"+ );+ const store = await vite.ssrLoadModule("/stores/actionProcessingStore.ts");+ const { createRoot } = require("react-dom/client");+ root = createRoot(container);+ await React.act(async () => root.render(React.createElement(Listener)));+ return { store, writes, focusListeners };+}++const PREVIOUS = {+ enhanced_content: null,+ enhancement_prompt: null,+ enhancement_template_id: null,+ enhanced_at_content_hash: null,+};+const APPLIED = {+ noteId: 4,+ action: { id: 1, name: "Shorten", translation_key: null },+ previous: PREVIOUS,+};++test("a note run offers Undo, which writes back what the run replaced", async (t) => {+ const { store, writes } = await mountListener(t, { success: true });+ await React.act(async () =>+ store.useActionProcessingStore.setState({ appliedEvents: [APPLIED] })+ );++ assert.equal(globalThis.__toasts.length, 1);+ const [toast] = globalThis.__toasts;+ assert.ok(toast.duration >= 5000 && toast.duration <= 6000, "a short undo window");+ assert.deepEqual(store.useActionProcessingStore.getState().appliedEvents, [], "consumed once");++ await React.act(async () => toast.action.props.onClick());+ assert.deepEqual(writes, [{ noteId: 4, payload: PREVIOUS }]);+ assert.deepEqual(globalThis.__dismissed, ["toast-1"]);+});++test("an undo the database refused leaves the toast up to try again", async (t) => {+ const { store, writes } = await mountListener(t, { success: false });+ await React.act(async () =>+ store.useActionProcessingStore.setState({ appliedEvents: [APPLIED] })+ );++ await React.act(async () => globalThis.__toasts[0].action.props.onClick());+ assert.equal(writes.length, 1);+ assert.deepEqual(globalThis.__dismissed, []);+});++test("a run that lands while the app is in the background offers Undo once the user is back", async (t) => {+ const { store, focusListeners } = await mountListener(t, { success: true }, { focused: false });+ await React.act(async () =>+ store.useActionProcessingStore.setState({ appliedEvents: [APPLIED] })+ );+ assert.equal(globalThis.__toasts.length, 0, "no toast runs out unseen");+ assert.equal(+ store.useActionProcessingStore.getState().appliedEvents.length,+ 1,+ "the event waits in the store until the window has focus"+ );++ // The window gains focus, as the user comes back to the app.+ globalThis.document.hasFocus = () => true;+ await React.act(async () => focusListeners.forEach((listener) => listener()));+ assert.equal(globalThis.__toasts.length, 1);+ await React.act(async () => focusListeners.forEach((listener) => listener()));+ assert.equal(globalThis.__toasts.length, 1, "shown once");+});++test("Undo leaves a note deleted since alone instead of bringing it back", async (t) => {+ const { store, writes } = await mountListener(+ t,+ { success: true },+ { storedNote: { id: 4, deleted_at: "2026-09-30T10:00:00Z" } }+ );+ await React.act(async () =>+ store.useActionProcessingStore.setState({ appliedEvents: [APPLIED] })+ );++ await React.act(async () => globalThis.__toasts[0].action.props.onClick());+ assert.deepEqual(writes, []);+ assert.deepEqual(globalThis.__dismissed, ["toast-1"]);+});++test("a new run starting on the note retires its Undo, which the run may build on", async (t) => {+ const { store } = await mountListener(t, { success: true });+ await React.act(async () =>+ store.useActionProcessingStore.setState({ appliedEvents: [APPLIED] })+ );+ await React.act(async () =>+ store.useActionProcessingStore.setState({+ noteStates: { 9: { status: "processing", actionName: "Shorten" } },+ })+ );+ assert.deepEqual(globalThis.__dismissed, [], "a run on another note leaves it");++ await React.act(async () =>+ store.useActionProcessingStore.setState({+ noteStates: { 4: { status: "processing", actionName: "Shorten" } },+ })+ );+ assert.deepEqual(globalThis.__dismissed, ["toast-1"]);+});++test("a run with nothing to write informs, where a failed one reports an error", async (t) => {+ const { store } = await mountListener(t, { success: true });+ await React.act(async () =>+ store.useActionProcessingStore.setState({+ errorEvents: [+ { noteId: 4, message: "Nothing to summarize", notice: true },+ { noteId: 4, message: "Request failed" },+ ],+ })+ );++ const [notice, failure] = globalThis.__toasts;+ assert.equal(notice.description, "Nothing to summarize");+ assert.equal(notice.variant, undefined);+ assert.equal(notice.title, undefined, "no error title over it");+ assert.equal(failure.variant, "destructive");+ assert.ok(failure.title);+});diff --git a/test/components/chatInputSlashCommands.test.js b/test/components/chatInputSlashCommands.test.jsnew file mode 100644index 000000000..de931d94c--- /dev/null+++ b/test/components/chatInputSlashCommands.test.js@@ -0,0 +1,164 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const React = require("react");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");+const { installInteractiveDom, findElement } = require("../lib/interactiveDom");++async function mountChatInput(t) {+ let root;+ t.after(async () => {+ if (root) await React.act(async () => root.unmount());+ });+ installBrowserGlobals(t);+ const container = installInteractiveDom(t);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-chat-input-slash-test-",+ mockModules: {+ "/ui/useToast": `export const useToast = () => ({ toast: () => {} });`,+ "/useVoiceDraft": `export const useVoiceDraft = () => ({ status: "idle", streamingOnlyProvider: false });`,+ "/stores/meetingRecordingStore": `+ export const getMicAnalyser = () => null;+ export const useMeetingRecordingStore = { getState: () => ({ currentMicLevel: 0 }) };+ `,+ // Radix positions the menu with real layout; render it in place instead.+ "/ui/popover": `+ import { createContext, createElement, useContext } from "react";+ const Open = createContext(false);+ export const Popover = ({ open, children }) =>+ createElement(Open.Provider, { value: open }, children);+ export const PopoverAnchor = () => null;+ export const PopoverContent = ({ children }) => (useContext(Open) ? children : null);+ `,+ },+ });+ const { ChatInput } = await vite.ssrLoadModule("/components/chat/ChatInput.tsx");+ // Loaded after the DOM is installed, so react-dom detects native input events.+ const { createRoot } = require("react-dom/client");+ root = createRoot(container);+ return { root, container, ChatInput };+}++const key = (target, name, modifiers = {}) =>+ React.act(async () =>+ target.dispatchEvent({+ type: "keydown",+ key: name,+ ...modifiers,+ bubbles: true,+ preventDefault() {+ this.defaultPrevented = true;+ },+ stopPropagation() {+ this.cancelBubble = true;+ },+ })+ );++const options = (container) => {+ const listbox = findElement(container, (el) => el.getAttribute?.("role") === "listbox");+ if (!listbox) return [];+ return listbox.childNodes.map((option) => ({+ label: option.textContent,+ selected: option.getAttribute("aria-selected") === "true",+ }));+};++test("typing / in the composer runs an action from the keyboard", async (t) => {+ const { root, container, ChatInput } = await mountChatInput(t);+ const ran = [];+ const drafts = [];+ const submitted = [];+ let escaped = 0;+ const commands = [+ { id: "email", label: "Follow-up email", run: () => ran.push("email") },+ { id: "todos", label: "Make to-dos", run: () => ran.push("todos") },+ {+ id: "tldr",+ label: "Add TL;DR",+ hint: "AI summary",+ disabled: true,+ run: () => ran.push("tldr"),+ },+ ];+ const render = (draftText) =>+ React.act(async () =>+ root.render(+ React.createElement(ChatInput, {+ variant: "note",+ agentState: "idle",+ partialTranscript: "",+ draftText,+ onDraftChange: (text) => drafts.push(text),+ onTextSubmit: (text) => submitted.push(text),+ onEscape: () => escaped++,+ focusOnIdle: false,+ slashCommands: commands,+ })+ )+ );++ await render("/");+ assert.deepEqual(options(container), [], "the menu waits for the composer to have focus");+ const textarea = findElement(container, (el) => el.tagName === "TEXTAREA");+ await React.act(async () => textarea.dispatchEvent({ type: "focusin", bubbles: true }));+ assert.deepEqual(+ options(container).map((option) => option.label),+ ["Follow-up email", "Make to-dos", "Add TL;DRAI summary"]+ );++ await key(textarea, "ArrowDown");+ assert.deepEqual(+ options(container).map((option) => option.selected),+ [false, true, false]+ );+ await key(textarea, "Enter");+ assert.deepEqual(ran, ["todos"]);+ assert.equal(drafts.at(-1), "", "running a command clears the draft");++ await render("/tl");+ assert.deepEqual(+ options(container).map((option) => option.label),+ ["Add TL;DRAI summary"]+ );+ await key(textarea, "Enter");+ assert.deepEqual(ran, ["todos"], "a disabled command doesn't run");+ assert.deepEqual(submitted, [], "nor is its filter sent as a message");++ await key(textarea, "Tab");+ assert.deepEqual(ran, ["todos"], "nor does Tab run it");++ drafts.length = 0;+ await key(textarea, "Escape");+ assert.deepEqual(drafts, [""], "Escape clears the filter");+ assert.equal(escaped, 0, "Escape dismisses the menu, not the composer");++ await render("/");+ await key(textarea, "Tab", { shiftKey: true });+ assert.deepEqual(ran, ["todos"], "Shift+Tab leaves the composer without running anything");+ await key(textarea, "ArrowUp");+ await key(textarea, "Tab");+ assert.deepEqual(ran, ["todos", "email"], "Tab runs the highlighted command");++ await render("/zzz");+ assert.deepEqual(options(container), []);+ await key(textarea, "Enter");+ assert.deepEqual(submitted, ["/zzz"], "a draft no command matches is sent as typed");+});++test("a / filter ranks labels with a word starting with it first", async () => {+ const { matchSlashCommands } = await import("../../src/components/chat/slashCommands.ts");+ const commands = ["Make to-dos", "Shorten", "Slack update", "全部操作"].map((label) => ({+ id: label,+ label,+ run: () => {},+ }));+ const labels = (draft) => matchSlashCommands(commands, draft).map((command) => command.label);++ assert.deepEqual(labels("/s"), ["Shorten", "Slack update", "Make to-dos"]);+ assert.deepEqual(labels("/DOS"), ["Make to-dos"]);+ assert.deepEqual(labels("/操作"), ["全部操作"], "a label without spaces matches mid-word");+ assert.deepEqual(labels("/操作"), ["全部操作"], "a CJK input method's full-width slash counts");+ assert.deepEqual(labels("/"), ["Make to-dos", "Shorten", "Slack update", "全部操作"]);+ assert.deepEqual(labels("Summarize /s"), [], "only a draft that starts with / asks");+ assert.deepEqual(labels("/s\nmore"), [], "nor one that runs onto a new line");+});diff --git a/test/components/fieldDirectionPolicy.test.js b/test/components/fieldDirectionPolicy.test.jsindex 03dd79f91..9847bca1b 100644--- a/test/components/fieldDirectionPolicy.test.js+++ b/test/components/fieldDirectionPolicy.test.js@@ -70,7 +70,7 @@ const EXPECTED_SHARED_FIELD_DIRECTIONS = {"src/components/SettingsPage.tsx": ["ltr", "ltr", "ltr", "ltr", "ltr", "ltr"],"src/components/SnippetsView.tsx": ["auto", "auto", "auto", "auto"],"src/components/TranscriptionModelPicker.tsx": ["ltr", "ltr", "ltr"],- "src/components/notes/ActionManagerDialog.tsx": ["auto", "auto"],+ "src/components/notes/ActionManagerDialog.tsx": ["auto", "auto", "auto"],"src/components/notes/DeleteSpaceDialog.tsx": ["auto"],"src/components/notes/UploadAudioView.tsx": ["auto"],"src/components/onboarding/ProviderSetupStep.tsx": ["ltr", "ltr", "ltr", "ltr", "ltr", "ltr"],@@ -97,7 +97,7 @@ const EXPECTED_NATIVE_FIELD_DIRECTIONS = {"src/components/chat/EmailApprovalFields.tsx": ["auto", "auto", "auto", "auto"],// Title and description, or a comment: prose in any script."src/components/chat/IssueApprovalFields.tsx": ["auto", "auto"],- "src/components/notes/ActionManagerDialog.tsx": ["auto"],+ "src/components/notes/ActionManagerDialog.tsx": ["auto", "auto"],"src/components/notes/AddNotesToFolderDialog.tsx": ["auto"],"src/components/notes/MeetingTranscriptChat.tsx": ["ltr", "auto"],"src/components/notes/NoteEditor.tsx": ["auto", "auto"],diff --git a/test/components/meetingRecordingSurvivesViewSwitch.test.js b/test/components/meetingRecordingSurvivesViewSwitch.test.jsindex c92452fd6..68367c7d8 100644--- a/test/components/meetingRecordingSurvivesViewSwitch.test.js+++ b/test/components/meetingRecordingSurvivesViewSwitch.test.js@@ -59,14 +59,14 @@ const MOCKS = {"./SpacesTree": `export default () => null;`,"/overview/ContainerOverview": `export const ContainerOverview = () => null;`,"./NotesStructureIntroDialog": `export default () => null;`,- "./ActionPicker": `export default () => null;`,"./ActionManagerDialog": `export default () => null;`,"./AddNotesToFolderDialog": `export default () => null;`,"./NotesOnboarding": `export default () => null;`,"/hooks/useActionProcessing": `export const useActionProcessing = () => ({ state: "idle", actionName: null, runAction() {} });`,- "/stores/actionStore": `export const useActions = () => [];`,+ "/stores/actionStore": `export const getActionName = (action) => action.name;`,+ "/utils/inferActionOutput": `export const inferActionOutput = async () => "chat";`,"/hooks/useNotesOnboarding": `export const useNotesOnboarding = () => ({ isComplete: true, complete() {} });`,diff --git a/test/components/noteActionChips.test.js b/test/components/noteActionChips.test.jsnew file mode 100644index 000000000..b37f38340--- /dev/null+++ b/test/components/noteActionChips.test.js@@ -0,0 +1,133 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createElement } = require("react");+const { renderToStaticMarkup } = require("react-dom/server");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++// i18n is not initialized, so labels render as raw keys or their default values.++const action = (overrides) => ({+ id: 1,+ client_id: "client",+ kind: "action",+ name: "Action",+ description: "",+ prompt: "Do it.",+ sections: null,+ output: "chat",+ icon: "sparkles",+ is_builtin: 0,+ sort_order: 0,+ translation_key: null,+ ...overrides,+});++const FOLLOW_UP = action({+ id: 2,+ client_id: "notes.actions.builtin.followUpEmail",+ name: "Follow-up email",+ translation_key: "notes.actions.builtin.followUpEmail",+});+const SHORTEN = action({ id: 3, client_id: "shorten", name: "Shorten", output: "summary" });++async function load(t, path, initialStorage) {+ installBrowserGlobals(t, { initialStorage });+ const vite = await createRendererServer(t, { cachePrefix: "openwhispr-note-action-chips-" });+ return (await vite.ssrLoadModule(path)).default;+}++// Every element a component returned when rendered inside a harness, without mounting it.+function renderTree(Component, props) {+ let tree = null;+ function Harness() {+ tree = Component(props);+ return null;+ }+ renderToStaticMarkup(createElement(Harness));+ return tree;+}++function collect(node, out = []) {+ if (node === null || typeof node !== "object") return out;+ if (Array.isArray(node)) {+ for (const child of node) collect(child, out);+ return out;+ }+ if (!node.props) return out;+ out.push(node);+ collect(node.props.children, out);+ return out;+}++test("the ask bar shows the first four actions as chips and every action under All actions", async (t) => {+ const ActionChips = await load(t, "/components/notes/ActionChips.tsx");+ const actions = [+ FOLLOW_UP,+ action({ id: 4, client_id: "todos", name: "Make to-dos" }),+ SHORTEN,+ action({ id: 5, client_id: "tldr", name: "Add TL;DR", output: "summary" }),+ action({ id: 6, client_id: "outline", name: "Create outline" }),+ ];+ const ran = [];+ const tree = collect(+ renderTree(ActionChips, {+ actions,+ canRun: (a) => a.output === "chat",+ onRunAction: (a) => ran.push(a.name),+ onManageActions: () => ran.push("manage"),+ })+ );++ const chips = tree.filter((node) => node.type === "button" && node.props.onClick);+ assert.deepEqual(+ chips.map((chip) => chip.key),+ ["2", "4", "3", "5"]+ );+ assert.deepEqual(+ chips.map((chip) => chip.props.disabled),+ [false, false, true, true],+ "a chip is disabled while its action can't run"+ );+ chips[0].props.onClick();++ const menuItems = tree.filter((node) => typeof node.type !== "string" && node.props.onClick);+ assert.equal(menuItems.length, actions.length + 1, "every action, then Manage Actions");+ menuItems.at(-2).props.onClick();+ menuItems.at(-1).props.onClick();+ assert.deepEqual(ran, ["Follow-up email", "Create outline", "manage"]);+});++test("the sidebar chat offers the note's chat actions, and Generate summary writes the summary", async (t) => {+ const EmbeddedChat = await load(t, "/components/notes/EmbeddedChat.tsx");+ const ran = [];+ const props = {+ mode: "sidebar",+ onModeChange: () => {},+ messages: [],+ onTextSubmit: (text) => ran.push(["chat", text]),+ onCancel: () => {},+ chatActions: [FOLLOW_UP],+ onRunChatAction: (a) => ran.push(["action", a.name]),+ onGenerateSummary: () => ran.push(["summary"]),+ slashCommands: [{ id: "cmd", label: "Follow-up email", run: () => {} }],+ };++ const idle = collect(renderTree(EmbeddedChat, { ...props, agentState: "idle" }));+ const pills = idle.filter((node) => node.type === "button" && node.props.onMouseDown);+ assert.deepEqual(+ pills.map((pill) => pill.key),+ ["summary", FOLLOW_UP.client_id]+ );+ for (const pill of pills) pill.props.onClick();+ assert.deepEqual(ran, [["summary"], ["action", "Follow-up email"]]);+ const composer = idle.find((node) => node.props.variant === "sidebar");+ assert.equal(composer.props.slashCommands, props.slashCommands, "/ reaches the sidebar composer");++ const streaming = collect(renderTree(EmbeddedChat, { ...props, agentState: "streaming" })).filter(+ (node) => node.type === "button" && node.props.onMouseDown+ );+ assert.equal(streaming.length, 2);+ for (const pill of streaming) {+ assert.equal(pill.props.disabled, true, "no quick action starts while a reply streams");+ }+});diff --git a/test/components/noteBottomBar.test.js b/test/components/noteBottomBar.test.jsindex 3ac4053a8..21814d9c7 100644--- a/test/components/noteBottomBar.test.js+++ b/test/components/noteBottomBar.test.js@@ -51,15 +51,25 @@ test("in-view chat expands the existing capsule around one composer", async (t)assert.equal((html.match(/<textarea/g) ?? []).length, 1);});-test("closing a selected chat restores the compact actions and summary callout", async (t) => {- const html = await renderBottomBar(t, {- chatOpen: false,+test("the action chips sit above the composer, inside the chat once it opens", async (t) => {+ const props = {chatContent: createElement("div", null, "Previous conversation"),- actionPicker: createElement("button", null, "More actions"),+ actionChips: createElement("button", null, "All actions"),callout: createElement("button", null, "Generate summary"),- });+ };+ const closed = await renderBottomBar(t, { ...props, chatOpen: false });- assert.ok(html.includes("More actions"));- assert.ok(html.includes("Generate summary"));- assert.ok(html.includes("agentMode.input.send"));+ assert.ok(closed.includes("Generate summary"));+ assert.ok(+ closed.indexOf("All actions") < closed.indexOf("<textarea"),+ "the chips sit above the composer"+ );++ const open = await renderBottomBar(t, { ...props, chatOpen: true });+ assert.equal(open.split("All actions").length, 2, "the chips show once");+ assert.ok(+ open.indexOf("Previous conversation") < open.indexOf("All actions") &&+ open.indexOf("All actions") < open.indexOf("<textarea"),+ "an open chat keeps the chips, between its messages and the composer"+ );});diff --git a/test/components/noteEditorSummaryDeletion.test.js b/test/components/noteEditorSummaryDeletion.test.jsindex f16cfff10..c66fab126 100644--- a/test/components/noteEditorSummaryDeletion.test.js+++ b/test/components/noteEditorSummaryDeletion.test.js@@ -104,6 +104,19 @@ const NOTE = {const ENHANCEMENT = { content: NOTE.enhanced_content, isStale: false, onChange() {} };+// The summary callout runs a template, so the note view needs one loaded.+const TEMPLATE = {+ id: 1,+ client_id: "notes.actions.builtin.detailedNotes",+ kind: "template",+ name: "Detailed Notes",+ description: "",+ prompt: "",+ sections: [{ heading: "Summary", instruction: "" }],+ output: null,+ translation_key: "notes.actions.builtin.detailedNotes",+};+function baseProps(enhancement) {return {note: { ...NOTE, enhanced_content: enhancement ? enhancement.content : null },@@ -124,6 +137,7 @@ async function loadNoteEditor(t) {electronAPI: {getSpeakerProfiles: async () => [],getSpeakerMappings: async () => [],+ getActions: async () => [TEMPLATE],},},});@@ -204,9 +218,14 @@ async function loadNoteEditor(t) {React.act(async () => {root.render(React.createElement(Harness, { enhancement, overrides }));});+ // The AI Summary tab wraps its label button and the template chevron.const click = (value) =>React.act(async () => {- collectSegments(renders.at(-1)).get(value).props.onClick();+ let target = null;+ walk(collectSegments(renders.at(-1)).get(value), (node) => {+ if (!target && node.props.onClick) target = node;+ });+ target.props.onClick();});const latest = () => renders.at(-1);const unmount = () => React.act(async () => root.unmount());@@ -295,6 +314,22 @@ test("hides the highlight instead of freezing it when no tab matches the selectiawait unmount();});+test("a typed note without a summary offers one with the default template", async (t) => {+ const { render, latest, unmount } = await loadNoteEditor(t);+ const ran = [];++ await render(undefined, { onRunNoteAction: (action) => ran.push(action.client_id) });+ let callout = null;+ walk(latest(), (node) => {+ if (!callout && "onAskSubmit" in node.props) callout = node.props.callout;+ });+ assert.ok(callout, "notes with no transcript still offer a summary");+ callout.props.onClick();+ assert.deepEqual(ran, [TEMPLATE.client_id]);++ await unmount();+});+test("the summary callout makes way for the transcript selection bar", async (t) => {const { render, click, latest, unmount } = await loadNoteEditor(t);const propsWith = (key) => {@@ -311,7 +346,7 @@ test("the summary callout makes way for the transcript selection bar", async (t)enhanced_content: null,transcript: JSON.stringify([{ text: "Hello", source: "mic", timestamp: 0 }]),},- onGenerateSummary() {},+ onRunNoteAction() {},});findSegmentStrip(latest()).props.ref.current = measurableStrip(["transcript", "raw"]);await click("transcript");@@ -377,6 +412,34 @@ test("the note's chat learns who is viewing the note and its calendar event", asawait unmount();});+test("the note's chat names the user's own speakers and leaves attendees to the attendee block", async (t) => {+ t.after(() => {+ delete globalThis.__embeddedChatOptions;+ delete globalThis.__noteEditorAuth;+ });+ globalThis.__noteEditorAuth = {+ isSignedIn: true,+ user: { id: "user-chad", name: "Chad", email: "[email protected]" },+ };+ const { render, unmount } = await loadNoteEditor(t);+ const transcript = JSON.stringify([+ { text: "I'll send the deck.", source: "mic", timestamp: 0 },+ { text: "Thanks.", source: "system", timestamp: 3 },+ ]);+ const chatTranscript = () => globalThis.__embeddedChatOptions.noteTranscript;++ await render(ENHANCEMENT, { note: { ...NOTE, transcript } });+ assert.match(chatTranscript(), /Chad: I'll send the deck\./);+ assert.doesNotMatch(chatTranscript(), /Dana Wu|Invited participants/);++ // A teammate's recording: its mic lines are theirs, so the chat keeps it as stored.+ await render(ENHANCEMENT, {+ note: { ...NOTE, transcript, cloud_id: "cloud-1", owner_user_id: "user-alice" },+ });+ assert.equal(chatTranscript(), transcript);+ await unmount();+});+// The note's bottom bar: the element that receives the in-view chat as `chatContent`.function findBottomBar(tree) {let bar = null;diff --git a/test/helpers/builtinActionsDatabase.test.js b/test/helpers/builtinActionsDatabase.test.jsindex 5c32f1a04..643e66120 100644--- a/test/helpers/builtinActionsDatabase.test.js+++ b/test/helpers/builtinActionsDatabase.test.js@@ -3,7 +3,13 @@ const assert = require("node:assert/strict");const { createDb } = require("./harness/db.js");const DatabaseManager = require("../../src/helpers/database.js");-const { BUILTIN_ACTIONS } = require("../../src/helpers/builtinActions.js");+const {+ BUILTIN_ACTIONS,+ DETAILED_NOTES_KEY,+ FOLLOW_UP_EMAIL_KEY,+ GENERATE_NOTES_KEY,+ NOTE_ACTION_LIMITS,+} = require("../../src/helpers/builtinActions.js");const builtinRows = (db, translationKey) =>db.getActions().filter((row) => row.translation_key === translationKey);@@ -19,6 +25,19 @@ function relaunch(check) {}}+test("every built-in is named and described in English, matching its fallback text", () => {+ const { notes } = require("../../src/locales/en/translation.json");+ for (const action of BUILTIN_ACTIONS) {+ const key = action.translationKey.split(".").pop();+ assert.equal(notes.actions.builtin[key]?.name, action.name, action.translationKey);+ assert.equal(+ notes.actions.builtin[key]?.description,+ action.description,+ action.translationKey+ );+ }+});+test("no built-in lists its current prompt as a previous default", () => {for (const action of BUILTIN_ACTIONS) {assert.equal(action.previousPrompts.includes(action.prompt), false, action.name);@@ -34,6 +53,10 @@ for (const action of BUILTIN_ACTIONS) {const rows = builtinRows(db, translationKey);assert.equal(rows.length, 1);assert.equal(rows[0].prompt, action.prompt);+ assert.equal(rows[0].kind, action.kind);+ assert.equal(rows[0].output, action.output);+ assert.equal(rows[0].client_id, translationKey);+ assert.deepEqual(rows[0].sections, action.sections);});action.previousPrompts.forEach((previousPrompt, index) => {@@ -43,11 +66,16 @@ for (const action of BUILTIN_ACTIONS) {const db = createDb(t);if (!db) return;const { id } = builtinRows(db, translationKey)[0];- db.db.prepare("UPDATE actions SET prompt = ? WHERE id = ?").run(previousPrompt, id);+ // Rows from before templates had sections held a flat prompt.+ db.db+ .prepare("UPDATE actions SET prompt = ?, sections = NULL WHERE id = ?")+ .run(previousPrompt, id);db.db.close();relaunch((upgraded) => {- assert.equal(builtinRows(upgraded, translationKey)[0].prompt, action.prompt);+ const [row] = builtinRows(upgraded, translationKey);+ assert.equal(row.prompt, action.prompt);+ assert.deepEqual(row.sections, action.sections);});relaunch((steady) => {const rows = builtinRows(steady, translationKey);@@ -62,13 +90,174 @@ for (const action of BUILTIN_ACTIONS) {if (!db) return;const edited = `${previousPrompt}\nAlways use numbered lists.`;db.db- .prepare("UPDATE actions SET prompt = ? WHERE translation_key = ?")+ .prepare("UPDATE actions SET prompt = ?, sections = NULL WHERE translation_key = ?").run(edited, translationKey);db.db.close();relaunch((reopened) => {- assert.equal(builtinRows(reopened, translationKey)[0].prompt, edited);+ const [row] = builtinRows(reopened, translationKey);+ assert.equal(row.prompt, edited);+ assert.equal(row.sections, null, "an edited flat prompt stays flat");});});});}++test("launch puts the default AI Summary template first, under its current name", (t) => {+ const db = createDb(t);+ if (!db) return;+ // As main shipped them: Generate Notes first, and the default under its old name.+ db.db+ .prepare("UPDATE actions SET sort_order = 0 WHERE translation_key = ?")+ .run(GENERATE_NOTES_KEY);+ db.db+ .prepare("UPDATE actions SET sort_order = 1, name = 'Detailed Notes' WHERE translation_key = ?")+ .run(DETAILED_NOTES_KEY);+ db.db.close();++ relaunch((migrated) => {+ const [first, second] = migrated.getActions();+ assert.equal(first.translation_key, DETAILED_NOTES_KEY);+ assert.equal(first.name, "AI Summary");+ assert.equal(second.translation_key, GENERATE_NOTES_KEY);+ migrated.db+ .prepare("UPDATE actions SET name = 'Team notes' WHERE translation_key = ?")+ .run(DETAILED_NOTES_KEY);+ });+ relaunch((again) => {+ assert.equal(+ builtinRows(again, DETAILED_NOTES_KEY)[0].name,+ "Team notes",+ "the user's name stays"+ );+ });+});++test("an upgrade to sections keeps a name the user gave the default template", (t) => {+ const db = createDb(t);+ if (!db) return;+ const detailed = BUILTIN_ACTIONS.find((a) => a.translationKey === DETAILED_NOTES_KEY);+ db.db+ .prepare(+ "UPDATE actions SET name = 'Team notes', prompt = ?, sections = NULL WHERE translation_key = ?"+ )+ .run(detailed.previousPrompts.at(-1), DETAILED_NOTES_KEY);+ db.db.close();++ relaunch((migrated) => {+ const [row] = builtinRows(migrated, DETAILED_NOTES_KEY);+ assert.deepEqual(row.sections, detailed.sections, "the old default still moves to sections");+ assert.equal(row.name, "Team notes");+ });+});++test("a database from before templates and chat actions migrates on launch", (t) => {+ const db = createDb(t);+ if (!db) return;+ const editedEmail = "Write a short thank-you email.";+ db.db.prepare("UPDATE actions SET client_id = NULL, kind = 'template', output = NULL").run();+ db.db+ .prepare("UPDATE actions SET prompt = ? WHERE translation_key = ?")+ .run(editedEmail, FOLLOW_UP_EMAIL_KEY);+ db.db+ .prepare("INSERT INTO actions (name, description, prompt, sort_order) VALUES (?, '', ?, 9)")+ .run("Board summary", "Summarize for the board.");+ db.db.close();++ let customClientId;+ relaunch((migrated) => {+ const [email] = builtinRows(migrated, FOLLOW_UP_EMAIL_KEY);+ assert.equal(email.kind, "action");+ assert.equal(email.output, "chat");+ assert.equal(email.prompt, editedEmail, "the user's edit is kept");+ assert.equal(email.client_id, FOLLOW_UP_EMAIL_KEY);++ const custom = migrated.getActions().find((row) => row.name === "Board summary");+ assert.equal(custom.kind, "template", "a custom action always rewrote the summary");+ assert.equal(custom.prompt, "Summarize for the board.");+ assert.equal(custom.sections, null);+ assert.match(custom.client_id, /^[0-9a-f-]{36}$/);+ customClientId = custom.client_id;+ });+ relaunch((steady) => {+ const custom = steady.getActions().find((row) => row.name === "Board summary");+ assert.equal(custom.client_id, customClientId, "client ids are assigned once");+ });+});++test("templates and actions are validated and normalized when saved", (t) => {+ const db = createDb(t);+ if (!db) return;++ const sectioned = db.createAction("Sales call", "", "", undefined, {+ sections: [+ { heading: "## Needs ", instruction: " What they want " },+ { heading: " ", instruction: "dropped" },+ ],+ });+ assert.equal(sectioned.success, true);+ assert.equal(sectioned.action.kind, "template");+ assert.equal(sectioned.action.output, null);+ assert.deepEqual(sectioned.action.sections, [+ { heading: "Needs", instruction: "What they want" },+ ]);++ assert.equal(db.createAction("Empty", "", " ").success, false, "a template needs something");++ const action = db.createAction("Shorten", "", "Make it shorter.", undefined, {+ kind: "action",+ output: "summary",+ sections: [{ heading: "Ignored", instruction: "" }],+ });+ assert.equal(action.success, true);+ assert.equal(action.action.output, "summary");+ assert.equal(action.action.sections, null, "only templates have sections");+ assert.equal(+ db.createAction("Ask", "", "Draft it.", undefined, { kind: "action" }).action.output,+ "chat"+ );+ assert.equal(db.createAction("Nothing", "", "", undefined, { kind: "action" }).success, false);+ assert.equal(+ db.createAction("x".repeat(NOTE_ACTION_LIMITS.name + 1), "", "Too long a name.").success,+ false+ );++ const updated = db.updateAction(action.action.id, { output: "chat", kind: "template" });+ assert.equal(updated.success, true);+ assert.equal(updated.action.kind, "action", "a row's kind never changes");+ assert.equal(updated.action.output, "chat");++ const [detailed] = builtinRows(db, DETAILED_NOTES_KEY);+ assert.equal(db.updateAction(detailed.id, { sections: [] }).success, false);+});++test("an older build renaming the newer built-ins doesn't stop the next launch", (t) => {+ const db = createDb(t);+ if (!db) return;+ const newerKeys = ["notes.actions.builtin.makeTodos", "notes.actions.builtin.createOutline"];+ // What a build that predates Make to-dos and Create outline does to their rows.+ db.db+ .prepare(+ "UPDATE actions SET translation_key = ? WHERE is_builtin = 1 AND translation_key IN (?, ?)"+ )+ .run(GENERATE_NOTES_KEY, ...newerKeys);+ db.db.close();++ relaunch((upgraded) => {+ for (const key of [GENERATE_NOTES_KEY, ...newerKeys]) {+ assert.equal(builtinRows(upgraded, key).length, 1, key);+ }+ });+});++test("a built-in action pointed at the summary stays there across launches", (t) => {+ const db = createDb(t);+ if (!db) return;+ const [email] = builtinRows(db, FOLLOW_UP_EMAIL_KEY);+ assert.equal(db.updateAction(email.id, { output: "summary" }).success, true);+ db.db.close();++ relaunch((reopened) => {+ assert.equal(builtinRows(reopened, FOLLOW_UP_EMAIL_KEY)[0].output, "summary");+ });+});diff --git a/test/helpers/cloudSyncGuards.test.js b/test/helpers/cloudSyncGuards.test.jsindex f0cd14ec7..1286fe4ac 100644--- a/test/helpers/cloudSyncGuards.test.js+++ b/test/helpers/cloudSyncGuards.test.js@@ -59,6 +59,7 @@ const localNote = {content: "REAL MEETING NOTES",enhanced_content: "ENHANCED NOTES",enhancement_prompt: "prompt",+ enhancement_template_id: "notes.actions.builtin.detailedNotes",enhanced_at_content_hash: "hash-1",note_type: "meeting",source_file: null,@@ -86,6 +87,7 @@ test("the note update payload carries the full content, not just identifiers", aassert.equal(payload.enhanced_content, "ENHANCED NOTES");assert.equal(payload.transcript, '[{"text":"hello"}]');assert.equal(payload.enhancement_prompt, "prompt");+ assert.equal(payload.enhancement_template_id, "notes.actions.builtin.detailedNotes");assert.equal(payload.enhanced_at_content_hash, "hash-1");assert.equal(payload.note_type, "meeting");assert.equal(payload.audio_duration_seconds, 3130);diff --git a/test/helpers/modelManagerContextSizing.test.js b/test/helpers/modelManagerContextSizing.test.jsindex 4551b3dda..714ee2372 100644--- a/test/helpers/modelManagerContextSizing.test.js+++ b/test/helpers/modelManagerContextSizing.test.js@@ -326,6 +326,37 @@ test("a selection edit is refused rather than given a clipped answer", async (t)assert.equal(calls.completions, 0);});+test("a summary rewrite gets a smaller answer, but never a clipped one", async (t) => {+ // A rewrite replaces the whole summary, so it refuses any cut-off reply, but+ // a shorter allowance is fine: most edits (Shorten, TL;DR) need far less+ // room than they ask for.+ const rewrite = {+ systemPrompt: "Revise the summary.",+ maxTokens: 8192,+ requireCompleteOutput: true,+ refuseClippedByWindow: true,+ };+ const fits = await setup(t, { tokenCount: 13000, totalMemoryBytes: 8 * GIB });+ assert.equal(await fits.modelManager.runInference(fits.modelId, LONG_PROMPT, rewrite), "done");+ assert.equal(fits.completionBody().max_tokens, 16384 - 13000);++ const clipped = await setup(t, {+ tokenCount: 13000,+ totalMemoryBytes: 8 * GIB,+ finishReason: "length",+ });+ await assert.rejects(+ () => clipped.modelManager.runInference(clipped.modelId, LONG_PROMPT, rewrite),+ (error) => error.code === "CONTEXT_TOO_LARGE"+ );++ const cappedWithRoom = await setup(t, { tokenCount: 40, finishReason: "length" });+ await assert.rejects(+ () => cappedWithRoom.modelManager.runInference(cappedWithRoom.modelId, SHORT_PROMPT, rewrite),+ (error) => error.code === "OUTPUT_TRUNCATED"+ );+});+test("a reply the window clipped is refused when the caller asks, so it can be split", async (t) => {// A long note trades output room for prompt room. A summary that then fills// the smaller allowance was cut short by the window, and a note action woulddiff --git a/test/helpers/noteCloudUpsertGuard.test.js b/test/helpers/noteCloudUpsertGuard.test.jsindex 4018780b7..42bbcdb05 100644--- a/test/helpers/noteCloudUpsertGuard.test.js+++ b/test/helpers/noteCloudUpsertGuard.test.js@@ -65,6 +65,7 @@ function seedEditedMeetingNote(db) {content: "REAL MEETING NOTES",enhanced_content: "ENHANCED NOTES",enhancement_prompt: "summarize the meeting",+ enhancement_template_id: "notes.actions.builtin.detailedNotes",enhanced_at_content_hash: "hash-of-real-notes",transcript: TRANSCRIPT,cloud_id: "cloud-test-1",@@ -148,6 +149,11 @@ test("upsertNoteFromCloud: empty cloud values never destroy non-empty local cont"summarize the meeting","enhancement_prompt must travel with the preserved enhanced_content");+ assert.equal(+ after.enhancement_template_id,+ "notes.actions.builtin.detailedNotes",+ "the template id must travel with the preserved enhanced_content"+ );assert.equal(after.enhanced_at_content_hash,"hash-of-real-notes",@@ -215,3 +221,27 @@ test("upsertNoteFromCloud: a brand-new empty cloud note still inserts as-is", (tassert.equal(row.content, "");assert.equal(row.sync_status, "synced");});++test("upsertNoteFromCloud: a cloud copy from an API without template ids keeps the local one", (t) => {+ const db = createDb(t);+ if (!db) return;++ const before = seedEditedMeetingNote(db);+ const cloudNote = { ...emptyCloudShell(before), enhanced_content: "CLOUD ENHANCED" };+ assert.equal("enhancement_template_id" in cloudNote, false, "premise: an older API omits it");+ db.upsertNoteFromCloud(cloudNote, null);+ assert.equal(+ db.getNote(before.id).enhancement_template_id,+ "notes.actions.builtin.detailedNotes"+ );++ db.upsertNoteFromCloud(+ { ...cloudNote, enhancement_template_id: "c0ffee00-0000-4000-8000-000000000001" },+ null+ );+ assert.equal(+ db.getNote(before.id).enhancement_template_id,+ "c0ffee00-0000-4000-8000-000000000001",+ "a cloud copy that carries a template id brings its own"+ );+});diff --git a/test/helpers/noteFormattingProbe.test.js b/test/helpers/noteFormattingProbe.test.jsindex 25bc99dc5..1f92f6d9b 100644--- a/test/helpers/noteFormattingProbe.test.js+++ b/test/helpers/noteFormattingProbe.test.js@@ -26,9 +26,17 @@ test("the probe transcript is meeting-sized, deterministic and in the editor's ltest("the probe sends the Detailed Notes prompt exactly as the note store assembles it", async () => {const { buildNoteProbeSystemPrompt } = await load();- const { BUILTIN_ACTIONS, DETAILED_NOTES_KEY, MEETING_INPUT_PREAMBLE } =+ const { BUILTIN_ACTIONS, DETAILED_NOTES_KEY } =await import("../../src/helpers/builtinActions.js");+ const { compileTemplatePrompt } = await import("../../src/helpers/templatePrompts.js");const detailed = BUILTIN_ACTIONS.find((action) => action.translationKey === DETAILED_NOTES_KEY);+ // The row the database seeds from the built-in, as the note store reads it.+ const row = {+ prompt: detailed.prompt,+ sections: detailed.sections,+ translation_key: detailed.translationKey,+ };- assert.equal(buildNoteProbeSystemPrompt(), MEETING_INPUT_PREAMBLE + detailed.prompt);+ assert.equal(buildNoteProbeSystemPrompt(), compileTemplatePrompt(row, { isMeetingNote: true }));+ assert.match(buildNoteProbeSystemPrompt(), /\n## Action Items\n/);});diff --git a/test/helpers/templatePrompts.test.js b/test/helpers/templatePrompts.test.jsnew file mode 100644index 000000000..8c3eb5b8c--- /dev/null+++ b/test/helpers/templatePrompts.test.js@@ -0,0 +1,196 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = async () => ({+ ...(await import("../../src/helpers/builtinActions.js")),+ ...(await import("../../src/helpers/templatePrompts.js")),+});++// The row the database seeds from a built-in, as the note store reads it.+const seededRow = (builtin) => ({+ prompt: builtin.prompt,+ sections: builtin.sections,+ translation_key: builtin.translationKey,+});++test("Detailed Notes compiled from its sections is the prompt it replaced, but for its closing rule", async () => {+ const {+ BUILTIN_ACTIONS,+ DETAILED_NOTES_KEY,+ MEETING_INPUT_PREAMBLE,+ NOTE_INPUT_PREAMBLE,+ compileTemplatePrompt,+ } = await load();+ const detailed = BUILTIN_ACTIONS.find((action) => action.translationKey === DETAILED_NOTES_KEY);+ const flat = detailed.previousPrompts.at(-1);+ // The closing rule is its last paragraph: a note with nothing to summarize now+ // answers with a marker instead of a sentence that was saved as its summary.+ const body = flat.slice(0, flat.lastIndexOf("\n\n"));++ for (const [isMeetingNote, preamble] of [+ [true, MEETING_INPUT_PREAMBLE],+ [false, NOTE_INPUT_PREAMBLE],+ ]) {+ const compiled = compileTemplatePrompt(seededRow(detailed), { isMeetingNote });+ assert.ok(compiled.startsWith(preamble + body), "everything before the rule is unchanged");+ assert.match(+ compiled.slice((preamble + body).length),+ /^\n\nFor material with no substantive discussion[^\n]*reply with exactly NOTHING_TO_SUMMARIZE[^\n]*$/+ );+ }+});++test("a template without sections is sent exactly as before templates had sections", async () => {+ const {+ BUILTIN_ACTIONS,+ DETAILED_NOTES_KEY,+ GENERATE_NOTES_KEY,+ MEETING_INPUT_PREAMBLE,+ MEETING_SYSTEM_PROMPT,+ BASE_SYSTEM_PROMPT,+ compileTemplatePrompt,+ } = await load();+ const generate = BUILTIN_ACTIONS.find((action) => action.translationKey === GENERATE_NOTES_KEY);+ assert.equal(+ compileTemplatePrompt(seededRow(generate), { isMeetingNote: true }),+ MEETING_SYSTEM_PROMPT + generate.prompt+ );++ const editedDetailed = { prompt: "My own notes rules.", translation_key: DETAILED_NOTES_KEY };+ assert.equal(+ compileTemplatePrompt(editedDetailed, { isMeetingNote: true }),+ MEETING_INPUT_PREAMBLE + editedDetailed.prompt+ );++ const custom = { prompt: "Summarize for the board.", sections: null, translation_key: null };+ assert.equal(compileTemplatePrompt(custom), BASE_SYSTEM_PROMPT + custom.prompt);+});++test("a sectioned template puts its context before the format rules and keeps section order", async () => {+ const { SECTIONED_NOTES_FORMAT, compileTemplatePrompt } = await load();+ const prompt = compileTemplatePrompt(+ {+ prompt: "A weekly sales pipeline review.",+ sections: [+ { heading: "## Deals", instruction: "One bullet per deal." },+ { heading: "Risks", instruction: "" },+ ],+ },+ { isMeetingNote: true }+ );++ const context = prompt.indexOf("A weekly sales pipeline review.");+ const format = prompt.indexOf(SECTIONED_NOTES_FORMAT);+ const deals = prompt.indexOf("\n## Deals\nOne bullet per deal.");+ const risks = prompt.indexOf("\n## Risks\n\n");+ assert.ok(context > 0 && context < format && format < deals && deals < risks, prompt);+});++test("sections are trimmed, lose their Markdown heading marks, and need a heading", async () => {+ const { normalizeSections } = await load();+ assert.deepEqual(normalizeSections(null), []);+ assert.deepEqual(normalizeSections("not a list"), []);+ assert.deepEqual(+ normalizeSections([+ { heading: " ### Next steps ", instruction: " Owners and dates. " },+ { heading: " ", instruction: "No heading, so dropped." },+ { heading: "# # #", instruction: "Only heading marks, so dropped." },+ { heading: "#1 Priority", instruction: "A '#' in the text itself stays." },+ ]),+ [+ { heading: "Next steps", instruction: "Owners and dates." },+ { heading: "#1 Priority", instruction: "A '#' in the text itself stays." },+ ]+ );+});++const MATERIAL = {+ summary: "- shipped",+ notes: "ask about pricing",+ meetingContext: "## Meeting Context\nInvited participants: Alice.",+ transcript: "Alice: we ship Friday.",+};+const TEMPLATE = { kind: "template", prompt: "", sections: [{ heading: "A", instruction: "" }] };+const ACTION = { kind: "action", output: "summary", prompt: "Translate it to Spanish." };++test("a template always reads the transcript, never the summary it replaces", async () => {+ const { buildNoteRunInput } = await load();+ assert.deepEqual(buildNoteRunInput(TEMPLATE, MATERIAL), {+ input:+ "ask about pricing\n\n## Meeting Context\nInvited participants: Alice.\n\n## Meeting Transcript\nAlice: we ship Friday.",+ fromSummary: false,+ // In pieces too, for splitting a long recording on a local model.+ material: {+ notes: "ask about pricing",+ meetingContext: "## Meeting Context\nInvited participants: Alice.",+ transcript: "Alice: we ship Friday.",+ },+ });+});++test("an action reads the summary when there is one, and the transcript when there isn't", async () => {+ const { buildNoteRunInput } = await load();+ assert.deepEqual(buildNoteRunInput(ACTION, MATERIAL), {+ input:+ "## Current Summary\n- shipped\n\n## My Notes\nask about pricing\n\n## Meeting Context\nInvited participants: Alice.",+ fromSummary: true,+ });+ assert.deepEqual(+ buildNoteRunInput(ACTION, { ...MATERIAL, summary: " " }),+ buildNoteRunInput(TEMPLATE, MATERIAL),+ "without a summary, an action reads, and can split, the material a template does"+ );+ assert.equal(+ buildNoteRunInput(ACTION, {+ summary: "- shipped",+ notes: " ",+ meetingContext: "",+ transcript: "",+ }).input,+ "## Current Summary\n- shipped"+ );+});++test("a summary action revises the summary, or writes one from the material first", async () => {+ const { compileSummaryActionPrompt, MEETING_INPUT_PREAMBLE } = await load();+ assert.match(+ compileSummaryActionPrompt(ACTION, { fromSummary: true }),+ /^You revise an existing AI summary[\s\S]*Instructions: Translate it to Spanish\.$/+ );+ const fromMaterial = compileSummaryActionPrompt(ACTION, {+ fromSummary: false,+ isMeetingNote: true,+ });+ assert.ok(fromMaterial.startsWith(MEETING_INPUT_PREAMBLE));+ assert.match(fromMaterial, /no AI summary yet[\s\S]*Instructions: Translate it to Spanish\.$/);+ assert.match(+ fromMaterial,+ /reply with exactly NOTHING_TO_SUMMARIZE/,+ "a first summary can decline too"+ );+});++test("a chat action works from the summary when there is one, and the transcript when there isn't", async () => {+ const { compileChatActionPrompt } = await load();+ const action = { prompt: "List the to-dos." };+ assert.match(+ compileChatActionPrompt(action, { fromSummary: true }),+ /^Work from the AI summary[\s\S]*\n\nList the to-dos\.$/+ );+ assert.match(+ compileChatActionPrompt(action, { fromSummary: false }),+ /no AI summary yet, so work from its transcript and notes[\s\S]*\n\nList the to-dos\.$/+ );+ for (const fromSummary of [true, false]) {+ assert.match(+ compileChatActionPrompt(action, { fromSummary }),+ /answer here in the chat as text\. Don't use a tool to draft, send or post it/,+ "one click never sends an email or posts to Slack"+ );+ assert.match(+ compileChatActionPrompt(action, { fromSummary }),+ /in the language the note is written in, not the language of these instructions/,+ "the English action prompt doesn't turn a German note's answer into English"+ );+ }+});diff --git a/test/helpers/useChatStreamingTools.test.js b/test/helpers/useChatStreamingTools.test.jsindex 0b7d31123..d3dcb8851 100644--- a/test/helpers/useChatStreamingTools.test.js+++ b/test/helpers/useChatStreamingTools.test.js@@ -9,7 +9,7 @@ const { createRendererServer, installBrowserGlobals } = require("../lib/renderer// Drives the real useChatStreaming hook (one synchronous render, then its// sendToAI closure; see useChatStreamingCancellation.test.js) on the// OpenWhispr Cloud path, with the stream itself stubbed so the test can see-// which tools a send offers the model.+// which tools (and messages) a send offers the model.async function renderChatStreaming(t,hookOptions = {},@@ -49,10 +49,12 @@ async function renderChatStreaming(t.after(() => reasoningService.destroy());const offeredTools = [];+ const sentMessages = [];const endStream = async function* () {yield { type: "done", finishReason: "stop" };};- t.mock.method(reasoningService, "processTextStreamingCloud", (_messages, config) => {+ t.mock.method(reasoningService, "processTextStreamingCloud", (messages, config) => {+ sentMessages.push(messages);offeredTools.push((config.tools ?? []).map((tool) => tool.name));return endStream();});@@ -78,6 +80,7 @@ async function renderChatStreaming(return {captured,offeredTools,+ sentMessages,reasoningService,usePolicyStore,getMessages: () => messages,@@ -676,3 +679,29 @@ test("a failed attendee lookup still answers, without the block", async (t) => {assert.equal(prompts.length, 1);assert.doesNotMatch(prompts[0], /Meeting attendees/);});++test("a note action sends its prompt in place of the visible message, without searching other notes", async (t) => {+ const searches = [];+ const { captured, sentMessages } = await renderChatStreaming(+ t,+ {},+ {+ electronAPI: {+ semanticSearchNotes: async (query) => {+ searches.push(query);+ return [];+ },+ },+ }+ );+ const visible = { id: "u1", role: "user", content: "Draft a follow-up email" };+ const requestText = "Using the note I'm viewing, draft the follow-up email.";++ await captured.sendToAI(visible.content, [visible], { requestText });+ assert.equal(sentMessages[0].filter((m) => m.role === "user").at(-1).content, requestText);+ assert.deepEqual(searches, []);++ await captured.sendToAI(visible.content, [visible]);+ assert.equal(sentMessages[1].filter((m) => m.role === "user").at(-1).content, visible.content);+ assert.deepEqual(searches, [visible.content], "a typed question still searches the library");+});diff --git a/test/stores/actionProcessingChunked.test.js b/test/stores/actionProcessingChunked.test.jsindex 083bd1fc2..76253e306 100644--- a/test/stores/actionProcessingChunked.test.js+++ b/test/stores/actionProcessingChunked.test.js@@ -31,6 +31,7 @@ async function loadStore(updates.push({ noteId, payload });return { success: true };},+ getNote: async () => null,getLocalContextBudget: async (modelId) => {budgetCalls.push(modelId);if (budget instanceof Error) throw budget;@@ -175,6 +176,37 @@ test("refused material is summarised in parts, then merged with the action promp);});+test("a summary action writing a first summary splits a refused recording like a template", async (t) => {+ const { store, calls, updates } = await loadStore(t, { failFirst: true });+ const tldr = {+ id: 2,+ client_id: "tldr",+ kind: "action",+ output: "summary",+ name: "Add TL;DR",+ prompt: "Add a TL;DR.",+ };+ run(store, 30, longMaterial(400), { fromSummary: false }, tldr);+ await waitFor(() => updates.length > 0, "save");++ // A first summary has nothing to lose, so no request, part or not, demands a+ // complete reply: a verbose part is kept clipped, as for a template.+ assert.equal(calls[0].config.refuseClippedByWindow, true, "a long recording can split");+ const parts = calls.slice(1, -1);+ assert.ok(parts.length >= 2, "the recording ran in parts");+ for (const part of parts) {+ assert.ok(isPart(part.config));+ assert.equal(part.config.requireCompleteOutput, undefined);+ assert.equal(part.config.refuseClippedByWindow, false);+ }+ assert.equal(calls.at(-1).config.requireCompleteOutput, undefined);+ assert.match(calls.at(-1).config.systemPrompt, /no AI summary yet[\s\S]*Add a TL;DR\./);+ assert.deepEqual(Object.keys(updates[0].payload), [+ "enhanced_content",+ "enhanced_at_content_hash",+ ]);+});+test("a refusal whose budget cannot be read is reported without splitting", async (t) => {const { store, calls, updates } = await loadStore(t, {budget: new Error("ipc down"),@@ -582,29 +614,15 @@ test("an unbroken CJK part rejected by the tokenizer is split and merged withoutassert.equal(accepted.join(""), body);});-test("the merge preserves a follow-up email action without imposing exhaustive notes", async (t) => {- const { BUILTIN_ACTIONS } = await import("../../src/helpers/builtinActions.js");- const email = BUILTIN_ACTIONS.find(- (action) => action.translationKey === "notes.actions.builtin.followUpEmail"- );+test("the merge preserves a custom template's instructions without imposing exhaustive notes", async (t) => {+ const prompt = "Write the follow-up email I would send to the other participants.";const { store, calls, updates } = await loadStore(t, { failFirst: true });- run(- store,- 16,- longMaterial(20),- {},- {- id: 2,- name: email.name,- prompt: email.prompt,- translation_key: email.translationKey,- }- );+ run(store, 16, longMaterial(20), {}, { id: 2, kind: "template", name: "Follow-up", prompt });await waitForResult(store, updates);assert.equal(updates.length, 1);- const prompt = calls.at(-1).config.systemPrompt;- assert.ok(prompt.includes(email.prompt));- assert.doesNotMatch(prompt, /Completeness outranks brevity|as long as that requires/);+ const systemPrompt = calls.at(-1).config.systemPrompt;+ assert.ok(systemPrompt.includes(prompt));+ assert.doesNotMatch(systemPrompt, /Completeness outranks brevity|as long as that requires/);});test("a local model reached through dictation cleanup is summarised in parts too", async (t) => {diff --git a/test/stores/actionProcessingNoteOutput.test.js b/test/stores/actionProcessingNoteOutput.test.jsindex 665a31dda..1e655dd90 100644--- a/test/stores/actionProcessingNoteOutput.test.js+++ b/test/stores/actionProcessingNoteOutput.test.js@@ -9,16 +9,29 @@ const { createRendererServer, installBrowserGlobals } = require("../lib/rendererconst ACTION = { id: 1, name: "Generate Notes", prompt: "Summarize the meeting." };const LABELS = { noModel: "no model", noEndpoint: "no endpoint", actionFailed: "failed" };+const STORED_NOTE = {+ title: "Untitled Note",+ enhanced_content: "- the summary before the run",+ enhancement_prompt: "the prompt before the run",+ enhancement_template_id: "the template before the run",+ enhanced_at_content_hash: "the hash before the run",+};-async function loadStore(t) {+async function loadStore(t, storedNote = STORED_NOTE) {const updates = [];installBrowserGlobals(t, {window: {electronAPI: {updateNote: async (noteId, payload) => {updates.push({ noteId, payload });- return { success: true };+ return { success: !globalThis.__updateNoteFails };},+ // What the database holds now, so a snapshot read after the write would show it.+ getNote: async (noteId) =>+ Object.assign(+ { id: noteId, ...storedNote },+ ...updates.filter((u) => u.noteId === noteId).map((u) => u.payload)+ ),},},});@@ -31,17 +44,28 @@ async function loadStore(t) {export default {processText: async (text, model, agentName, config) => {globalThis.__processTextCalls.push({ text, model, config });+ if (globalThis.__processTextError) throw globalThis.__processTextError;return globalThis.__processTextResult ?? "# Notes\\n- decided things";},};`,- "/utils/generateTitle": `export const generateNoteTitle = async () => undefined;`,+ "/utils/generateTitle": `+ export const generateNoteTitle = async () => {+ globalThis.__titleRequests += 1;+ return globalThis.__generatedTitle;+ };+ `,},});globalThis.__processTextCalls = calls;+ globalThis.__titleRequests = 0;t.after(() => {delete globalThis.__processTextCalls;delete globalThis.__processTextResult;+ delete globalThis.__processTextError;+ delete globalThis.__generatedTitle;+ delete globalThis.__titleRequests;+ delete globalThis.__updateNoteFails;});const store = await vite.ssrLoadModule("/stores/actionProcessingStore.ts");@@ -135,3 +159,304 @@ test("note formatting requests carry the noteFormatting scope, which is what buyawait waitFor(() => updates.length > 0, "the note to be written");assert.equal(calls[0].config.inferenceScope, "noteFormatting");});++test("a template writes the summary and records which template produced it", async (t) => {+ const { store, calls, updates } = await loadStore(t);+ const template = {+ id: 3,+ client_id: "c0ffee00-0000-4000-8000-000000000001",+ kind: "template",+ name: "Sales call",+ prompt: "",+ sections: [{ heading: "Objections", instruction: "Each objection and the answer." }],+ };++ store.runBackgroundAction(+ 11,+ "## Meeting Transcript\nThem: the price is too high.",+ "hash-11",+ template,+ { modelId: "gpt-4.1", isCloudMode: true, isMeetingNote: true },+ LABELS+ );++ await waitFor(() => updates.length > 0, "the note to be written");+ assert.match(calls[0].config.systemPrompt, /\n## Objections\nEach objection and the answer\./);+ const { payload } = updates[0];+ assert.equal(payload.enhancement_template_id, template.client_id);+ assert.equal(payload.enhanced_at_content_hash, "hash-11");+ assert.match(payload.enhancement_prompt, /## Objections/);+});++test("a summary action rewrites only the summary and never saves a clipped rewrite", async (t) => {+ const { store, calls, updates } = await loadStore(t);+ const action = {+ id: 4,+ client_id: "c0ffee00-0000-4000-8000-000000000002",+ kind: "action",+ output: "summary",+ name: "Shorten",+ prompt: "Make it half as long.",+ };++ store.runBackgroundAction(+ 12,+ "## Current Summary\n- decided things",+ "hash-12",+ action,+ {+ modelId: "gpt-4.1",+ isCloudMode: true,+ isMeetingNote: true,+ allowTitleGeneration: true,+ fromSummary: true,+ },+ LABELS+ );++ await waitFor(() => updates.length > 0, "the note to be written");+ assert.equal(calls.length, 1);+ assert.match(calls[0].config.systemPrompt, /revise an existing AI summary[\s\S]*half as long/);+ assert.equal(calls[0].config.requireCompleteOutput, true);+ assert.equal(+ calls[0].config.refuseClippedByWindow,+ true,+ "a local model shortens the reply to fit rather than refusing up front"+ );+ const { NOTE_OUTPUT_MAX_TOKENS } = await import("../../src/helpers/builtinActions.js");+ assert.equal(+ calls[0].config.maxTokens,+ 2 * NOTE_OUTPUT_MAX_TOKENS,+ "a rewrite has room to repeat a summary written under the note cap"+ );+ // The template and material hash stay those of the summary being edited.+ assert.deepEqual(Object.keys(updates[0].payload), ["enhanced_content"]);+});++test("a cut-off or empty rewrite reports a notes error, not the dictation one providers attach", async (t) => {+ const { store, updates } = await loadStore(t);+ const { EMPTY_OUTPUT_MESSAGE_KEY, TRUNCATED_OUTPUT_MESSAGE_KEY } =+ await import("../../src/services/ai/chatRequestBody.ts");++ for (const [noteId, providerKey, noteKey] of [+ [13, TRUNCATED_OUTPUT_MESSAGE_KEY, "notes.actions.errors.outputTruncated"],+ [14, EMPTY_OUTPUT_MESSAGE_KEY, "notes.actions.emptyReply"],+ ]) {+ globalThis.__processTextError = Object.assign(new Error("Provider refused the reply"), {+ messageKey: providerKey,+ });++ store.runBackgroundAction(+ noteId,+ "## Current Summary\n- decided things",+ `hash-${noteId}`,+ {+ id: 5,+ client_id: "shorten",+ kind: "action",+ output: "summary",+ name: "Shorten",+ prompt: "x",+ },+ { modelId: "gpt-4.1", isCloudMode: true, isMeetingNote: true, fromSummary: true },+ LABELS+ );++ let events = [];+ await waitFor(() => (events = store.consumeErrorEvents()).length > 0, "the error");+ assert.equal(events[0].messageKey, noteKey);+ }+ assert.equal(updates.length, 0);+});++test("a summary action on a note without a summary writes one from the transcript, and tracks it for staleness", async (t) => {+ const { store, calls, updates } = await loadStore(t);+ const action = {+ id: 6,+ client_id: "tldr",+ kind: "action",+ output: "summary",+ name: "TL;DR",+ prompt: "Add a TL;DR.",+ };++ store.runBackgroundAction(+ 14,+ "## Meeting Transcript\nAlice: we ship Friday.",+ "hash-14",+ action,+ { modelId: "gpt-4.1", isCloudMode: true, isMeetingNote: true, fromSummary: false },+ LABELS+ );++ await waitFor(() => updates.length > 0, "the note to be written");+ assert.match(calls[0].config.systemPrompt, /no AI summary yet[\s\S]*Add a TL;DR\.$/);+ assert.equal(calls[0].text, "## Meeting Transcript\nAlice: we ship Friday.");+ assert.equal(calls[0].config.requireCompleteOutput, undefined, "nothing to lose yet");+ assert.deepEqual(Object.keys(updates[0].payload), [+ "enhanced_content",+ "enhanced_at_content_hash",+ ]);+ assert.equal(updates[0].payload.enhanced_at_content_hash, "hash-14");+});++test("a run hands Undo the summary fields it overwrote, and the title when it renamed the note", async (t) => {+ const { store, updates } = await loadStore(t);+ const summaryFields = {+ enhanced_content: STORED_NOTE.enhanced_content,+ enhancement_prompt: STORED_NOTE.enhancement_prompt,+ enhancement_template_id: STORED_NOTE.enhancement_template_id,+ enhanced_at_content_hash: STORED_NOTE.enhanced_at_content_hash,+ };+ const shorten = {+ id: 7,+ client_id: "shorten",+ kind: "action",+ output: "summary",+ name: "Shorten",+ prompt: "x",+ };+ const options = { modelId: "gpt-4.1", isCloudMode: true, isMeetingNote: true };++ store.runBackgroundAction(+ 15,+ "## Current Summary\n- a",+ "hash-15",+ shorten,+ { ...options, fromSummary: true },+ LABELS+ );+ await waitFor(() => updates.length === 1, "the rewrite to be written");+ assert.deepEqual(store.consumeAppliedEvents(), [+ { noteId: 15, action: shorten, previous: summaryFields },+ ]);++ globalThis.__generatedTitle = "Q3 launch sync";+ store.runBackgroundAction(+ 16,+ "notes",+ "hash-16",+ ACTION,+ { ...options, allowTitleGeneration: true },+ LABELS+ );+ await waitFor(() => updates.length === 2, "the template run to be written");+ assert.equal(updates[1].payload.title, "Q3 launch sync");+ const [{ previous }] = store.consumeAppliedEvents();+ assert.deepEqual(previous, { ...summaryFields, title: STORED_NOTE.title });+});++test("Undo of a first summary clears it with an empty string, which sync can't ignore", async (t) => {+ // The API keeps its copy when a push sends null (COALESCE), so a null here+ // would bring the undone summary back on the next pull.+ const { store, updates } = await loadStore(t, {+ title: "Untitled Note",+ enhanced_content: null,+ enhancement_prompt: null,+ enhancement_template_id: null,+ enhanced_at_content_hash: null,+ });+ store.runBackgroundAction(+ 31,+ "notes",+ "hash-31",+ ACTION,+ { modelId: "gpt-4.1", isCloudMode: true, isMeetingNote: false },+ LABELS+ );+ await waitFor(() => updates.length === 1, "the first summary to be written");+ const [{ previous }] = store.consumeAppliedEvents();+ assert.equal(previous.enhanced_content, "");+});++test("a write the database refused offers no Undo and reports the failure", async (t) => {+ const { store, updates } = await loadStore(t);+ globalThis.__updateNoteFails = true;+ store.runBackgroundAction(+ 17,+ "notes",+ "hash-17",+ ACTION,+ { modelId: "gpt-4.1", isCloudMode: true, isMeetingNote: false },+ LABELS+ );+ let errors = [];+ await waitFor(() => (errors = store.consumeErrorEvents()).length > 0, "the error");+ assert.equal(errors[0].message, LABELS.actionFailed);+ assert.deepEqual(store.consumeAppliedEvents(), []);+});++test("material with nothing to summarize leaves the note as it was and says so", async (t) => {+ const { store, calls, updates } = await loadStore(t);+ globalThis.__generatedTitle = "Should not be asked for";++ const replies = [+ "NOTHING_TO_SUMMARIZE",+ "**NOTHING_TO_SUMMARIZE**",+ "```markdown\nNOTHING_TO_SUMMARIZE\n```",+ "Only greetings were exchanged.\n\nNOTHING_TO_SUMMARIZE",+ "<think>Just hellos.</think>\nNOTHING_TO_SUMMARIZE",+ ];+ for (const [index, reply] of replies.entries()) {+ const noteId = 18 + index;+ globalThis.__processTextResult = reply;+ store.runBackgroundAction(+ noteId,+ "## Meeting Transcript\nYou: Hi, can you hear me?",+ `hash-${noteId}`,+ ACTION,+ { modelId: "gpt-4.1", isCloudMode: true, isMeetingNote: true, allowTitleGeneration: true },+ LABELS+ );+ let errors = [];+ await waitFor(() => (errors = store.consumeErrorEvents()).length > 0, "the notice");+ assert.equal(errors[0].messageKey, "notes.actions.errors.nothingToSummarize", reply);+ assert.equal(errors[0].notice, true, "not a failure");+ }+ assert.equal(calls.length, replies.length, "one request per run");+ assert.equal(globalThis.__titleRequests, 0, "no title request");+ assert.deepEqual(updates, [], "nothing is written");+ assert.deepEqual(store.consumeAppliedEvents(), [], "nothing to undo");+});++test("the marker only in the model's thinking still saves the summary", async (t) => {+ const { store, updates } = await loadStore(t);+ globalThis.__processTextResult =+ "<think>NOTHING_TO_SUMMARIZE? No, they set a date.</think>\n# Notes\n- ship Friday";++ store.runBackgroundAction(+ 30,+ "## Meeting Transcript\nYou: We ship Friday.",+ "hash-30",+ ACTION,+ { modelId: "gpt-4.1", isCloudMode: true, isMeetingNote: true },+ LABELS+ );+ await waitFor(() => updates.length > 0, "the summary write");+ assert.deepEqual(store.consumeErrorEvents(), []);+});++test("a summary that merely contains the marker is still saved", async (t) => {+ const { store, updates } = await loadStore(t);+ const summaries = [+ // A small model answering one empty section with the marker.+ "## Summary\n- We agreed to ship on Friday.\n\n## Decisions\nNOTHING_TO_SUMMARIZE",+ "- We agreed to ship on Friday.\n- NOTHING_TO_SUMMARIZE",+ "# Notes\n- The marker NOTHING_TO_SUMMARIZE confused the parser.\n- Ship Friday.",+ ];+ for (const [index, reply] of summaries.entries()) {+ const noteId = 40 + index;+ globalThis.__processTextResult = reply;+ store.runBackgroundAction(+ noteId,+ "## Meeting Transcript\nYou: We ship Friday.",+ `hash-${noteId}`,+ ACTION,+ { modelId: "gpt-4.1", isCloudMode: true, isMeetingNote: true },+ LABELS+ );+ await waitFor(() => updates.length === index + 1, "the summary write");+ assert.equal(updates[index].payload.enhanced_content, reply);+ }+ assert.deepEqual(store.consumeErrorEvents(), []);+});diff --git a/test/utils/inferActionOutput.test.js b/test/utils/inferActionOutput.test.jsnew file mode 100644index 000000000..aeadd412c--- /dev/null+++ b/test/utils/inferActionOutput.test.js@@ -0,0 +1,55 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++async function loadInfer(t, reply) {+ installBrowserGlobals(t);+ const calls = [];+ globalThis.__inferCalls = calls;+ globalThis.__inferReply = reply;+ t.after(() => {+ delete globalThis.__inferCalls;+ delete globalThis.__inferReply;+ });+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-infer-action-output-test-",+ mockModules: {+ "/services/ReasoningService": `+ export default {+ processText: async (text, model, agentName, config) => {+ globalThis.__inferCalls.push({ text, model, config });+ const reply = globalThis.__inferReply;+ if (reply instanceof Error) throw reply;+ return reply;+ },+ };+ `,+ },+ });+ const { inferActionOutput } = await vite.ssrLoadModule("/utils/inferActionOutput.ts");+ return { inferActionOutput, calls };+}++test("an action that changes the summary is inferred as a summary action", async (t) => {+ const { inferActionOutput, calls } = await loadInfer(t, "SUMMARY");+ assert.equal(await inferActionOutput("Translate it to Spanish.", "gpt-4.1", true), "summary");+ assert.equal(calls[0].text, "Translate it to Spanish.");+ assert.equal(calls[0].config.inferenceScope, "noteFormatting", "asks the note model");+ assert.equal(calls[0].config.disableThinking, true, "thinking text would hide the answer");+});++test("a reply is read by its first word, whatever the case or punctuation", async (t) => {+ const { inferActionOutput } = await loadInfer(t, " summary.");+ assert.equal(await inferActionOutput("Shorten it.", "gpt-4.1", true), "summary");+ globalThis.__inferReply = "<think>Could be chat, but it rewrites the summary.</think>\nSUMMARY";+ assert.equal(await inferActionOutput("Make it longer.", "gpt-4.1", true), "summary");+ globalThis.__inferReply = "CHAT — it writes an email, not the summary";+ assert.equal(await inferActionOutput("Draft an email.", "gpt-4.1", true), "chat");+});++test("without an answer, an action answers in chat and leaves the summary alone", async (t) => {+ const { inferActionOutput } = await loadInfer(t, new Error("no model"));+ assert.equal(await inferActionOutput("Anything.", "", false), "chat");+ globalThis.__inferReply = "";+ assert.equal(await inferActionOutput("Anything.", "gpt-4.1", true), "chat");+});