AI-native design editor. Open-source Figma alternative.
feat: compact chat conversations and show how full the context is (#1673)
Danila Poyarkovdc34628006b1
diff --git a/changes/1673/added.md b/changes/1673/added.mdnew file mode 100644index 000000000..52f09c59f--- /dev/null+++ b/changes/1673/added.md@@ -0,0 +1 @@+- The AI chat compacts long conversations: the model summarizes what came before, automatically before the context window fills up, also between the steps of a long reply, from the new context meter in the chat header, or with `/compact`, and a request that is already too long offers Compact and retry. With Pi, `/compact` asks Pi to compact its own context, and the transcript shows where it did. Replies show the tokens they used on hover.diff --git a/changes/1673/changed.md b/changes/1673/changed.mdnew file mode 100644index 000000000..82fdb056c--- /dev/null+++ b/changes/1673/changed.md@@ -0,0 +1 @@+- Model settings open from the chat's model picker instead of a gear beside the message field.diff --git a/packages/core/src/ai/providers.ts b/packages/core/src/ai/providers.tsindex ebdc4b64b..5bc95c006 100644--- a/packages/core/src/ai/providers.ts+++ b/packages/core/src/ai/providers.ts@@ -83,6 +83,8 @@ export interface ModelOption {tag?: stringcapabilities?: readonly ('tools' | 'vision')[]recommendedMaxOutputTokens?: number+ /** Tokens a request may hold, prompt and reply together, as the provider's catalog gives it. */+ contextWindow?: numberreleaseDate?: stringstatus?: 'active' | 'beta' | 'deprecated'/** Lowest reasoning effort the model accepts; lower thinking levels, Off included, use it. */diff --git a/packages/docs/development/ai-chat.md b/packages/docs/development/ai-chat.mdindex 474d46f3d..bda49ce52 100644--- a/packages/docs/development/ai-chat.md+++ b/packages/docs/development/ai-chat.md@@ -20,7 +20,7 @@ A message that starts with `/skill:name` runs that skill, as in pi: the request## References-Messages name layers, pages, and skills with Markdown links in the `openpencil:` scheme, `[Hero](openpencil://node/12:34)` (`chat/references/link.ts`), in both directions: the composer inserts them and the system prompt asks the model to cite what it touched the same way. The composer is a CodeMirror field (`components/chat/composer/`), built like the variable formula field: `@` completes layers (the current page's first, then other loaded pages'), pages, and skills (`references/candidates.ts`), and `/` at the start of a message completes the skills the user can run, or an ACP agent's own commands from `available_commands_update` (`agents/acp/commands.ts`). A reference shows as a chip that edits as one unit. The transcript renders the same chip (`ChatReferenceChip`): replies get references rewritten to an inline `chat-reference` component before Markdown renders them, so other links keep the renderer's own handling, and the user's text is split around them. The selection button inserts the selected layers as references, and the layers a message mentions go with it as previews (`references/nodes.ts`), rebuilt from the text when a sent message is edited, which also runs a `/skill:` again; a message with images still cannot be edited. Hovering a layer chip outlines the layer on the canvas. A chip follows renames, shows its written label once its target is gone, and on click shows the layer on its page, switches to the page, or opens the skill in Settings › Skills; a conversation from another document resolves nothing by ID.+Messages name layers, pages, and skills with Markdown links in the `openpencil:` scheme, `[Hero](openpencil://node/12:34)` (`chat/references/link.ts`), in both directions: the composer inserts them and the system prompt asks the model to cite what it touched the same way. The composer is a CodeMirror field (`components/chat/composer/`), built like the variable formula field: `@` completes layers (the current page's first, then other loaded pages'), pages, and skills (`references/candidates.ts`), and `/` at the start of a message completes the chat's own commands such as `/compact` and the skills the user can run, or an ACP agent's own commands from `available_commands_update` (`agents/acp/commands.ts`). A chosen command is a reference too, of the `command` kind (`references/command.ts`): the chat reads `/compact` and `/skill:` from the link at the message's start (`leadingCommand`), never by matching typed text, and agents and models get it written out (`commandsAsText`). Typing a command's whole name then a space picks it from the open list, so it becomes the same chip. A reference shows as a chip that edits as one unit. The transcript renders the same chip (`ChatReferenceChip`): replies get references rewritten to an inline `chat-reference` component before Markdown renders them, so other links keep the renderer's own handling, and the user's text is split around them. The selection button inserts the selected layers as references, and the layers a message mentions go with it as previews (`references/nodes.ts`), rebuilt from the text when a sent message is edited, which also runs a `/skill:` again; a message with images still cannot be edited. Hovering a layer chip outlines the layer on the canvas. A chip follows renames, shows its written label once its target is gone, and on click shows the layer on its page, switches to the page, or opens the skill in Settings › Skills; a conversation from another document resolves nothing by ID.## Messages while the agent works@@ -91,6 +91,14 @@ Edit → Undo and the chat's **Revert changes** therefore end in the same state:A reply's metadata (`chat/metadata.ts`) keeps whether you stopped it, and its edits with those undone and what the model was last told. Conversations save messages with `structuredClone`, so metadata is written from the plain message, never from the chat's reactive copy. Reopening a conversation settles any reply saved mid-way. The undo history does not survive closing a document, so a reopened reply keeps its marks but offers no Revert or Restore.+## Compaction++A compaction is a message in the conversation (`chat/compaction/marker.ts`): a user message whose text is the summary and whose metadata marks it, so the transcript draws a divider and any backend that knows nothing of compaction still reads the summary. `messagesSinceCompaction` gives what a model reads, from the latest marker on; the tool loop sends only that. Undo notes still cover edits before it, which the summary describes as made. Saved conversations keep every message, so nothing changes in storage.++`chat/compaction/use.ts` runs it: the Design model summarizes the conversation (`summarize.ts`, with `prompt.md`), from a copy without images and with long tool results cut, so a conversation too long for its model can still be summarized; the marker is added only once the summary arrives, so a failed or cancelled compaction leaves the conversation as it was. One compaction runs at a time, and a message sent meanwhile waits for it. Before a message is sent, `compactIfFull` compacts when the last request since the latest marker, with the outgoing text estimated, passes `autoCompactAt` (`limits.ts`): the context window, from the model catalogs' `contextWindow`, less the whole reply allowance up to half the window, of which a tenth is kept for the next message. Compact and retry compacts only what came before the failed request, which stays after the summary to be asked again. Each reply keeps its token usage in its metadata (`usage`), written by the tool loop's `messageMetadata`, which the context meter and the reply's token line read. A provider error for a prompt past the window classifies as `context-limit`, whose notice offers Compact and retry.++Within one reply, `steps.ts` compacts between steps through the tool loop's `prepareStep`: when the last step's request passed the threshold, everything before that step's call and results becomes a summary of the model messages, and the step goes on from the summary and those. The reply records its compactions in its metadata as a list (`compactions`), each with the step it kept (`step`). The whole list is sent with each step's start, since a merge replaces it; `messagesSinceCompaction` then gives the summary and the reply from that step on, the reply draws the divider there, and `trace/rebuild.ts` rebuilds the later steps from the summary. Pi compacts its own context: `session.compact` in the harness protocol asks it to. `@ai-sdk/harness-pi` queues the `compaction` part of a compaction between turns and never delivers it. So once Pi confirms, the chat adds its own marker flagged `agent`, without a summary. `messagesSinceCompaction` skips that marker, and the Pi transport ignores manual reports. The compactions Pi runs on its own during a turn reach the reply as the same `compactions` metadata. ACP agents compact their own context.+## TracesSave trace… in the conversation menu writes a file to reproduce what the agent did (`chat/trace/export.ts`). It holds the conversation's messages, its runs, and its diagnostic events.diff --git a/packages/docs/programmable/ai-chat.md b/packages/docs/programmable/ai-chat.mdindex ca5c6eab6..f254b5473 100644--- a/packages/docs/programmable/ai-chat.md+++ b/packages/docs/programmable/ai-chat.md@@ -12,13 +12,13 @@ Press <kbd>⌘</kbd><kbd>J</kbd> (<kbd>Ctrl</kbd> + <kbd>J</kbd>) to open the AIThe first time you open OpenPencil, guided setup asks what AI should help with and what you already use: a [coding agent](./coding-agents) such as Claude Code, Codex, Gemini CLI, or Pi in the desktop app, an API account, or a local or company server. It connects that access and assigns it to the **Design agent** and **Vision** roles, keeping anything you configured by hand. With OpenRouter you can sign in instead of pasting an API key. Skip it to start designing, and run it again from **Settings → Models → Run guided setup**. To configure models by hand:1. Open the AI chat panel (<kbd>⌘</kbd><kbd>J</kbd>)-2. Click the settings icon+2. Open the model picker under the message field and choose **Manage models and roles…**3. Add a model and configure its provider, model ID, credentials, and capabilities4. Save the model and assign it to **Design agent**You can configure multiple reusable models and separately assign models for design work, reviews, fast tasks, and image input. Models using the same provider connection reuse its stored credential.-The chat composer grows with multiline prompts. Type `@` to mention a layer, page, or skill, or use the selection button to mention the selected layers, and `/` at the start of a message to run a skill, or one of an ACP agent's commands. Mentions show as chips, in replies too, where the assistant names the layers it touched; click one to show the layer on the canvas. Assistant messages show provider reasoning in collapsible sections and provide a per-response copy action. Image attachments remain available for visual references when a Vision model is configured. Streaming responses use a hardened Markdown renderer with Shiki-highlighted code blocks; unsafe link protocols and embedded data images are blocked.+The chat composer grows with multiline prompts. Type `@` to mention a layer, page, or skill, and `/` at the start of a message to run a skill, `/compact`, or one of an ACP agent's commands. Mentions show as chips, in replies too, where the assistant names the layers it touched; click one to show the layer on the canvas. Assistant messages show provider reasoning in collapsible sections and provide a per-response copy action. Image attachments remain available for visual references when a Vision model is configured. Streaming responses use a hardened Markdown renderer with Shiki-highlighted code blocks; unsafe link protocols and embedded data images are blocked.## Step limit@@ -102,6 +102,14 @@ The configurable tool catalog covers these categories; the tools offered to a moThe assistant can verify its work visually. With `export_image`, on by default, it can capture a screenshot after creating or modifying designs and checks the result against the original request. This catches layout issues, missing elements, and color mismatches that text-only responses would miss. `diff_visual`, enabled by default, compares an edited node with a reference copy and returns the changed pixels and region, so the assistant can confirm an edit stayed within its target.+## Context and compaction++A model reads a limited amount of conversation at once, its context window. With a model the chat calls itself, the header shows how full the window is; click it for the token count, when the conversation compacts, and the Cloud credits left. When the window is nearly full, a bar over the message field offers to compact.++Compacting asks the conversation's model for a summary, which then stands for everything before it: later requests send the summary and what followed, while the transcript keeps every message, with a divider where the summary opens. **Compact automatically** in **Settings → Chat**, on by default, compacts before a message would leave too little room for the reply, and between the steps of a long reply whose tool calls fill the window, where the divider then appears inside the reply. `/compact` compacts at once, and instructions after it say what the summary should keep. A compaction that fails changes nothing and offers Retry; a request that is already too long for the model offers **Compact and retry**. Pi keeps its own context: `/compact` asks Pi to compact it, and a divider appears once Pi confirms. Pi reports no summary of it, so the divider has none to open. When Pi compacts on its own during a reply, the divider appears inside the reply with Pi's summary. ACP agents compact their own context too, and an ACP agent's own `/compact` reaches it as written.++Hover a reply to see the tokens it used; **Settings → Chat → Token usage** shows them always or never.+## Messages while the assistant worksYou can keep typing while a reply runs. **Enter** sends the message as soon as the current step's tool calls finish, so the built-in AI can change course without being stopped; **Alt+Enter** waits until it has finished all work. Waiting messages show dimmed below the reply, with a button to remove each. **Escape** stops the reply and sends what is waiting at once, and **Up** on the first line takes waiting messages back to edit. ACP agents and Pi take a waiting message once their turn ends.diff --git a/packages/harness/src/backends/pi.ts b/packages/harness/src/backends/pi.tsindex f20455a6c..f5cafc7f7 100644--- a/packages/harness/src/backends/pi.ts+++ b/packages/harness/src/backends/pi.ts@@ -32,7 +32,28 @@ function asJSONValue(value: unknown): JSONValue {}}+/** The harness reports a compaction as a call and result of its own `compaction` tool. */+function isCompaction(part: { toolName: string; toolCallId: string }): boolean {+ return part.toolName === 'compaction' && part.toolCallId.startsWith('harness-compaction-')+}++function compactionEvent(output: unknown): BackendEvent | undefined {+ if (typeof output !== 'object' || output === null) return undefined+ if (!('summary' in output) || typeof output.summary !== 'string') return undefined+ if (!('trigger' in output) || (output.trigger !== 'manual' && output.trigger !== 'auto'))+ return undefined+ const tokensBefore = 'tokensBefore' in output ? output.tokensBefore : undefined+ return {+ type: 'compaction',+ trigger: output.trigger,+ summary: output.summary,+ tokensBefore: typeof tokensBefore === 'number' ? tokensBefore : null+ }+}+function mapPart(part: TextStreamPart<ToolSet>): BackendEvent | undefined {+ if ((part.type === 'tool-call' || part.type === 'tool-result') && isCompaction(part))+ return part.type === 'tool-result' ? compactionEvent(part.output) : undefinedif (part.type === 'text-delta') return { type: 'text-delta', text: part.text }if (part.type === 'reasoning-delta') return { type: 'reasoning-delta', text: part.text }if (part.type === 'tool-call') {@@ -93,6 +114,10 @@ class PiBackendSession implements BackendSession {}}+ async compact(instructions?: string): Promise<void> {+ await this.session.compact(instructions)+ }+async stop(): Promise<HarnessResumeState> {return (await this.session.stop()) as HarnessResumeState}diff --git a/packages/harness/src/backends/types.ts b/packages/harness/src/backends/types.tsindex 269b2c0a4..ea59acbc8 100644--- a/packages/harness/src/backends/types.ts+++ b/packages/harness/src/backends/types.ts@@ -1,5 +1,6 @@import type {HarnessAdapterID,+ HarnessCompactionEvent,HarnessProviderCapability,HarnessSessionConfiguration,HarnessTurnUsage,@@ -18,6 +19,8 @@ export interface BackendSession {readonly sessionId: stringreadonly isResume: booleanrunTurn(prompt: string, signal?: AbortSignal): AsyncIterable<BackendEvent>+ /** Asks the agent to compact its context; the summary arrives on its next or active turn. */+ compact(instructions?: string): Promise<void>stop(): Promise<HarnessResumeState>destroy(): Promise<void>}@@ -28,6 +31,7 @@ export type BackendEvent =| { type: 'tool-call'; toolCallId: string; toolName: string; input: JSONValue }| { type: 'tool-result'; toolCallId: string; toolName: string; output: JSONValue }| { type: 'finish'; finishReason: string; usage?: HarnessTurnUsage }+ | HarnessCompactionEvent| { type: 'error'; message: string }export interface HarnessBackend {diff --git a/packages/harness/src/index.ts b/packages/harness/src/index.tsindex f951fd21e..31c1e3d5d 100644--- a/packages/harness/src/index.ts+++ b/packages/harness/src/index.ts@@ -10,6 +10,7 @@ export {MAX_PROTOCOL_LINE_BYTES,parseHarnessRequest,type HarnessAdapterID,+ type HarnessCompactionEvent,type HarnessProviderCapability,type HarnessRequest,type HarnessSandboxID,diff --git a/packages/harness/src/protocol.ts b/packages/harness/src/protocol.tsindex 0198e0205..cff427b0a 100644--- a/packages/harness/src/protocol.ts+++ b/packages/harness/src/protocol.ts@@ -51,6 +51,7 @@ export type HarnessRequest =}| { id: string; method: 'session.turn'; params: HarnessTurnInput }| { id: string; method: 'session.cancel'; params: { sessionId: string } }+ | { id: string; method: 'session.compact'; params: { sessionId: string; instructions?: string } }| { id: string; method: 'session.stop'; params: { sessionId: string } }| { id: string; method: 'session.destroy'; params: { sessionId: string } }| { id: string; method: 'service.shutdown'; params?: Record<string, never> }@@ -69,8 +70,17 @@ export type HarnessTurnEvent =| { type: 'tool-call'; toolCallId: string; toolName: string; input: JSONValue }| { type: 'tool-result'; toolCallId: string; toolName: string; output: JSONValue }| { type: 'finish'; finishReason: string; usage?: HarnessTurnUsage }+ | HarnessCompactionEvent| { type: 'error'; message: string }+/** The agent compacted its context, by request or because it filled; its summary stands for it. */+export interface HarnessCompactionEvent {+ type: 'compaction'+ trigger: 'manual' | 'auto'+ summary: string+ tokensBefore: number | null+}+export type HarnessSidecarMessage =| { type: 'response'; id: string; result?: JSONValue; error?: string }| { type: 'turn.event'; id: string; event: HarnessTurnEvent }@@ -190,6 +200,15 @@ export function parseHarnessRequest(line: string): HarnessRequest {if (method === 'session.cancel' || method === 'session.stop' || method === 'session.destroy') {return { id, method, params: parseSessionParams(parsed.params) }}+ if (method === 'session.compact') {+ const params = parseSessionParams(parsed.params)+ const instructions = isRecord(parsed.params) ? parsed.params.instructions : undefined+ if (instructions !== undefined && typeof instructions !== 'string')+ throw new Error('Expected instructions to be a string')+ if (instructions && instructions.length > MAX_PROMPT_LENGTH)+ throw new Error('Harness instructions exceed the size limit')+ return { id, method, params: instructions ? { ...params, instructions } : params }+ }if (method === 'session.turn') {if (!isRecord(parsed.params)) throw new Error('Expected request params')const sessionId = requireString(parsed.params, 'sessionId')diff --git a/packages/harness/src/service.ts b/packages/harness/src/service.tsindex 2fc6663c0..80dc66205 100644--- a/packages/harness/src/service.ts+++ b/packages/harness/src/service.ts@@ -69,6 +69,10 @@ export class HarnessSessionService {return this.cancelled.has(sessionId)}+ async compactSession(sessionId: string, instructions?: string): Promise<void> {+ await this.requireSession(sessionId).compact(instructions)+ }+cancelTurn(sessionId: string): void {this.requireSession(sessionId)this.turns.get(sessionId)?.abort()diff --git a/packages/harness/src/stdio.ts b/packages/harness/src/stdio.tsindex 8d9748dd6..948b51e25 100644--- a/packages/harness/src/stdio.ts+++ b/packages/harness/src/stdio.ts@@ -92,6 +92,11 @@ async function dispatch(line: string): Promise<boolean> {await emit({ type: 'response', id: request.id, result: { cancelled: true } })return true}+ if (request.method === 'session.compact') {+ await service.compactSession(request.params.sessionId, request.params.instructions)+ await emit({ type: 'response', id: request.id, result: { compacted: true } })+ return true+ }if (request.method === 'session.stop') {await service.stopSession(request.params.sessionId)await emit({ type: 'response', id: request.id, result: { stopped: true } })diff --git a/packages/harness/tests/protocol.test.ts b/packages/harness/tests/protocol.test.tsindex 41b128cd1..340df8a95 100644--- a/packages/harness/tests/protocol.test.ts+++ b/packages/harness/tests/protocol.test.ts@@ -69,6 +69,21 @@ describe('harness sidecar protocol', () => {})})+ test('parses a compaction request, with or without instructions', () => {+ const compact = (params: object) =>+ parseHarnessRequest(JSON.stringify({ id: 'request-1', method: 'session.compact', params }))+ expect(compact({ sessionId: 'session-1' })).toEqual({+ id: 'request-1',+ method: 'session.compact',+ params: { sessionId: 'session-1' }+ })+ expect(compact({ sessionId: 'session-1', instructions: 'keep the colors' }).params).toEqual({+ sessionId: 'session-1',+ instructions: 'keep the colors'+ })+ expect(() => compact({ sessionId: 'session-1', instructions: 3 })).toThrow('instructions')+ })+test('rejects unknown methods and oversized prompts', () => {expect(() =>parseHarnessRequest(JSON.stringify({ id: 'request-1', method: 'unknown' }))diff --git a/packages/harness/tests/service.test.ts b/packages/harness/tests/service.test.tsindex 7175bec2d..7a0f28222 100644--- a/packages/harness/tests/service.test.ts+++ b/packages/harness/tests/service.test.ts@@ -35,6 +35,7 @@ class MemoryStore implements ResumeStateStore {class FakeSession implements BackendSession {readonly isResume: booleandestroyed = false+ compacted: (string | undefined)[] = []constructor(readonly sessionId: string,@@ -48,6 +49,10 @@ class FakeSession implements BackendSession {yield { type: 'finish', finishReason: 'stop' }}+ async compact(instructions?: string): Promise<void> {+ this.compacted.push(instructions)+ }+async stop(): Promise<HarnessResumeState> {return {type: 'resume-session',@@ -121,6 +126,16 @@ describe('HarnessSessionService', () => {expect(await service.createSession('session-1', configuration)).toEqual({ isResume: true })})+ test('asks the session to compact, with the instructions given', async () => {+ const backend = new FakeBackend()+ const service = new HarnessSessionService(new Map([[backend.id, backend]]), new MemoryStore())+ await service.createSession('session', configuration)+ await service.compactSession('session', 'keep the colors')+ await service.compactSession('session')+ expect(backend.sessions[0]?.compacted).toEqual(['keep the colors', undefined])+ await expect(service.compactSession('missing')).rejects.toThrow('not active')+ })+test('says whether a turn ended because it was cancelled', async () => {const backend = new FakeBackend()const service = new HarnessSessionService(new Map([[backend.id, backend]]), new MemoryStore())diff --git a/packages/vue/src/i18n/locales/de/ai.json b/packages/vue/src/i18n/locales/de/ai.jsonindex f99751fa8..a1d6f0e69 100644--- a/packages/vue/src/i18n/locales/de/ai.json+++ b/packages/vue/src/i18n/locales/de/ai.json@@ -1,7 +1,59 @@{+ "jumpToLatest": "Zum neuesten Beitrag",+ "chatSettings": "Chat",+ "notificationsHint": "Nur während OpenPencil im Hintergrund ist oder ein anderes Dokument zeigt.",+ "notifyNeedsInput": "Ein Agent braucht dich",+ "notifyNeedsInputHint": "Eine Berechtigungsanfrage wartet seit einigen Sekunden auf eine Antwort.",+ "notifyFinished": "Eine Antwort ist fertig",+ "notifyFailed": "Eine Antwort ist fehlgeschlagen",+ "notificationsAllow": "Mitteilungen erlauben",+ "notificationsAllowHint": "Dein Browser fragt einmal, ob OpenPencil Mitteilungen zeigen darf.",+ "notificationsBlocked": "Mitteilungen sind für diese Website blockiert. Erlaube sie in den Website-Einstellungen des Browsers.",+ "notificationsUnsupported": "Dieser Browser kann keine Mitteilungen zeigen.",+ "notificationsSystemHint": "Wenn keine erscheinen, erlaube OpenPencil in den Mitteilungseinstellungen deines Systems.",+ "notifyTitle": "{agent} · {document}",+ "notifyPermission": "Bittet um Erlaubnis.",+ "notifyPermissionAction": "Bittet um Erlaubnis: {action}",+ "notifyReplyFinished": "Die KI-Antwort ist fertig.",+ "notifyReplyFailed": "Die KI-Antwort wurde mit einem Fehler beendet.","maxAgentSteps": "Maximale Schritte pro Nachricht",+ "maxAgentStepsCustom": "Eigener Wert…","maxAgentStepsHint": "Nur für die integrierte KI; ACP und Pi verwalten eigene Limits. Mit Enter oder beim Verlassen des Feldes gespeichert und ab der nächsten Nachricht angewendet. Höhere Limits können die Kosten erhöhen.","maxAgentStepsRange": "Gib eine ganze Zahl von {min} bis {max} ein.",+ "reasoningDisplay": "Anzeige der Überlegungen",+ "reasoningCollapsed": "Standardmäßig eingeklappt",+ "reasoningWhileThinking": "Beim Nachdenken ausklappen",+ "reasoningExpanded": "Standardmäßig ausgeklappt",+ "continueChat": "Fortfahren",+ "searchChats": "Unterhaltungen suchen…",+ "chatScope": "Unterhaltungsbereich",+ "thisDocument": "Dieses Dokument",+ "allDocuments": "Alle Dokumente",+ "noChatsFound": "Keine Unterhaltungen gefunden.",+ "chatActions": "Unterhaltungsaktionen",+ "chatHistory": "Chatverlauf",+ "newChat": "Neuer Chat",+ "followAgents": "Agenten bei der Arbeit folgen",+ "stopFollowingAgents": "Agenten bei der Arbeit nicht mehr folgen",+ "allChats": "Alle Chats",+ "renameChat": "Umbenennen",+ "saveChatTrace": "Trace speichern…",+ "chatTraceFailed": "Der Chat-Trace konnte nicht gespeichert werden.",+ "deleteChat": "Löschen",+ "chatTitle": "Chatname",+ "saveChatTitle": "Speichern",+ "cancelChatAction": "Abbrechen",+ "deleteChatConfirmation": "Diesen Chat endgültig löschen?",+ "deleteChatDescription": "„{title}“ und die Nachrichten darin werden entfernt. Das lässt sich nicht rückgängig machen.",+ "chatDocumentHint": "Öffne das Dokument des Chats, um fortzufahren.",+ "chatReadOnly": "Dieser Chat gehört zu einem anderen Dokument. Öffne es, um fortzufahren.",+ "chatAgentReadOnly": "Der Agentenverlauf wurde gespeichert, aber die Sitzung kann hier noch nicht fortgesetzt werden. Starte einen neuen Chat.",+ "chatStorageFailed": "Der Chatverlauf konnte nicht gespeichert werden. Lass dieses Fenster geöffnet und versuche es erneut.",+ "chatHistoryFailed": "Der Chatverlauf konnte nicht aktualisiert werden. Versuche es erneut.",+ "chatInterrupted": "Diese Antwort wurde unterbrochen.",+ "chatAgentWorkingOn": "{agent} arbeitet an „{page}“",+ "chatGoToPage": "Zur Seite",+ "connectProvider": "Verbinde einen KI-Anbieter, um den Chat zu starten.","connectionTestSuccess": "Verbindung erfolgreich. Das Modell ist erreichbar.","connectionTestMissingAPIKey": "Gib vor dem Testen einen API-Schlüssel ein.","connectionTestMissingSignIn": "Melde dich vor dem Testen an.",@@ -17,6 +69,7 @@"connectionTestBrowserNetworkFailed": "Dieser Endpunkt ist vom Browser aus nicht erreichbar. Versuche die Desktop-App oder einen Endpunkt mit aktiviertem CORS.","connectionTestNetworkFailed": "Der Endpunkt ist nicht erreichbar. Prüfe die URL und deine Netzwerkverbindung.","connectionTestUnknownFailed": "Verbindungstest fehlgeschlagen. Prüfe die Anbietereinstellungen und versuche es erneut.",+ "getProviderAPIKey": "Einen {provider}-API-Schlüssel erhalten →","oneKeyManyModels": "Ein Schlüssel für über 100 Modelle aller Anbieter.","describeChange": "Beschreibe eine Änderung…","describeCreateOrChange": "Beschreibe, was du erstellen oder ändern möchtest.",@@ -80,8 +133,10 @@"permissionRequest": "{tool} fordert eine Berechtigung an.","baseURLPlaceholder": "Base URL (z. B. http://localhost:11434/v1)","modelIDPlaceholder": "Model ID (z. B. llama-3.3-70b)",+ "provider": "KI-Anbieter","providerSettings": "Anbietereinstellungen","openProviderSettings": "Anbietereinstellungen öffnen",+ "modelsTitle": "Modelle","modelsDescription": "Wiederverwendbare Modelle und ihre Anbieter-Verbindungen konfigurieren.","addModel": "Modell hinzufügen","editModel": "Modell bearbeiten",@@ -136,6 +191,12 @@"apiType": "API-Typ","baseURL": "Basis-URL","modelID": "Modell-ID",+ "selectModel": "Modell auswählen",+ "searchModels": "Modelle suchen…",+ "recommendedModels": "Empfohlen",+ "latestModels": "Neueste",+ "allModels": "Alle Modelle",+ "latest": "Neu","customModelID": "Benutzerdefinierte Modell-ID","customModel": "Benutzerdefiniertes Modell…","customModelGroup": "Eigenes Modell",@@ -146,9 +207,12 @@"chatSignInExpired": "Deine Anmeldung ist abgelaufen. Melde dich in den Einstellungen erneut an.","chatPlanForbidden": "Dein Tarif kann das ausgewählte Modell nicht nutzen. Wähle in den Einstellungen ein anderes Modell.","chatForbidden": "Dieser API-Schlüssel kann das ausgewählte Modell nicht verwenden. Prüfe den Modellzugriff.",+ "chatInsufficientCredit": "Das Anbieterkonto hat nicht genügend Guthaben oder Kontingent. Lade es auf und versuche es erneut.",+ "chatOutputLimit": "Das Modell hat beim Schlussfolgern das Ausgabetoken-Limit erreicht. Erhöhe die maximalen Ausgabetoken oder verringere den Schlussfolgerungsaufwand.","chatModelNotFound": "Das ausgewählte Modell ist nicht verfügbar. Wähle in den Einstellungen ein anderes Modell.","chatNetworkFailed": "OpenPencil konnte den Anbieter nicht erreichen. Prüfe die Verbindung und den Endpunkt.","chatRateLimited": "Das Anfragelimit des Anbieters wurde erreicht. Warte kurz und versuche es erneut.",+ "chatRequestFailed": "Die Modellanfrage ist fehlgeschlagen. Prüfe die Anbietereinstellungen und versuche es erneut.","openProviderSettingsAction": "Einstellungen öffnen","cloudWorkspace": "Arbeitsbereich","cloudWorkspaceHint": "Der Arbeitsbereich, dessen Tarif diese Anfragen bezahlt.",@@ -164,9 +228,6 @@"cloudCreditsRenew": "Erneuert sich am {date}","manageCloudPlanAction": "Tarif verwalten","chatCloudUnavailable": "OpenPencil-Cloud-KI ist nicht verfügbar. Melde dich bei OpenPencil Cloud an und wähle in den Einstellungen einen Arbeitsbereich.",- "chatInsufficientCredit": "Das Anbieterkonto hat nicht genügend Guthaben oder Kontingent. Lade es auf und versuche es erneut.",- "chatOutputLimit": "Das Modell hat beim Schlussfolgern das Ausgabetoken-Limit erreicht. Erhöhe die maximalen Ausgabetoken oder verringere den Schlussfolgerungsaufwand.",- "chatRequestFailed": "Die Modellanfrage ist fehlgeschlagen. Prüfe die Anbietereinstellungen und versuche es erneut.","visionModelUnavailable": "Wähle in den Einstellungen ein Vision-Modell aus, bevor du Bilder anhängst.","chatPiCompanionMissing": "Pi braucht den Harness-Begleiter. Starte die geführte Einrichtung, um ihn zu installieren.","chatPiCompanionOutdated": "Der Harness-Begleiter passt nicht zu dieser OpenPencil-Version. Starte die geführte Einrichtung, um ihn zu aktualisieren.",@@ -175,65 +236,6 @@"chatPiModel": "Pi hat kein Modell. Starte pi im Terminal und gib /model ein oder wähle eines in den Einstellungen.","completions": "Completions","responses": "Responses",- "connectProvider": "Verbinde einen KI-Anbieter, um den Chat zu starten.",- "getProviderAPIKey": "Einen {provider}-API-Schlüssel erhalten →",- "provider": "KI-Anbieter",- "modelsTitle": "Modelle",- "selectModel": "Modell auswählen",- "searchModels": "Modelle suchen…",- "recommendedModels": "Empfohlen",- "latestModels": "Neueste",- "allModels": "Alle Modelle",- "latest": "Neu",- "chatHistory": "Chatverlauf",- "newChat": "Neuer Chat",- "followAgents": "Agenten bei der Arbeit folgen",- "stopFollowingAgents": "Agenten bei der Arbeit nicht mehr folgen",- "allChats": "Alle Chats",- "renameChat": "Umbenennen",- "saveChatTrace": "Trace speichern…",- "chatTraceFailed": "Der Chat-Trace konnte nicht gespeichert werden.",- "deleteChat": "Löschen",- "chatTitle": "Chatname",- "saveChatTitle": "Speichern",- "cancelChatAction": "Abbrechen",- "deleteChatConfirmation": "Diesen Chat endgültig löschen?",- "deleteChatDescription": "„{title}“ und die Nachrichten darin werden entfernt. Das lässt sich nicht rückgängig machen.",- "chatDocumentHint": "Öffne das Dokument des Chats, um fortzufahren.",- "chatReadOnly": "Dieser Chat gehört zu einem anderen Dokument. Öffne es, um fortzufahren.",- "chatAgentReadOnly": "Der Agentenverlauf wurde gespeichert, aber die Sitzung kann hier noch nicht fortgesetzt werden. Starte einen neuen Chat.",- "chatStorageFailed": "Der Chatverlauf konnte nicht gespeichert werden. Lass dieses Fenster geöffnet und versuche es erneut.",- "chatHistoryFailed": "Der Chatverlauf konnte nicht aktualisiert werden. Versuche es erneut.",- "chatInterrupted": "Diese Antwort wurde unterbrochen.",- "searchChats": "Unterhaltungen suchen…",- "chatScope": "Unterhaltungsbereich",- "thisDocument": "Dieses Dokument",- "allDocuments": "Alle Dokumente",- "noChatsFound": "Keine Unterhaltungen gefunden.",- "chatActions": "Unterhaltungsaktionen",- "continueChat": "Fortfahren",- "chatSettings": "Chat",- "notificationsHint": "Nur während OpenPencil im Hintergrund ist oder ein anderes Dokument zeigt.",- "notifyNeedsInput": "Ein Agent braucht dich",- "notifyNeedsInputHint": "Eine Berechtigungsanfrage wartet seit einigen Sekunden auf eine Antwort.",- "notifyFinished": "Eine Antwort ist fertig",- "notifyFailed": "Eine Antwort ist fehlgeschlagen",- "notificationsAllow": "Mitteilungen erlauben",- "notificationsAllowHint": "Dein Browser fragt einmal, ob OpenPencil Mitteilungen zeigen darf.",- "notificationsBlocked": "Mitteilungen sind für diese Website blockiert. Erlaube sie in den Website-Einstellungen des Browsers.",- "notificationsUnsupported": "Dieser Browser kann keine Mitteilungen zeigen.",- "notificationsSystemHint": "Wenn keine erscheinen, erlaube OpenPencil in den Mitteilungseinstellungen deines Systems.",- "notifyTitle": "{agent} · {document}",- "notifyPermission": "Bittet um Erlaubnis.",- "notifyPermissionAction": "Bittet um Erlaubnis: {action}",- "notifyReplyFinished": "Die KI-Antwort ist fertig.",- "notifyReplyFailed": "Die KI-Antwort wurde mit einem Fehler beendet.",- "reasoningDisplay": "Anzeige der Überlegungen",- "reasoningCollapsed": "Standardmäßig eingeklappt",- "reasoningWhileThinking": "Beim Nachdenken ausklappen",- "reasoningExpanded": "Standardmäßig ausgeklappt",- "jumpToLatest": "Zum neuesten Beitrag",- "maxAgentStepsCustom": "Eigener Wert…","aiSetupWelcomeTitle": "Willkommen bei OpenPencil","aiSetupWelcomeDescription": "Erstelle und bearbeite Designs auf einer offenen Arbeitsfläche. Importiere Figma-Dateien und mach sie zu deinen eigenen.","aiSetupWelcomeAITitle": "Mit KI gestalten",@@ -259,69 +261,34 @@"modelProviderSetUp": "Eingerichtet","aiSetupAccessAPI": "API-Konten","aiSetupAccessServer": "Lokales Modell oder Firmenserver",+ "aiSetupAccessMore": "Weitere Anbieter",+ "providerGroupAgents": "Deine Agenten",+ "providerGroupProviders": "Anbieter",+ "aiSetupServerOther": "Anderer Server","aiSetupAccessServerDescription": "Jeder Server, der die OpenAI-API spricht, etwa Ollama oder LM Studio.","aiSetupConnectTitle": "KI verbinden","aiSetupNothingDescription": "Geh zurück, um etwas anderes zu wählen, oder richte die KI in den erweiterten Einstellungen ein.","aiSetupAgentDescription": "OpenPencil startet {agent}, sobald du eine Nachricht sendest, mit dem Konto, bei dem {agent} angemeldet ist.","aiSetupAgentInstall": "Falls es noch nicht installiert ist, führe Folgendes aus:","aiSetupAgentInstallSupported": "Installiere den unterstützten Adapter:",- "aiSetupMeteredNote": "OpenRouter bietet Modelle mehrerer Anbieter mit einem Konto und einem Schlüssel.",- "aiSetupSkillsTitle": "Skills deiner Coding-Agenten",- "aiSetupSkillsDescription": "Der Design-Chat kann Skills nutzen, die deine Coding-Agenten installiert haben. Die meisten sind Coding-Workflows, wähle also nur die, die beim Design helfen; unter Einstellungen › Skills lässt sich das später ändern.",- "aiSetupReviewTitle": "Einrichtung prüfen",- "aiSetupAgentModel": "Vom Agenten gewähltes Modell",- "aiSetupFinish": "Einrichtung abschließen",- "aiSetupSavedTitle": "Die KI ist bereit",- "aiSetupSavedDescription": "Du kannst Modelle und Rollen jederzeit in den Einstellungen ändern.",- "aiSetupRun": "Geführte Einrichtung starten",- "aiSetupServerKeyHint": "Wenn dein Server keine Schlüssel prüft, gib einen beliebigen Wert ein.",- "aiSetupAlreadyConnected": "Alles, was du ausgewählt hast, ist bereits verbunden.",- "aiSetupOpenRouterSignIn": "Mit OpenRouter anmelden",- "aiSetupOpenRouterWaiting": "Schließe die Anmeldung bei OpenRouter in deinem Browser ab.",- "aiSetupSignInReopen": "Erneut öffnen",- "aiSetupOpenRouterOrKey": "Oder einen API-Schlüssel einfügen",- "aiSetupOpenRouterBlocked": "Dein Browser hat das Anmeldefenster blockiert. Erlaube Pop-ups für OpenPencil und versuche es erneut.",- "aiSetupSignInCancelled": "Die Anmeldung wurde abgebrochen.",- "aiSetupSignInExpired": "Die Anmeldung hat zu lange gedauert. Versuche es erneut.",- "aiSetupOpenRouterFailed": "Die Anmeldung bei OpenRouter ist fehlgeschlagen. Versuche es erneut oder füge einen API-Schlüssel ein.",- "aiSetupOpenRouterSignedInTitle": "Bei OpenRouter angemeldet",- "aiSetupSavedKeyHint": "Leer lassen, um den gespeicherten Schlüssel zu behalten.",- "aiSetupOpenRouterKeyLabel": "· Schlüssel „{label}“",- "aiSetupOpenRouterVerifying": "Dein OpenRouter-Schlüssel wird geprüft…",- "aiSetupOpenRouterNoCredits": "Dieses OpenRouter-Konto hat noch kein Guthaben. Lade bei OpenRouter Guthaben auf, um kostenpflichtige Modelle wie das empfohlene zu nutzen.",- "aiSetupSignInChange": "Anderes Konto verwenden",- "aiSetupSignOut": "Abmelden",- "aiSetupAccessSubscriptions": "Abos",- "aiSetupAccessChatGPT": "Nutze die Modelle deines ChatGPT-Abos im eigenen Agenten von OpenPencil.",- "aiSetupChatGPTSignIn": "Mit ChatGPT anmelden",- "aiSetupChatGPTWaiting": "Schließe die Anmeldung bei ChatGPT in deinem Browser ab.",- "aiSetupChatGPTSignedInTitle": "Bei ChatGPT angemeldet",- "aiSetupChatGPTFailed": "Anmeldung bei ChatGPT fehlgeschlagen. Versuche es erneut.",- "aiSetupChatGPTPortInUse": "Eine andere Anmeldung, etwa `codex login`, belegt Port 1455. Schließe sie ab oder beende sie und versuche es erneut.",- "aiSetupChatGPTCallbackSignedIn": "Bei ChatGPT angemeldet. Du kannst diesen Tab schließen und zu OpenPencil zurückkehren.",- "aiSetupChatGPTCallbackCancelled": "Die Anmeldung bei ChatGPT wurde abgebrochen. Du kannst diesen Tab schließen.",- "aiSetupChatGPTCallbackStale": "Dieser Anmeldelink gehört zu einem früheren Versuch. Starte erneut in OpenPencil.",- "aiSetupChatGPTUsage": "Antworten zählen zu den Nutzungslimits deines ChatGPT-Abos.",- "aiSetupSavedSignInHint": "Deine gespeicherte Anmeldung wird verwendet.",- "aiSetupUseRecommended": "Empfohlene Einrichtung verwenden",- "aiSetupRolesDescription": "Wähle für jede Art von Arbeit ein Modell. Wir haben aus deinen Verbindungen empfohlene ausgewählt; alles andere, was du eingerichtet hast, bleibt unverändert.",- "aiSetupGapDesign": "Nichts von deiner Auswahl kann Designs erstellen und bearbeiten.",- "aiSetupGapVision": "Nichts von deiner Auswahl kann Bilder prüfen, daher bliebe die visuelle Prüfung aus.",- "aiSetupGapContinue": "Du kannst ohne fortfahren und es später in den Einstellungen hinzufügen.",- "aiSetupGapAddOpenRouter": "OpenRouter hinzufügen (nutzungsbasiert)",- "aiSetupGapRemoveOpenRouter": "OpenRouter nicht verwenden",- "aiSetupServerVision": "Dieses Modell kann Bilder lesen",- "aiSetupGapCoveredByOpenRouter": "OpenRouter übernimmt, was deine übrige Auswahl nicht abdeckt, und rechnet pro Anfrage ab.",- "aiSetupAccessMore": "Weitere Anbieter",- "providerGroupAgents": "Deine Agenten",- "providerGroupProviders": "Anbieter",- "aiSetupServerOther": "Anderer Server","aiSetupAgentChecking": "Dieser Computer wird geprüft…","aiSetupAgentInstalled": "installiert","aiSetupAgentNotFound": "nicht gefunden","aiSetupAgentMCP": "OpenPencil-MCP-Server","aiSetupAgentMCPInstall": "Coding-Agenten greifen über den MCP-Server von OpenPencil auf die Arbeitsfläche zu. Installiere ihn mit:","aiSetupAgentPromptHint": "Nutzt du schon {agent} oder einen anderen Coding-Agenten? Kopiere den Einrichtungs-Prompt und füge ihn dort ein; er installiert, was OpenPencil braucht.",+ "aiSetupAgentNeedsAdapter": "installiert · OpenPencil-Adapter fehlt",+ "aiSetupAgentInstallAdapter": "Adapter installieren",+ "aiSetupAgentInstallMCP": "MCP-Server installieren",+ "aiSetupAgentUpdateMCP": "MCP-Server aktualisieren",+ "aiSetupAgentOutdated": "Update nötig",+ "aiSetupAgentInstalling": "Wird installiert…",+ "aiSetupAgentGetCLI": "{agent} installieren",+ "aiSetupAgentNeedsNpm": "Zum Installieren wird npm benötigt, das mit Node.js geliefert wird. Installiere Node.js und prüfe dann erneut.",+ "aiSetupAgentNeedsAdmin": "Die Installation braucht Administratorrechte, weil npm globale Pakete in einem geschützten Ordner ablegt. Führe den Befehl unten im Terminal aus oder lass deinen Agenten einen Ordner einrichten, der dir gehört.",+ "aiSetupAgentInstallFailed": "Die Installation wurde nicht abgeschlossen. Prüfe deine Verbindung oder führe den Befehl selbst aus.",+ "aiSetupAgentMCPStartFailed": "Der MCP-Server ist installiert, startet aber nicht. Starte OpenPencil neu und prüfe dann erneut.",+ "aiSetupAgentLookupFailed": "Dieser Computer konnte nicht geprüft werden. Versuche es erneut.","aiSetupAgentCopyPrompt": "Einrichtungs-Prompt kopieren","aiSetupAgentCheckAgain": "Erneut prüfen","aiSetupAgentInstallRuns": "Die Installation führt {command} aus.",@@ -356,20 +323,53 @@"piModelHint": "Ein Pi-Modell wie provider/model. Leer lassen, um das Standardmodell von Pi zu verwenden.","aiSetupPiSignIn": "Um dich bei einem Anbieter anzumelden oder ein Standardmodell zu wählen, starte pi im Terminal und gib /login oder /model ein.","aiSetupGetDesktop": "Desktop-App herunterladen",- "aiSetupAgentNeedsAdapter": "installiert · OpenPencil-Adapter fehlt",- "aiSetupAgentInstallAdapter": "Adapter installieren",- "aiSetupAgentInstallMCP": "MCP-Server installieren",- "aiSetupAgentUpdateMCP": "MCP-Server aktualisieren",- "aiSetupAgentOutdated": "Update nötig",- "aiSetupAgentInstalling": "Wird installiert…",- "aiSetupAgentGetCLI": "{agent} installieren",- "aiSetupAgentNeedsNpm": "Zum Installieren wird npm benötigt, das mit Node.js geliefert wird. Installiere Node.js und prüfe dann erneut.",- "aiSetupAgentNeedsAdmin": "Die Installation braucht Administratorrechte, weil npm globale Pakete in einem geschützten Ordner ablegt. Führe den Befehl unten im Terminal aus oder lass deinen Agenten einen Ordner einrichten, der dir gehört.",- "aiSetupAgentInstallFailed": "Die Installation wurde nicht abgeschlossen. Prüfe deine Verbindung oder führe den Befehl selbst aus.",- "aiSetupAgentMCPStartFailed": "Der MCP-Server ist installiert, startet aber nicht. Starte OpenPencil neu und prüfe dann erneut.",- "aiSetupAgentLookupFailed": "Dieser Computer konnte nicht geprüft werden. Versuche es erneut.",- "chatAgentWorkingOn": "{agent} arbeitet an „{page}“",- "chatGoToPage": "Zur Seite",+ "aiSetupMeteredNote": "OpenRouter bietet Modelle mehrerer Anbieter mit einem Konto und einem Schlüssel.",+ "aiSetupSkillsTitle": "Skills deiner Coding-Agenten",+ "aiSetupSkillsDescription": "Der Design-Chat kann Skills nutzen, die deine Coding-Agenten installiert haben. Die meisten sind Coding-Workflows, wähle also nur die, die beim Design helfen; unter Einstellungen › Skills lässt sich das später ändern.",+ "aiSetupReviewTitle": "Einrichtung prüfen",+ "aiSetupAgentModel": "Vom Agenten gewähltes Modell",+ "aiSetupFinish": "Einrichtung abschließen",+ "aiSetupSavedTitle": "Die KI ist bereit",+ "aiSetupSavedDescription": "Du kannst Modelle und Rollen jederzeit in den Einstellungen ändern.",+ "aiSetupRun": "Geführte Einrichtung starten",+ "aiSetupServerKeyHint": "Wenn dein Server keine Schlüssel prüft, gib einen beliebigen Wert ein.",+ "aiSetupGapDesign": "Nichts von deiner Auswahl kann Designs erstellen und bearbeiten.",+ "aiSetupGapVision": "Nichts von deiner Auswahl kann Bilder prüfen, daher bliebe die visuelle Prüfung aus.",+ "aiSetupGapContinue": "Du kannst ohne fortfahren und es später in den Einstellungen hinzufügen.",+ "aiSetupGapAddOpenRouter": "OpenRouter hinzufügen (nutzungsbasiert)",+ "aiSetupGapRemoveOpenRouter": "OpenRouter nicht verwenden",+ "aiSetupGapCoveredByOpenRouter": "OpenRouter übernimmt, was deine übrige Auswahl nicht abdeckt, und rechnet pro Anfrage ab.",+ "aiSetupServerVision": "Dieses Modell kann Bilder lesen",+ "aiSetupSavedKeyHint": "Leer lassen, um den gespeicherten Schlüssel zu behalten.",+ "aiSetupAlreadyConnected": "Alles, was du ausgewählt hast, ist bereits verbunden.",+ "aiSetupOpenRouterSignIn": "Mit OpenRouter anmelden",+ "aiSetupOpenRouterWaiting": "Schließe die Anmeldung bei OpenRouter in deinem Browser ab.",+ "aiSetupSignInReopen": "Erneut öffnen",+ "aiSetupOpenRouterOrKey": "Oder einen API-Schlüssel einfügen",+ "aiSetupOpenRouterBlocked": "Dein Browser hat das Anmeldefenster blockiert. Erlaube Pop-ups für OpenPencil und versuche es erneut.",+ "aiSetupSignInCancelled": "Die Anmeldung wurde abgebrochen.",+ "aiSetupSignInExpired": "Die Anmeldung hat zu lange gedauert. Versuche es erneut.",+ "aiSetupOpenRouterFailed": "Die Anmeldung bei OpenRouter ist fehlgeschlagen. Versuche es erneut oder füge einen API-Schlüssel ein.",+ "aiSetupOpenRouterSignedInTitle": "Bei OpenRouter angemeldet",+ "aiSetupOpenRouterKeyLabel": "· Schlüssel „{label}“",+ "aiSetupOpenRouterVerifying": "Dein OpenRouter-Schlüssel wird geprüft…",+ "aiSetupOpenRouterNoCredits": "Dieses OpenRouter-Konto hat noch kein Guthaben. Lade bei OpenRouter Guthaben auf, um kostenpflichtige Modelle wie das empfohlene zu nutzen.",+ "aiSetupSignInChange": "Anderes Konto verwenden",+ "aiSetupSignOut": "Abmelden",+ "aiSetupAccessSubscriptions": "Abos",+ "aiSetupAccessChatGPT": "Nutze die Modelle deines ChatGPT-Abos im eigenen Agenten von OpenPencil.",+ "aiSetupChatGPTSignIn": "Mit ChatGPT anmelden",+ "aiSetupChatGPTWaiting": "Schließe die Anmeldung bei ChatGPT in deinem Browser ab.",+ "aiSetupChatGPTSignedInTitle": "Bei ChatGPT angemeldet",+ "aiSetupChatGPTFailed": "Anmeldung bei ChatGPT fehlgeschlagen. Versuche es erneut.",+ "aiSetupChatGPTPortInUse": "Eine andere Anmeldung, etwa `codex login`, belegt Port 1455. Schließe sie ab oder beende sie und versuche es erneut.",+ "aiSetupChatGPTCallbackSignedIn": "Bei ChatGPT angemeldet. Du kannst diesen Tab schließen und zu OpenPencil zurückkehren.",+ "aiSetupChatGPTCallbackCancelled": "Die Anmeldung bei ChatGPT wurde abgebrochen. Du kannst diesen Tab schließen.",+ "aiSetupChatGPTCallbackStale": "Dieser Anmeldelink gehört zu einem früheren Versuch. Starte erneut in OpenPencil.",+ "aiSetupChatGPTUsage": "Antworten zählen zu den Nutzungslimits deines ChatGPT-Abos.",+ "aiSetupSavedSignInHint": "Deine gespeicherte Anmeldung wird verwendet.",+ "aiSetupUseRecommended": "Empfohlene Einrichtung verwenden",+ "aiSetupRolesDescription": "Wähle für jede Art von Arbeit ein Modell. Wir haben aus deinen Verbindungen empfohlene ausgewählt; alles andere, was du eingerichtet hast, bleibt unverändert.","chatReferenceLayers": "Ebenen","chatReferencePages": "Seiten","chatReferenceSkills": "Skills",@@ -417,6 +417,31 @@"skillWarningLongDescription": "Die Beschreibung ist länger als {max} Zeichen.","skillErrorNoFrontmatter": "SKILL.md beginnt nicht mit YAML-Frontmatter zwischen Zeilen mit ---.","skillErrorInvalidFrontmatter": "Das Frontmatter der SKILL.md ist ungültig: {detail}",+ "contextUsed": "Kontext: {percent} % belegt",+ "contextTitle": "Kontext",+ "contextTokens": "{used} von {total} Tokens",+ "contextCompactsAt": "Wird bei {tokens} Tokens automatisch komprimiert, damit Platz für die Antwort bleibt.",+ "contextCompactsOff": "Automatisches Komprimieren ist aus.",+ "contextNearlyFull": "Kontext {percent} % belegt",+ "compact": "Komprimieren",+ "compactCommand": "Die bisherige Unterhaltung zusammenfassen; Text danach sagt, was erhalten bleiben soll",+ "compactAutomatically": "Automatisch komprimieren",+ "compactAutomaticallyHint": "Fasst ältere Nachrichten zusammen, wenn das Kontextfenster voll wird.",+ "compacting": "Unterhaltung wird komprimiert…",+ "compactionFailed": "Die Unterhaltung konnte nicht komprimiert werden. Nichts wurde geändert.",+ "compactAndRetry": "Komprimieren und erneut versuchen",+ "chatContextLimit": "Die Unterhaltung ist länger, als das Modell lesen kann.",+ "conversationCompacted": "Unterhaltung komprimiert",+ "compactionKeepsMessages": "Das Modell erhält jetzt diese Zusammenfassung statt der Nachrichten darüber; du siehst sie weiterhin.",+ "agentCompactionKeepsMessages": "Der Agent arbeitet jetzt mit seiner eigenen Zusammenfassung der Nachrichten darüber; du siehst sie weiterhin.",+ "compactionTokens": "{before} → {after} Tokens",+ "tokenUsage": "Token-Verbrauch",+ "tokenUsageHint": "Zeigt die Tokens jeder Antwort.",+ "tokenUsageHover": "Beim Überfahren",+ "tokenUsageAlways": "Immer",+ "tokenUsageHidden": "Ausgeblendet",+ "replyTokens": "{input} ein · {output} aus",+ "replyCachedTokens": "{cached} im Cache","skillErrorNoDescription": "Das Frontmatter der SKILL.md hat keine Beschreibung.","skillErrorNoName": "Das Frontmatter der SKILL.md hat keinen Namen."}diff --git a/packages/vue/src/i18n/locales/es/ai.json b/packages/vue/src/i18n/locales/es/ai.jsonindex dbb1d07cf..b369d25fe 100644--- a/packages/vue/src/i18n/locales/es/ai.json+++ b/packages/vue/src/i18n/locales/es/ai.json@@ -1,7 +1,59 @@{+ "jumpToLatest": "Ir al último mensaje",+ "chatSettings": "Chat",+ "notificationsHint": "Solo mientras OpenPencil está en segundo plano o muestra otro documento.",+ "notifyNeedsInput": "Un agente te necesita",+ "notifyNeedsInputHint": "Una solicitud de permiso lleva unos segundos sin respuesta.",+ "notifyFinished": "Una respuesta terminó",+ "notifyFailed": "Una respuesta falló",+ "notificationsAllow": "Permitir notificaciones",+ "notificationsAllowHint": "El navegador pregunta una vez si OpenPencil puede mostrar notificaciones.",+ "notificationsBlocked": "Las notificaciones están bloqueadas para este sitio. Permítelas en la configuración del sitio del navegador.",+ "notificationsUnsupported": "Este navegador no puede mostrar notificaciones.",+ "notificationsSystemHint": "Si no aparece ninguna, permite OpenPencil en la configuración de notificaciones del sistema.",+ "notifyTitle": "{agent} · {document}",+ "notifyPermission": "Pide permiso.",+ "notifyPermissionAction": "Pide permiso: {action}",+ "notifyReplyFinished": "La respuesta de la IA terminó.",+ "notifyReplyFailed": "La respuesta de la IA se detuvo con un error.","maxAgentSteps": "Máximo de pasos por mensaje",+ "maxAgentStepsCustom": "Personalizado…","maxAgentStepsHint": "Solo para la IA integrada; ACP y Pi controlan sus propios límites. Se guarda al pulsar Enter o salir del campo y se aplica al siguiente mensaje. Un límite mayor puede aumentar el coste.","maxAgentStepsRange": "Introduce un número entero entre {min} y {max}.",+ "reasoningDisplay": "Visualización del razonamiento",+ "reasoningCollapsed": "Contraído por defecto",+ "reasoningWhileThinking": "Expandir al razonar",+ "reasoningExpanded": "Expandido por defecto",+ "continueChat": "Continuar",+ "searchChats": "Buscar conversaciones…",+ "chatScope": "Ámbito de conversaciones",+ "thisDocument": "Este documento",+ "allDocuments": "Todos los documentos",+ "noChatsFound": "No se encontraron conversaciones.",+ "chatActions": "Acciones de la conversación",+ "chatHistory": "Historial de chats",+ "newChat": "Nuevo chat",+ "followAgents": "Seguir a los agentes mientras trabajan",+ "stopFollowingAgents": "Dejar de seguir a los agentes mientras trabajan",+ "allChats": "Todos los chats",+ "renameChat": "Renombrar",+ "saveChatTrace": "Guardar traza…",+ "chatTraceFailed": "No se pudo guardar la traza del chat.",+ "deleteChat": "Eliminar",+ "chatTitle": "Título del chat",+ "saveChatTitle": "Guardar",+ "cancelChatAction": "Cancelar",+ "deleteChatConfirmation": "¿Eliminar este chat permanentemente?",+ "deleteChatDescription": "«{title}» y sus mensajes se eliminan. Esta acción no se puede deshacer.",+ "chatDocumentHint": "Abre el documento del chat para continuar.",+ "chatReadOnly": "Este chat pertenece a otro documento. Ábrelo para continuar.",+ "chatAgentReadOnly": "La conversación del agente está guardada, pero todavía no se puede reanudar su sesión aquí. Inicia un nuevo chat.",+ "chatStorageFailed": "No se pudo guardar el historial. Mantén esta ventana abierta e inténtalo de nuevo.",+ "chatHistoryFailed": "No se pudo actualizar el historial. Inténtalo de nuevo.",+ "chatInterrupted": "Esta respuesta se interrumpió.",+ "chatAgentWorkingOn": "{agent} está trabajando en «{page}»",+ "chatGoToPage": "Ir a la página",+ "connectProvider": "Conecta un proveedor de IA para empezar a chatear.","connectionTestSuccess": "Conexión correcta. Se puede acceder al modelo.","connectionTestMissingAPIKey": "Introduce una clave API antes de probar.","connectionTestMissingSignIn": "Inicia sesión antes de probar.",@@ -17,6 +69,7 @@"connectionTestBrowserNetworkFailed": "No se ha podido acceder a este endpoint desde el navegador. Prueba la aplicación de escritorio o usa un endpoint con CORS habilitado.","connectionTestNetworkFailed": "No se ha podido acceder al endpoint. Comprueba la URL y la conexión de red.","connectionTestUnknownFailed": "La prueba de conexión ha fallado. Comprueba los ajustes del proveedor e inténtalo de nuevo.",+ "getProviderAPIKey": "Obtener una clave API de {provider} →","oneKeyManyModels": "Una clave para más de 100 modelos de todos los proveedores.","describeChange": "Describe un cambio…","describeCreateOrChange": "Describe lo que quieres crear o cambiar.",@@ -80,8 +133,10 @@"permissionRequest": "{tool} solicita permiso.","baseURLPlaceholder": "Base URL (p. ej. http://localhost:11434/v1)","modelIDPlaceholder": "Model ID (p. ej. llama-3.3-70b)",+ "provider": "Proveedor de IA","providerSettings": "Opciones del proveedor","openProviderSettings": "Abrir opciones del proveedor",+ "modelsTitle": "Modelos","modelsDescription": "Configura modelos reutilizables y sus conexiones de proveedor.","addModel": "Añadir modelo","editModel": "Editar modelo",@@ -152,9 +207,12 @@"chatSignInExpired": "Tu sesión ha caducado. Vuelve a iniciar sesión en Ajustes.","chatPlanForbidden": "Tu plan no puede usar el modelo seleccionado. Elige otro modelo en Ajustes.","chatForbidden": "Esta clave API no puede usar el modelo seleccionado. Comprueba el acceso al modelo.",+ "chatInsufficientCredit": "La cuenta del proveedor no tiene suficiente saldo o cuota. Recárgala e inténtalo de nuevo.",+ "chatOutputLimit": "El modelo agotó los tokens de salida mientras razonaba. Aumenta los tokens máximos de salida o reduce el esfuerzo de razonamiento.","chatModelNotFound": "El modelo seleccionado no está disponible. Elige otro modelo en Ajustes.","chatNetworkFailed": "OpenPencil no pudo acceder al proveedor. Comprueba la conexión y el endpoint.","chatRateLimited": "Se alcanzó el límite de solicitudes del proveedor. Espera un momento e inténtalo de nuevo.",+ "chatRequestFailed": "La solicitud al modelo falló. Comprueba la configuración del proveedor e inténtalo de nuevo.","openProviderSettingsAction": "Abrir ajustes","cloudWorkspace": "Espacio de trabajo","cloudWorkspaceHint": "El espacio de trabajo cuyo plan paga estas solicitudes.",@@ -170,9 +228,6 @@"cloudCreditsRenew": "Se renueva el {date}","manageCloudPlanAction": "Gestionar plan","chatCloudUnavailable": "La IA de OpenPencil Cloud no está disponible. Inicia sesión en OpenPencil Cloud y elige un espacio de trabajo en Ajustes.",- "chatInsufficientCredit": "La cuenta del proveedor no tiene suficiente saldo o cuota. Recárgala e inténtalo de nuevo.",- "chatOutputLimit": "El modelo agotó los tokens de salida mientras razonaba. Aumenta los tokens máximos de salida o reduce el esfuerzo de razonamiento.",- "chatRequestFailed": "La solicitud al modelo falló. Comprueba la configuración del proveedor e inténtalo de nuevo.","visionModelUnavailable": "Elige un modelo de visión en Ajustes antes de adjuntar imágenes.","chatPiCompanionMissing": "Pi necesita el complemento Harness. Ejecuta la configuración guiada para instalarlo.","chatPiCompanionOutdated": "El complemento Harness no coincide con esta versión de OpenPencil. Ejecuta la configuración guiada para actualizarlo.",@@ -181,59 +236,6 @@"chatPiModel": "Pi no tiene ningún modelo. Ejecuta pi en una terminal y escribe /model, o elige uno en Ajustes.","completions": "Completions","responses": "Responses",- "connectProvider": "Conecta un proveedor de IA para empezar a chatear.",- "getProviderAPIKey": "Obtener una clave API de {provider} →",- "provider": "Proveedor de IA",- "modelsTitle": "Modelos",- "chatHistory": "Historial de chats",- "newChat": "Nuevo chat",- "followAgents": "Seguir a los agentes mientras trabajan",- "stopFollowingAgents": "Dejar de seguir a los agentes mientras trabajan",- "allChats": "Todos los chats",- "renameChat": "Renombrar",- "saveChatTrace": "Guardar traza…",- "chatTraceFailed": "No se pudo guardar la traza del chat.",- "deleteChat": "Eliminar",- "chatTitle": "Título del chat",- "saveChatTitle": "Guardar",- "cancelChatAction": "Cancelar",- "deleteChatConfirmation": "¿Eliminar este chat permanentemente?",- "deleteChatDescription": "«{title}» y sus mensajes se eliminan. Esta acción no se puede deshacer.",- "chatDocumentHint": "Abre el documento del chat para continuar.",- "chatReadOnly": "Este chat pertenece a otro documento. Ábrelo para continuar.",- "chatAgentReadOnly": "La conversación del agente está guardada, pero todavía no se puede reanudar su sesión aquí. Inicia un nuevo chat.",- "chatStorageFailed": "No se pudo guardar el historial. Mantén esta ventana abierta e inténtalo de nuevo.",- "chatHistoryFailed": "No se pudo actualizar el historial. Inténtalo de nuevo.",- "chatInterrupted": "Esta respuesta se interrumpió.",- "searchChats": "Buscar conversaciones…",- "chatScope": "Ámbito de conversaciones",- "thisDocument": "Este documento",- "allDocuments": "Todos los documentos",- "noChatsFound": "No se encontraron conversaciones.",- "chatActions": "Acciones de la conversación",- "continueChat": "Continuar",- "chatSettings": "Chat",- "notificationsHint": "Solo mientras OpenPencil está en segundo plano o muestra otro documento.",- "notifyNeedsInput": "Un agente te necesita",- "notifyNeedsInputHint": "Una solicitud de permiso lleva unos segundos sin respuesta.",- "notifyFinished": "Una respuesta terminó",- "notifyFailed": "Una respuesta falló",- "notificationsAllow": "Permitir notificaciones",- "notificationsAllowHint": "El navegador pregunta una vez si OpenPencil puede mostrar notificaciones.",- "notificationsBlocked": "Las notificaciones están bloqueadas para este sitio. Permítelas en la configuración del sitio del navegador.",- "notificationsUnsupported": "Este navegador no puede mostrar notificaciones.",- "notificationsSystemHint": "Si no aparece ninguna, permite OpenPencil en la configuración de notificaciones del sistema.",- "notifyTitle": "{agent} · {document}",- "notifyPermission": "Pide permiso.",- "notifyPermissionAction": "Pide permiso: {action}",- "notifyReplyFinished": "La respuesta de la IA terminó.",- "notifyReplyFailed": "La respuesta de la IA se detuvo con un error.",- "reasoningDisplay": "Visualización del razonamiento",- "reasoningCollapsed": "Contraído por defecto",- "reasoningWhileThinking": "Expandir al razonar",- "reasoningExpanded": "Expandido por defecto",- "jumpToLatest": "Ir al último mensaje",- "maxAgentStepsCustom": "Personalizado…","aiSetupWelcomeTitle": "Te damos la bienvenida a OpenPencil","aiSetupWelcomeDescription": "Crea y edita diseños en un lienzo abierto. Importa archivos de Figma y hazlos tuyos.","aiSetupWelcomeAITitle": "Diseña con IA",@@ -259,69 +261,34 @@"modelProviderSetUp": "Configurado","aiSetupAccessAPI": "Cuentas de API","aiSetupAccessServer": "Modelo local o servidor de la empresa",+ "aiSetupAccessMore": "Más proveedores",+ "providerGroupAgents": "Tus agentes",+ "providerGroupProviders": "Proveedores",+ "aiSetupServerOther": "Otro servidor","aiSetupAccessServerDescription": "Cualquier servidor compatible con la API de OpenAI, como Ollama o LM Studio.","aiSetupConnectTitle": "Conecta tu IA","aiSetupNothingDescription": "Vuelve atrás para elegir otro acceso o configura la IA en los ajustes avanzados.","aiSetupAgentDescription": "OpenPencil inicia {agent} cuando envías un mensaje, con la cuenta en la que {agent} tiene la sesión iniciada.","aiSetupAgentInstall": "Si aún no está instalado, ejecuta:","aiSetupAgentInstallSupported": "Instala el adaptador compatible:",- "aiSetupMeteredNote": "OpenRouter te da modelos de varios proveedores con una sola cuenta y una sola clave.",- "aiSetupSkillsTitle": "Habilidades de tus agentes de programación",- "aiSetupSkillsDescription": "El chat de diseño puede usar habilidades que instalaron tus agentes de programación. La mayoría son flujos de programación, así que elige solo las que ayudan con el diseño; puedes cambiarlas en Ajustes › Habilidades.",- "aiSetupReviewTitle": "Revisa tu configuración",- "aiSetupAgentModel": "Modelo elegido por el agente",- "aiSetupFinish": "Terminar la configuración",- "aiSetupSavedTitle": "La IA está lista",- "aiSetupSavedDescription": "Puedes cambiar los modelos y los roles en cualquier momento en Ajustes.",- "aiSetupRun": "Iniciar la configuración guiada",- "aiSetupServerKeyHint": "Si tu servidor no comprueba claves, escribe cualquier valor.",- "aiSetupAlreadyConnected": "Todo lo que seleccionaste ya está conectado.",- "aiSetupOpenRouterSignIn": "Iniciar sesión con OpenRouter",- "aiSetupOpenRouterWaiting": "Termina de iniciar sesión en OpenRouter en tu navegador.",- "aiSetupSignInReopen": "Abrir de nuevo",- "aiSetupOpenRouterOrKey": "O pega una clave de API",- "aiSetupOpenRouterBlocked": "Tu navegador bloqueó la ventana de inicio de sesión. Permite ventanas emergentes para OpenPencil y vuelve a intentarlo.",- "aiSetupSignInCancelled": "Se canceló el inicio de sesión.",- "aiSetupSignInExpired": "El inicio de sesión tardó demasiado. Vuelve a intentarlo.",- "aiSetupOpenRouterFailed": "No se pudo iniciar sesión en OpenRouter. Vuelve a intentarlo o pega una clave de API.",- "aiSetupOpenRouterSignedInTitle": "Sesión iniciada en OpenRouter",- "aiSetupSavedKeyHint": "Déjalo en blanco para conservar la clave guardada.",- "aiSetupOpenRouterKeyLabel": "· clave «{label}»",- "aiSetupOpenRouterVerifying": "Comprobando tu clave de OpenRouter…",- "aiSetupOpenRouterNoCredits": "Esta cuenta de OpenRouter aún no tiene créditos. Añade créditos en OpenRouter para usar modelos de pago como el recomendado.",- "aiSetupSignInChange": "Usar otra cuenta",- "aiSetupSignOut": "Cerrar sesión",- "aiSetupAccessSubscriptions": "Suscripciones",- "aiSetupAccessChatGPT": "Usa los modelos de tu plan de ChatGPT en el agente propio de OpenPencil.",- "aiSetupChatGPTSignIn": "Iniciar sesión con ChatGPT",- "aiSetupChatGPTWaiting": "Termina de iniciar sesión en ChatGPT en tu navegador.",- "aiSetupChatGPTSignedInTitle": "Sesión iniciada en ChatGPT",- "aiSetupChatGPTFailed": "No se pudo iniciar sesión en ChatGPT. Inténtalo de nuevo.",- "aiSetupChatGPTPortInUse": "Otro inicio de sesión, como `codex login`, está usando el puerto 1455. Termínalo o ciérralo y vuelve a intentarlo.",- "aiSetupChatGPTCallbackSignedIn": "Sesión iniciada en ChatGPT. Puedes cerrar esta pestaña y volver a OpenPencil.",- "aiSetupChatGPTCallbackCancelled": "Se canceló el inicio de sesión en ChatGPT. Puedes cerrar esta pestaña.",- "aiSetupChatGPTCallbackStale": "Este enlace de inicio de sesión pertenece a un intento anterior. Vuelve a empezar desde OpenPencil.",- "aiSetupChatGPTUsage": "Las respuestas cuentan para los límites de uso de tu plan de ChatGPT.",- "aiSetupSavedSignInHint": "Se usará tu sesión guardada.",- "aiSetupUseRecommended": "Usar la configuración recomendada",- "aiSetupRolesDescription": "Elige un modelo para cada tipo de trabajo. Elegimos los recomendados entre lo que conectaste; todo lo demás que configuraste se mantiene igual.",- "aiSetupGapDesign": "Nada de lo que elegiste puede crear y editar diseños.",- "aiSetupGapVision": "Nada de lo que elegiste puede revisar imágenes, así que la revisión visual quedaría desactivada.",- "aiSetupGapContinue": "Puedes continuar sin ello y añadirlo más tarde en Ajustes.",- "aiSetupGapAddOpenRouter": "Añadir OpenRouter (pago por uso)",- "aiSetupGapRemoveOpenRouter": "No usar OpenRouter",- "aiSetupServerVision": "Este modelo puede leer imágenes",- "aiSetupGapCoveredByOpenRouter": "OpenRouter cubrirá lo que no cubre el resto de tu elección, con cobro por solicitud.",- "aiSetupAccessMore": "Más proveedores",- "providerGroupAgents": "Tus agentes",- "providerGroupProviders": "Proveedores",- "aiSetupServerOther": "Otro servidor","aiSetupAgentChecking": "Comprobando este equipo…","aiSetupAgentInstalled": "instalado","aiSetupAgentNotFound": "no encontrado","aiSetupAgentMCP": "Servidor MCP de OpenPencil","aiSetupAgentMCPInstall": "Los agentes de programación acceden al lienzo a través del servidor MCP de OpenPencil. Instálalo con:","aiSetupAgentPromptHint": "¿Ya usas {agent} u otro agente de programación? Copia el prompt de configuración y pégalo allí; instalará lo que OpenPencil necesita.",+ "aiSetupAgentNeedsAdapter": "instalado · falta el adaptador de OpenPencil",+ "aiSetupAgentInstallAdapter": "Instalar adaptador",+ "aiSetupAgentInstallMCP": "Instalar servidor MCP",+ "aiSetupAgentUpdateMCP": "Actualizar servidor MCP",+ "aiSetupAgentOutdated": "requiere actualización",+ "aiSetupAgentInstalling": "Instalando…",+ "aiSetupAgentGetCLI": "Instalar {agent}",+ "aiSetupAgentNeedsNpm": "Para instalar hace falta npm, que viene con Node.js. Instala Node.js y vuelve a comprobar.",+ "aiSetupAgentNeedsAdmin": "La instalación necesita permisos de administrador, porque npm guarda los paquetes globales en una carpeta protegida. Ejecuta el comando de abajo en una terminal o deja que tu agente configure una carpeta tuya.",+ "aiSetupAgentInstallFailed": "La instalación no terminó. Revisa tu conexión o ejecuta el comando tú mismo.",+ "aiSetupAgentMCPStartFailed": "El servidor MCP está instalado pero no se inició. Reinicia OpenPencil y vuelve a comprobar.",+ "aiSetupAgentLookupFailed": "No se pudo comprobar este equipo. Vuelve a intentarlo.","aiSetupAgentCopyPrompt": "Copiar prompt de configuración","aiSetupAgentCheckAgain": "Comprobar de nuevo","aiSetupAgentInstallRuns": "La instalación ejecuta {command}.",@@ -356,20 +323,53 @@"piModelHint": "Un modelo de Pi como provider/model. Déjalo vacío para usar el modelo predeterminado de Pi.","aiSetupPiSignIn": "Para iniciar sesión en un proveedor o elegir un modelo predeterminado, ejecuta pi en una terminal y escribe /login o /model.","aiSetupGetDesktop": "Descargar la aplicación de escritorio",- "aiSetupAgentNeedsAdapter": "instalado · falta el adaptador de OpenPencil",- "aiSetupAgentInstallAdapter": "Instalar adaptador",- "aiSetupAgentInstallMCP": "Instalar servidor MCP",- "aiSetupAgentUpdateMCP": "Actualizar servidor MCP",- "aiSetupAgentOutdated": "requiere actualización",- "aiSetupAgentInstalling": "Instalando…",- "aiSetupAgentGetCLI": "Instalar {agent}",- "aiSetupAgentNeedsNpm": "Para instalar hace falta npm, que viene con Node.js. Instala Node.js y vuelve a comprobar.",- "aiSetupAgentNeedsAdmin": "La instalación necesita permisos de administrador, porque npm guarda los paquetes globales en una carpeta protegida. Ejecuta el comando de abajo en una terminal o deja que tu agente configure una carpeta tuya.",- "aiSetupAgentInstallFailed": "La instalación no terminó. Revisa tu conexión o ejecuta el comando tú mismo.",- "aiSetupAgentMCPStartFailed": "El servidor MCP está instalado pero no se inició. Reinicia OpenPencil y vuelve a comprobar.",- "aiSetupAgentLookupFailed": "No se pudo comprobar este equipo. Vuelve a intentarlo.",- "chatAgentWorkingOn": "{agent} está trabajando en «{page}»",- "chatGoToPage": "Ir a la página",+ "aiSetupMeteredNote": "OpenRouter te da modelos de varios proveedores con una sola cuenta y una sola clave.",+ "aiSetupSkillsTitle": "Habilidades de tus agentes de programación",+ "aiSetupSkillsDescription": "El chat de diseño puede usar habilidades que instalaron tus agentes de programación. La mayoría son flujos de programación, así que elige solo las que ayudan con el diseño; puedes cambiarlas en Ajustes › Habilidades.",+ "aiSetupReviewTitle": "Revisa tu configuración",+ "aiSetupAgentModel": "Modelo elegido por el agente",+ "aiSetupFinish": "Terminar la configuración",+ "aiSetupSavedTitle": "La IA está lista",+ "aiSetupSavedDescription": "Puedes cambiar los modelos y los roles en cualquier momento en Ajustes.",+ "aiSetupRun": "Iniciar la configuración guiada",+ "aiSetupServerKeyHint": "Si tu servidor no comprueba claves, escribe cualquier valor.",+ "aiSetupGapDesign": "Nada de lo que elegiste puede crear y editar diseños.",+ "aiSetupGapVision": "Nada de lo que elegiste puede revisar imágenes, así que la revisión visual quedaría desactivada.",+ "aiSetupGapContinue": "Puedes continuar sin ello y añadirlo más tarde en Ajustes.",+ "aiSetupGapAddOpenRouter": "Añadir OpenRouter (pago por uso)",+ "aiSetupGapRemoveOpenRouter": "No usar OpenRouter",+ "aiSetupGapCoveredByOpenRouter": "OpenRouter cubrirá lo que no cubre el resto de tu elección, con cobro por solicitud.",+ "aiSetupServerVision": "Este modelo puede leer imágenes",+ "aiSetupSavedKeyHint": "Déjalo en blanco para conservar la clave guardada.",+ "aiSetupAlreadyConnected": "Todo lo que seleccionaste ya está conectado.",+ "aiSetupOpenRouterSignIn": "Iniciar sesión con OpenRouter",+ "aiSetupOpenRouterWaiting": "Termina de iniciar sesión en OpenRouter en tu navegador.",+ "aiSetupSignInReopen": "Abrir de nuevo",+ "aiSetupOpenRouterOrKey": "O pega una clave de API",+ "aiSetupOpenRouterBlocked": "Tu navegador bloqueó la ventana de inicio de sesión. Permite ventanas emergentes para OpenPencil y vuelve a intentarlo.",+ "aiSetupSignInCancelled": "Se canceló el inicio de sesión.",+ "aiSetupSignInExpired": "El inicio de sesión tardó demasiado. Vuelve a intentarlo.",+ "aiSetupOpenRouterFailed": "No se pudo iniciar sesión en OpenRouter. Vuelve a intentarlo o pega una clave de API.",+ "aiSetupOpenRouterSignedInTitle": "Sesión iniciada en OpenRouter",+ "aiSetupOpenRouterKeyLabel": "· clave «{label}»",+ "aiSetupOpenRouterVerifying": "Comprobando tu clave de OpenRouter…",+ "aiSetupOpenRouterNoCredits": "Esta cuenta de OpenRouter aún no tiene créditos. Añade créditos en OpenRouter para usar modelos de pago como el recomendado.",+ "aiSetupSignInChange": "Usar otra cuenta",+ "aiSetupSignOut": "Cerrar sesión",+ "aiSetupAccessSubscriptions": "Suscripciones",+ "aiSetupAccessChatGPT": "Usa los modelos de tu plan de ChatGPT en el agente propio de OpenPencil.",+ "aiSetupChatGPTSignIn": "Iniciar sesión con ChatGPT",+ "aiSetupChatGPTWaiting": "Termina de iniciar sesión en ChatGPT en tu navegador.",+ "aiSetupChatGPTSignedInTitle": "Sesión iniciada en ChatGPT",+ "aiSetupChatGPTFailed": "No se pudo iniciar sesión en ChatGPT. Inténtalo de nuevo.",+ "aiSetupChatGPTPortInUse": "Otro inicio de sesión, como `codex login`, está usando el puerto 1455. Termínalo o ciérralo y vuelve a intentarlo.",+ "aiSetupChatGPTCallbackSignedIn": "Sesión iniciada en ChatGPT. Puedes cerrar esta pestaña y volver a OpenPencil.",+ "aiSetupChatGPTCallbackCancelled": "Se canceló el inicio de sesión en ChatGPT. Puedes cerrar esta pestaña.",+ "aiSetupChatGPTCallbackStale": "Este enlace de inicio de sesión pertenece a un intento anterior. Vuelve a empezar desde OpenPencil.",+ "aiSetupChatGPTUsage": "Las respuestas cuentan para los límites de uso de tu plan de ChatGPT.",+ "aiSetupSavedSignInHint": "Se usará tu sesión guardada.",+ "aiSetupUseRecommended": "Usar la configuración recomendada",+ "aiSetupRolesDescription": "Elige un modelo para cada tipo de trabajo. Elegimos los recomendados entre lo que conectaste; todo lo demás que configuraste se mantiene igual.","chatReferenceLayers": "Capas","chatReferencePages": "Páginas","chatReferenceSkills": "Habilidades",@@ -417,6 +417,31 @@"skillWarningLongDescription": "La descripción tiene más de {max} caracteres.","skillErrorNoFrontmatter": "SKILL.md no empieza con un frontmatter YAML entre líneas ---.","skillErrorInvalidFrontmatter": "El frontmatter de SKILL.md no es válido: {detail}",+ "contextUsed": "Contexto: {percent} % usado",+ "contextTitle": "Contexto",+ "contextTokens": "{used} de {total} tokens",+ "contextCompactsAt": "Se compacta automáticamente a los {tokens} tokens, dejando espacio para la respuesta.",+ "contextCompactsOff": "La compactación automática está desactivada.",+ "contextNearlyFull": "Contexto {percent} % usado",+ "compact": "Compactar",+ "compactCommand": "Resumir la conversación hasta ahora; el texto que sigue indica qué conservar",+ "compactAutomatically": "Compactar automáticamente",+ "compactAutomaticallyHint": "Resume los mensajes anteriores cuando se llena la ventana de contexto.",+ "compacting": "Compactando la conversación…",+ "compactionFailed": "No se pudo compactar la conversación. No se cambió nada.",+ "compactAndRetry": "Compactar y reintentar",+ "chatContextLimit": "La conversación es más larga de lo que el modelo puede leer.",+ "conversationCompacted": "Conversación compactada",+ "compactionKeepsMessages": "Ahora el modelo recibe este resumen en lugar de los mensajes de arriba; tú los sigues viendo.",+ "agentCompactionKeepsMessages": "El agente ahora trabaja con su propio resumen de los mensajes de arriba; tú los sigues viendo.",+ "compactionTokens": "De {before} a {after} tokens",+ "tokenUsage": "Uso de tokens",+ "tokenUsageHint": "Muestra los tokens de cada respuesta.",+ "tokenUsageHover": "Al pasar el cursor",+ "tokenUsageAlways": "Siempre",+ "tokenUsageHidden": "Oculto",+ "replyTokens": "{input} de entrada · {output} de salida",+ "replyCachedTokens": "{cached} en caché","skillErrorNoDescription": "El frontmatter de SKILL.md no tiene descripción.","skillErrorNoName": "El frontmatter de SKILL.md no tiene nombre."}diff --git a/packages/vue/src/i18n/locales/fr/ai.json b/packages/vue/src/i18n/locales/fr/ai.jsonindex 58981d4fa..5477c83d4 100644--- a/packages/vue/src/i18n/locales/fr/ai.json+++ b/packages/vue/src/i18n/locales/fr/ai.json@@ -1,7 +1,59 @@{+ "jumpToLatest": "Aller au dernier message",+ "chatSettings": "Discussion",+ "notificationsHint": "Uniquement quand OpenPencil est en arrière-plan ou affiche un autre document.",+ "notifyNeedsInput": "Un agent a besoin de vous",+ "notifyNeedsInputHint": "Une demande d’autorisation attend une réponse depuis quelques secondes.",+ "notifyFinished": "Une réponse est terminée",+ "notifyFailed": "Une réponse a échoué",+ "notificationsAllow": "Autoriser les notifications",+ "notificationsAllowHint": "Le navigateur demande une fois si OpenPencil peut afficher des notifications.",+ "notificationsBlocked": "Les notifications sont bloquées pour ce site. Autorisez-les dans les paramètres du site du navigateur.",+ "notificationsUnsupported": "Ce navigateur ne peut pas afficher de notifications.",+ "notificationsSystemHint": "Si rien n’apparaît, autorisez OpenPencil dans les réglages de notifications du système.",+ "notifyTitle": "{agent} · {document}",+ "notifyPermission": "Demande une autorisation.",+ "notifyPermissionAction": "Demande une autorisation : {action}",+ "notifyReplyFinished": "La réponse de l’IA est terminée.",+ "notifyReplyFailed": "La réponse de l’IA s’est arrêtée sur une erreur.","maxAgentSteps": "Nombre maximal d’étapes par message",+ "maxAgentStepsCustom": "Personnalisé…","maxAgentStepsHint": "Pour l’IA intégrée uniquement ; ACP et Pi gèrent leurs propres limites. Enregistré avec Entrée ou en quittant le champ, puis appliqué au prochain message. Une limite élevée peut augmenter le coût.","maxAgentStepsRange": "Saisissez un nombre entier entre {min} et {max}.",+ "reasoningDisplay": "Affichage du raisonnement",+ "reasoningCollapsed": "Replié par défaut",+ "reasoningWhileThinking": "Déplier pendant le raisonnement",+ "reasoningExpanded": "Déplié par défaut",+ "continueChat": "Continuer",+ "searchChats": "Rechercher des discussions…",+ "chatScope": "Portée des discussions",+ "thisDocument": "Ce document",+ "allDocuments": "Tous les documents",+ "noChatsFound": "Aucune discussion trouvée.",+ "chatActions": "Actions de la discussion",+ "chatHistory": "Historique des discussions",+ "newChat": "Nouvelle discussion",+ "followAgents": "Suivre les agents pendant qu’ils travaillent",+ "stopFollowingAgents": "Ne plus suivre les agents pendant qu’ils travaillent",+ "allChats": "Toutes les discussions",+ "renameChat": "Renommer",+ "saveChatTrace": "Enregistrer la trace…",+ "chatTraceFailed": "Impossible d’enregistrer la trace de la conversation.",+ "deleteChat": "Supprimer",+ "chatTitle": "Titre de la discussion",+ "saveChatTitle": "Enregistrer",+ "cancelChatAction": "Annuler",+ "deleteChatConfirmation": "Supprimer définitivement cette discussion ?",+ "deleteChatDescription": "« {title} » et ses messages sont supprimés. Cette action est irréversible.",+ "chatDocumentHint": "Ouvrez le document de la discussion pour continuer.",+ "chatReadOnly": "Cette discussion appartient à un autre document. Ouvrez-le pour continuer.",+ "chatAgentReadOnly": "La conversation avec l’agent est enregistrée, mais sa session ne peut pas encore reprendre ici. Commencez une nouvelle discussion.",+ "chatStorageFailed": "Impossible d’enregistrer l’historique. Gardez cette fenêtre ouverte et réessayez.",+ "chatHistoryFailed": "Impossible de mettre à jour l’historique. Réessayez.",+ "chatInterrupted": "Cette réponse a été interrompue.",+ "chatAgentWorkingOn": "{agent} travaille sur « {page} »",+ "chatGoToPage": "Aller à la page",+ "connectProvider": "Connectez un fournisseur d’IA pour commencer à discuter.","connectionTestSuccess": "Connexion réussie. Le modèle est accessible.","connectionTestMissingAPIKey": "Saisissez une clé API avant le test.","connectionTestMissingSignIn": "Connectez-vous avant le test.",@@ -17,6 +69,7 @@"connectionTestBrowserNetworkFailed": "Impossible d’atteindre ce point de terminaison depuis le navigateur. Essayez l’application de bureau ou un point de terminaison avec CORS activé.","connectionTestNetworkFailed": "Impossible d’atteindre le point de terminaison. Vérifiez l’URL et votre connexion réseau.","connectionTestUnknownFailed": "Échec du test de connexion. Vérifiez les paramètres du fournisseur, puis réessayez.",+ "getProviderAPIKey": "Obtenir une clé API {provider} →","oneKeyManyModels": "Une clé pour plus de 100 modèles de tous les fournisseurs.","describeChange": "Décrivez un changement…","describeCreateOrChange": "Décrivez ce que vous voulez créer ou modifier.",@@ -80,8 +133,10 @@"permissionRequest": "{tool} demande une autorisation.","baseURLPlaceholder": "Base URL (ex. http://localhost:11434/v1)","modelIDPlaceholder": "Model ID (ex. llama-3.3-70b)",+ "provider": "Fournisseur d'IA","providerSettings": "Paramètres du fournisseur","openProviderSettings": "Ouvrir les paramètres du fournisseur",+ "modelsTitle": "Modèles","modelsDescription": "Configurez des modèles réutilisables et leurs connexions fournisseur.","addModel": "Ajouter un modèle","editModel": "Modifier le modèle",@@ -136,6 +191,12 @@"apiType": "Type d'API","baseURL": "URL de base","modelID": "ID du modèle",+ "selectModel": "Sélectionner un modèle",+ "searchModels": "Rechercher des modèles…",+ "recommendedModels": "Recommandés",+ "latestModels": "Plus récents",+ "allModels": "Tous les modèles",+ "latest": "Nouveau","customModelID": "ID du modèle personnalisé","customModel": "Modèle personnalisé…","customModelGroup": "Modèle personnalisé",@@ -146,9 +207,12 @@"chatSignInExpired": "Votre connexion a expiré. Reconnectez-vous dans les paramètres.","chatPlanForbidden": "Votre forfait ne permet pas d’utiliser le modèle sélectionné. Choisissez-en un autre dans les paramètres.","chatForbidden": "Cette clé API ne peut pas utiliser le modèle sélectionné. Vérifiez son accès au modèle.",+ "chatInsufficientCredit": "Le compte du fournisseur n’a pas assez de crédit ou de quota. Rechargez-le et réessayez.",+ "chatOutputLimit": "Le modèle a épuisé ses jetons de sortie pendant le raisonnement. Augmentez le nombre maximal de jetons de sortie ou réduisez l’effort de raisonnement.","chatModelNotFound": "Le modèle sélectionné est indisponible. Choisissez-en un autre dans les paramètres.","chatNetworkFailed": "OpenPencil n’a pas pu joindre le fournisseur. Vérifiez la connexion et le point de terminaison.","chatRateLimited": "La limite de requêtes du fournisseur a été atteinte. Patientez puis réessayez.",+ "chatRequestFailed": "La requête au modèle a échoué. Vérifiez les paramètres du fournisseur et réessayez.","openProviderSettingsAction": "Ouvrir les paramètres","cloudWorkspace": "Espace de travail","cloudWorkspaceHint": "L’espace de travail dont l’abonnement paie ces requêtes.",@@ -164,9 +228,6 @@"cloudCreditsRenew": "Renouvelé le {date}","manageCloudPlanAction": "Gérer l’abonnement","chatCloudUnavailable": "L’IA d’OpenPencil Cloud n’est pas disponible. Connectez-vous à OpenPencil Cloud et choisissez un espace de travail dans les paramètres.",- "chatInsufficientCredit": "Le compte du fournisseur n’a pas assez de crédit ou de quota. Rechargez-le et réessayez.",- "chatOutputLimit": "Le modèle a épuisé ses jetons de sortie pendant le raisonnement. Augmentez le nombre maximal de jetons de sortie ou réduisez l’effort de raisonnement.",- "chatRequestFailed": "La requête au modèle a échoué. Vérifiez les paramètres du fournisseur et réessayez.","visionModelUnavailable": "Choisissez un modèle Vision dans les paramètres avant de joindre des images.","chatPiCompanionMissing": "Pi a besoin du compagnon Harness. Lancez la configuration guidée pour l’installer.","chatPiCompanionOutdated": "Le compagnon Harness ne correspond pas à cette version d’OpenPencil. Lancez la configuration guidée pour le mettre à jour.",@@ -175,65 +236,6 @@"chatPiModel": "Pi n’a aucun modèle. Lancez pi dans un terminal et tapez /model, ou choisissez-en un dans les réglages.","completions": "Completions","responses": "Responses",- "connectProvider": "Connectez un fournisseur d’IA pour commencer à discuter.",- "getProviderAPIKey": "Obtenir une clé API {provider} →",- "provider": "Fournisseur d'IA",- "modelsTitle": "Modèles",- "selectModel": "Sélectionner un modèle",- "searchModels": "Rechercher des modèles…",- "recommendedModels": "Recommandés",- "latestModels": "Plus récents",- "allModels": "Tous les modèles",- "latest": "Nouveau",- "chatHistory": "Historique des discussions",- "newChat": "Nouvelle discussion",- "followAgents": "Suivre les agents pendant qu’ils travaillent",- "stopFollowingAgents": "Ne plus suivre les agents pendant qu’ils travaillent",- "allChats": "Toutes les discussions",- "renameChat": "Renommer",- "saveChatTrace": "Enregistrer la trace…",- "chatTraceFailed": "Impossible d’enregistrer la trace de la conversation.",- "deleteChat": "Supprimer",- "chatTitle": "Titre de la discussion",- "saveChatTitle": "Enregistrer",- "cancelChatAction": "Annuler",- "deleteChatConfirmation": "Supprimer définitivement cette discussion ?",- "deleteChatDescription": "« {title} » et ses messages sont supprimés. Cette action est irréversible.",- "chatDocumentHint": "Ouvrez le document de la discussion pour continuer.",- "chatReadOnly": "Cette discussion appartient à un autre document. Ouvrez-le pour continuer.",- "chatAgentReadOnly": "La conversation avec l’agent est enregistrée, mais sa session ne peut pas encore reprendre ici. Commencez une nouvelle discussion.",- "chatStorageFailed": "Impossible d’enregistrer l’historique. Gardez cette fenêtre ouverte et réessayez.",- "chatHistoryFailed": "Impossible de mettre à jour l’historique. Réessayez.",- "chatInterrupted": "Cette réponse a été interrompue.",- "searchChats": "Rechercher des discussions…",- "chatScope": "Portée des discussions",- "thisDocument": "Ce document",- "allDocuments": "Tous les documents",- "noChatsFound": "Aucune discussion trouvée.",- "chatActions": "Actions de la discussion",- "continueChat": "Continuer",- "chatSettings": "Discussion",- "notificationsHint": "Uniquement quand OpenPencil est en arrière-plan ou affiche un autre document.",- "notifyNeedsInput": "Un agent a besoin de vous",- "notifyNeedsInputHint": "Une demande d’autorisation attend une réponse depuis quelques secondes.",- "notifyFinished": "Une réponse est terminée",- "notifyFailed": "Une réponse a échoué",- "notificationsAllow": "Autoriser les notifications",- "notificationsAllowHint": "Le navigateur demande une fois si OpenPencil peut afficher des notifications.",- "notificationsBlocked": "Les notifications sont bloquées pour ce site. Autorisez-les dans les paramètres du site du navigateur.",- "notificationsUnsupported": "Ce navigateur ne peut pas afficher de notifications.",- "notificationsSystemHint": "Si rien n’apparaît, autorisez OpenPencil dans les réglages de notifications du système.",- "notifyTitle": "{agent} · {document}",- "notifyPermission": "Demande une autorisation.",- "notifyPermissionAction": "Demande une autorisation : {action}",- "notifyReplyFinished": "La réponse de l’IA est terminée.",- "notifyReplyFailed": "La réponse de l’IA s’est arrêtée sur une erreur.",- "reasoningDisplay": "Affichage du raisonnement",- "reasoningCollapsed": "Replié par défaut",- "reasoningWhileThinking": "Déplier pendant le raisonnement",- "reasoningExpanded": "Déplié par défaut",- "jumpToLatest": "Aller au dernier message",- "maxAgentStepsCustom": "Personnalisé…","aiSetupWelcomeTitle": "Bienvenue dans OpenPencil","aiSetupWelcomeDescription": "Créez et modifiez des designs sur un canevas ouvert. Importez des fichiers Figma et appropriez-vous-les.","aiSetupWelcomeAITitle": "Concevez avec l’IA",@@ -259,69 +261,34 @@"modelProviderSetUp": "Configuré","aiSetupAccessAPI": "Comptes API","aiSetupAccessServer": "Modèle local ou serveur d’entreprise",+ "aiSetupAccessMore": "Autres fournisseurs",+ "providerGroupAgents": "Vos agents",+ "providerGroupProviders": "Fournisseurs",+ "aiSetupServerOther": "Autre serveur","aiSetupAccessServerDescription": "Tout serveur compatible avec l’API OpenAI, comme Ollama ou LM Studio.","aiSetupConnectTitle": "Connectez votre IA","aiSetupNothingDescription": "Revenez en arrière pour choisir un autre accès, ou configurez l’IA dans les réglages avancés.","aiSetupAgentDescription": "OpenPencil lance {agent} quand vous envoyez un message, avec le compte auquel {agent} est connecté.","aiSetupAgentInstall": "S’il n’est pas encore installé, exécutez :","aiSetupAgentInstallSupported": "Installez l’adaptateur pris en charge :",- "aiSetupMeteredNote": "OpenRouter donne accès aux modèles de plusieurs fournisseurs avec un seul compte et une seule clé.",- "aiSetupSkillsTitle": "Compétences de vos agents de code",- "aiSetupSkillsDescription": "Le chat de design peut utiliser les compétences installées par vos agents de code. La plupart sont des workflows de développement : choisissez seulement celles qui aident au design ; Réglages › Compétences permet de les changer ensuite.",- "aiSetupReviewTitle": "Vérifiez votre configuration",- "aiSetupAgentModel": "Modèle choisi par l’agent",- "aiSetupFinish": "Terminer la configuration",- "aiSetupSavedTitle": "L’IA est prête",- "aiSetupSavedDescription": "Vous pouvez changer les modèles et les rôles à tout moment dans les réglages.",- "aiSetupRun": "Lancer la configuration guidée",- "aiSetupServerKeyHint": "Si votre serveur ne vérifie pas les clés, saisissez n’importe quelle valeur.",- "aiSetupAlreadyConnected": "Tout ce que vous avez sélectionné est déjà connecté.",- "aiSetupOpenRouterSignIn": "Se connecter avec OpenRouter",- "aiSetupOpenRouterWaiting": "Terminez la connexion à OpenRouter dans votre navigateur.",- "aiSetupSignInReopen": "Rouvrir",- "aiSetupOpenRouterOrKey": "Ou collez une clé API",- "aiSetupOpenRouterBlocked": "Votre navigateur a bloqué la fenêtre de connexion. Autorisez les fenêtres contextuelles pour OpenPencil, puis réessayez.",- "aiSetupSignInCancelled": "La connexion a été annulée.",- "aiSetupSignInExpired": "La connexion a pris trop de temps. Réessayez.",- "aiSetupOpenRouterFailed": "Impossible de se connecter à OpenRouter. Réessayez ou collez une clé API.",- "aiSetupOpenRouterSignedInTitle": "Connecté à OpenRouter",- "aiSetupSavedKeyHint": "Laissez vide pour conserver la clé enregistrée.",- "aiSetupOpenRouterKeyLabel": "· clé « {label} »",- "aiSetupOpenRouterVerifying": "Vérification de votre clé OpenRouter…",- "aiSetupOpenRouterNoCredits": "Ce compte OpenRouter n’a pas encore de crédits. Ajoutez des crédits sur OpenRouter pour utiliser des modèles payants comme celui recommandé.",- "aiSetupSignInChange": "Utiliser un autre compte",- "aiSetupSignOut": "Se déconnecter",- "aiSetupAccessSubscriptions": "Abonnements",- "aiSetupAccessChatGPT": "Utilisez les modèles de votre forfait ChatGPT dans l’agent d’OpenPencil.",- "aiSetupChatGPTSignIn": "Se connecter avec ChatGPT",- "aiSetupChatGPTWaiting": "Terminez la connexion à ChatGPT dans votre navigateur.",- "aiSetupChatGPTSignedInTitle": "Connecté à ChatGPT",- "aiSetupChatGPTFailed": "Impossible de se connecter à ChatGPT. Réessayez.",- "aiSetupChatGPTPortInUse": "Une autre connexion, comme `codex login`, utilise le port 1455. Terminez-la ou fermez-la, puis réessayez.",- "aiSetupChatGPTCallbackSignedIn": "Connecté à ChatGPT. Vous pouvez fermer cet onglet et revenir à OpenPencil.",- "aiSetupChatGPTCallbackCancelled": "La connexion à ChatGPT a été annulée. Vous pouvez fermer cet onglet.",- "aiSetupChatGPTCallbackStale": "Ce lien de connexion appartient à une tentative précédente. Recommencez depuis OpenPencil.",- "aiSetupChatGPTUsage": "Les réponses sont décomptées des limites d’utilisation de votre forfait ChatGPT.",- "aiSetupSavedSignInHint": "Votre connexion enregistrée sera utilisée.",- "aiSetupUseRecommended": "Utiliser la configuration recommandée",- "aiSetupRolesDescription": "Choisissez un modèle pour chaque type de travail. Nous avons choisi ceux recommandés parmi ce que vous avez connecté ; tout le reste de votre configuration reste inchangé.",- "aiSetupGapDesign": "Rien de ce que vous avez choisi ne peut créer et modifier des designs.",- "aiSetupGapVision": "Rien de ce que vous avez choisi ne peut analyser d’images : la relecture visuelle resterait désactivée.",- "aiSetupGapContinue": "Vous pouvez continuer sans et l’ajouter plus tard dans les réglages.",- "aiSetupGapAddOpenRouter": "Ajouter OpenRouter (à l’usage)",- "aiSetupGapRemoveOpenRouter": "Ne pas utiliser OpenRouter",- "aiSetupServerVision": "Ce modèle peut lire des images",- "aiSetupGapCoveredByOpenRouter": "OpenRouter couvrira ce que vos autres choix ne couvrent pas, facturé à la requête.",- "aiSetupAccessMore": "Autres fournisseurs",- "providerGroupAgents": "Vos agents",- "providerGroupProviders": "Fournisseurs",- "aiSetupServerOther": "Autre serveur","aiSetupAgentChecking": "Vérification de cet ordinateur…","aiSetupAgentInstalled": "installé","aiSetupAgentNotFound": "introuvable","aiSetupAgentMCP": "Serveur MCP d’OpenPencil","aiSetupAgentMCPInstall": "Les agents de code accèdent au canevas via le serveur MCP d’OpenPencil. Installez-le avec :","aiSetupAgentPromptHint": "Vous utilisez déjà {agent} ou un autre agent de code ? Copiez le prompt de configuration et collez-le dedans ; il installe ce dont OpenPencil a besoin.",+ "aiSetupAgentNeedsAdapter": "installé · adaptateur OpenPencil manquant",+ "aiSetupAgentInstallAdapter": "Installer l’adaptateur",+ "aiSetupAgentInstallMCP": "Installer le serveur MCP",+ "aiSetupAgentUpdateMCP": "Mettre à jour le serveur MCP",+ "aiSetupAgentOutdated": "mise à jour requise",+ "aiSetupAgentInstalling": "Installation…",+ "aiSetupAgentGetCLI": "Installer {agent}",+ "aiSetupAgentNeedsNpm": "L’installation nécessite npm, fourni avec Node.js. Installez Node.js, puis vérifiez à nouveau.",+ "aiSetupAgentNeedsAdmin": "L’installation nécessite des droits administrateur, car npm place les paquets globaux dans un dossier protégé. Exécutez la commande ci-dessous dans un terminal, ou laissez votre agent configurer un dossier qui vous appartient.",+ "aiSetupAgentInstallFailed": "L’installation n’a pas abouti. Vérifiez votre connexion ou exécutez la commande vous-même.",+ "aiSetupAgentMCPStartFailed": "Le serveur MCP est installé mais n’a pas démarré. Redémarrez OpenPencil, puis vérifiez à nouveau.",+ "aiSetupAgentLookupFailed": "Impossible de vérifier cet ordinateur. Réessayez.","aiSetupAgentCopyPrompt": "Copier le prompt de configuration","aiSetupAgentCheckAgain": "Vérifier à nouveau","aiSetupAgentInstallRuns": "L’installation exécute {command}.",@@ -356,20 +323,53 @@"piModelHint": "Un modèle Pi comme provider/model. Laissez vide pour utiliser le modèle par défaut de Pi.","aiSetupPiSignIn": "Pour vous connecter à un fournisseur ou choisir un modèle par défaut, lancez pi dans un terminal et tapez /login ou /model.","aiSetupGetDesktop": "Télécharger l’application de bureau",- "aiSetupAgentNeedsAdapter": "installé · adaptateur OpenPencil manquant",- "aiSetupAgentInstallAdapter": "Installer l’adaptateur",- "aiSetupAgentInstallMCP": "Installer le serveur MCP",- "aiSetupAgentUpdateMCP": "Mettre à jour le serveur MCP",- "aiSetupAgentOutdated": "mise à jour requise",- "aiSetupAgentInstalling": "Installation…",- "aiSetupAgentGetCLI": "Installer {agent}",- "aiSetupAgentNeedsNpm": "L’installation nécessite npm, fourni avec Node.js. Installez Node.js, puis vérifiez à nouveau.",- "aiSetupAgentNeedsAdmin": "L’installation nécessite des droits administrateur, car npm place les paquets globaux dans un dossier protégé. Exécutez la commande ci-dessous dans un terminal, ou laissez votre agent configurer un dossier qui vous appartient.",- "aiSetupAgentInstallFailed": "L’installation n’a pas abouti. Vérifiez votre connexion ou exécutez la commande vous-même.",- "aiSetupAgentMCPStartFailed": "Le serveur MCP est installé mais n’a pas démarré. Redémarrez OpenPencil, puis vérifiez à nouveau.",- "aiSetupAgentLookupFailed": "Impossible de vérifier cet ordinateur. Réessayez.",- "chatAgentWorkingOn": "{agent} travaille sur « {page} »",- "chatGoToPage": "Aller à la page",+ "aiSetupMeteredNote": "OpenRouter donne accès aux modèles de plusieurs fournisseurs avec un seul compte et une seule clé.",+ "aiSetupSkillsTitle": "Compétences de vos agents de code",+ "aiSetupSkillsDescription": "Le chat de design peut utiliser les compétences installées par vos agents de code. La plupart sont des workflows de développement : choisissez seulement celles qui aident au design ; Réglages › Compétences permet de les changer ensuite.",+ "aiSetupReviewTitle": "Vérifiez votre configuration",+ "aiSetupAgentModel": "Modèle choisi par l’agent",+ "aiSetupFinish": "Terminer la configuration",+ "aiSetupSavedTitle": "L’IA est prête",+ "aiSetupSavedDescription": "Vous pouvez changer les modèles et les rôles à tout moment dans les réglages.",+ "aiSetupRun": "Lancer la configuration guidée",+ "aiSetupServerKeyHint": "Si votre serveur ne vérifie pas les clés, saisissez n’importe quelle valeur.",+ "aiSetupGapDesign": "Rien de ce que vous avez choisi ne peut créer et modifier des designs.",+ "aiSetupGapVision": "Rien de ce que vous avez choisi ne peut analyser d’images : la relecture visuelle resterait désactivée.",+ "aiSetupGapContinue": "Vous pouvez continuer sans et l’ajouter plus tard dans les réglages.",+ "aiSetupGapAddOpenRouter": "Ajouter OpenRouter (à l’usage)",+ "aiSetupGapRemoveOpenRouter": "Ne pas utiliser OpenRouter",+ "aiSetupGapCoveredByOpenRouter": "OpenRouter couvrira ce que vos autres choix ne couvrent pas, facturé à la requête.",+ "aiSetupServerVision": "Ce modèle peut lire des images",+ "aiSetupSavedKeyHint": "Laissez vide pour conserver la clé enregistrée.",+ "aiSetupAlreadyConnected": "Tout ce que vous avez sélectionné est déjà connecté.",+ "aiSetupOpenRouterSignIn": "Se connecter avec OpenRouter",+ "aiSetupOpenRouterWaiting": "Terminez la connexion à OpenRouter dans votre navigateur.",+ "aiSetupSignInReopen": "Rouvrir",+ "aiSetupOpenRouterOrKey": "Ou collez une clé API",+ "aiSetupOpenRouterBlocked": "Votre navigateur a bloqué la fenêtre de connexion. Autorisez les fenêtres contextuelles pour OpenPencil, puis réessayez.",+ "aiSetupSignInCancelled": "La connexion a été annulée.",+ "aiSetupSignInExpired": "La connexion a pris trop de temps. Réessayez.",+ "aiSetupOpenRouterFailed": "Impossible de se connecter à OpenRouter. Réessayez ou collez une clé API.",+ "aiSetupOpenRouterSignedInTitle": "Connecté à OpenRouter",+ "aiSetupOpenRouterKeyLabel": "· clé « {label} »",+ "aiSetupOpenRouterVerifying": "Vérification de votre clé OpenRouter…",+ "aiSetupOpenRouterNoCredits": "Ce compte OpenRouter n’a pas encore de crédits. Ajoutez des crédits sur OpenRouter pour utiliser des modèles payants comme celui recommandé.",+ "aiSetupSignInChange": "Utiliser un autre compte",+ "aiSetupSignOut": "Se déconnecter",+ "aiSetupAccessSubscriptions": "Abonnements",+ "aiSetupAccessChatGPT": "Utilisez les modèles de votre forfait ChatGPT dans l’agent d’OpenPencil.",+ "aiSetupChatGPTSignIn": "Se connecter avec ChatGPT",+ "aiSetupChatGPTWaiting": "Terminez la connexion à ChatGPT dans votre navigateur.",+ "aiSetupChatGPTSignedInTitle": "Connecté à ChatGPT",+ "aiSetupChatGPTFailed": "Impossible de se connecter à ChatGPT. Réessayez.",+ "aiSetupChatGPTPortInUse": "Une autre connexion, comme `codex login`, utilise le port 1455. Terminez-la ou fermez-la, puis réessayez.",+ "aiSetupChatGPTCallbackSignedIn": "Connecté à ChatGPT. Vous pouvez fermer cet onglet et revenir à OpenPencil.",+ "aiSetupChatGPTCallbackCancelled": "La connexion à ChatGPT a été annulée. Vous pouvez fermer cet onglet.",+ "aiSetupChatGPTCallbackStale": "Ce lien de connexion appartient à une tentative précédente. Recommencez depuis OpenPencil.",+ "aiSetupChatGPTUsage": "Les réponses sont décomptées des limites d’utilisation de votre forfait ChatGPT.",+ "aiSetupSavedSignInHint": "Votre connexion enregistrée sera utilisée.",+ "aiSetupUseRecommended": "Utiliser la configuration recommandée",+ "aiSetupRolesDescription": "Choisissez un modèle pour chaque type de travail. Nous avons choisi ceux recommandés parmi ce que vous avez connecté ; tout le reste de votre configuration reste inchangé.","chatReferenceLayers": "Calques","chatReferencePages": "Pages","chatReferenceSkills": "Compétences",@@ -417,6 +417,31 @@"skillWarningLongDescription": "La description dépasse {max} caractères.","skillErrorNoFrontmatter": "SKILL.md ne commence pas par un frontmatter YAML entre des lignes ---.","skillErrorInvalidFrontmatter": "Le frontmatter de SKILL.md n’est pas valide : {detail}",+ "contextUsed": "Contexte : {percent} % utilisé",+ "contextTitle": "Contexte",+ "contextTokens": "{used} sur {total} jetons",+ "contextCompactsAt": "Compacté automatiquement à {tokens} jetons, en laissant de la place pour la réponse.",+ "contextCompactsOff": "La compaction automatique est désactivée.",+ "contextNearlyFull": "Contexte {percent} % utilisé",+ "compact": "Compacter",+ "compactCommand": "Résumer la conversation jusqu’ici ; le texte qui suit indique ce qu’il faut garder",+ "compactAutomatically": "Compacter automatiquement",+ "compactAutomaticallyHint": "Résume les anciens messages quand la fenêtre de contexte se remplit.",+ "compacting": "Compaction de la conversation…",+ "compactionFailed": "La conversation n’a pas pu être compactée. Rien n’a été modifié.",+ "compactAndRetry": "Compacter et réessayer",+ "chatContextLimit": "La conversation est plus longue que ce que le modèle peut lire.",+ "conversationCompacted": "Conversation compactée",+ "compactionKeepsMessages": "Le modèle reçoit désormais ce résumé à la place des messages ci-dessus ; vous les voyez toujours.",+ "agentCompactionKeepsMessages": "L’agent travaille désormais à partir de son propre résumé des messages ci-dessus ; vous les voyez toujours.",+ "compactionTokens": "{before} → {after} jetons",+ "tokenUsage": "Utilisation des jetons",+ "tokenUsageHint": "Affiche les jetons de chaque réponse.",+ "tokenUsageHover": "Au survol",+ "tokenUsageAlways": "Toujours",+ "tokenUsageHidden": "Masqué",+ "replyTokens": "{input} en entrée · {output} en sortie",+ "replyCachedTokens": "{cached} en cache","skillErrorNoDescription": "Le frontmatter de SKILL.md n’a pas de description.","skillErrorNoName": "Le frontmatter de SKILL.md n’a pas de nom."}diff --git a/packages/vue/src/i18n/locales/it/ai.json b/packages/vue/src/i18n/locales/it/ai.jsonindex 90525a766..d2f753b8c 100644--- a/packages/vue/src/i18n/locales/it/ai.json+++ b/packages/vue/src/i18n/locales/it/ai.json@@ -1,7 +1,59 @@{+ "jumpToLatest": "Vai all’ultimo messaggio",+ "chatSettings": "Chat",+ "notificationsHint": "Solo mentre OpenPencil è in background o mostra un altro documento.",+ "notifyNeedsInput": "Un agente ha bisogno di te",+ "notifyNeedsInputHint": "Una richiesta di autorizzazione attende una risposta da qualche secondo.",+ "notifyFinished": "Una risposta è terminata",+ "notifyFailed": "Una risposta non è riuscita",+ "notificationsAllow": "Consenti notifiche",+ "notificationsAllowHint": "Il browser chiede una volta se OpenPencil può mostrare notifiche.",+ "notificationsBlocked": "Le notifiche sono bloccate per questo sito. Consentile nelle impostazioni del sito del browser.",+ "notificationsUnsupported": "Questo browser non può mostrare notifiche.",+ "notificationsSystemHint": "Se non ne compare nessuna, consenti OpenPencil nelle impostazioni di notifica del sistema.",+ "notifyTitle": "{agent} · {document}",+ "notifyPermission": "Chiede un’autorizzazione.",+ "notifyPermissionAction": "Chiede un’autorizzazione: {action}",+ "notifyReplyFinished": "La risposta dell’IA è terminata.",+ "notifyReplyFailed": "La risposta dell’IA si è interrotta con un errore.","maxAgentSteps": "Passaggi massimi per messaggio",+ "maxAgentStepsCustom": "Personalizzato…","maxAgentStepsHint": "Solo per l’IA integrata; ACP e Pi gestiscono i propri limiti. Si salva premendo Invio o uscendo dal campo e si applica al messaggio successivo. Limiti più alti possono aumentare i costi.","maxAgentStepsRange": "Inserisci un numero intero da {min} a {max}.",+ "reasoningDisplay": "Visualizzazione del ragionamento",+ "reasoningCollapsed": "Compresso per impostazione predefinita",+ "reasoningWhileThinking": "Espandi durante il ragionamento",+ "reasoningExpanded": "Espanso per impostazione predefinita",+ "continueChat": "Continua",+ "searchChats": "Cerca conversazioni…",+ "chatScope": "Ambito delle conversazioni",+ "thisDocument": "Questo documento",+ "allDocuments": "Tutti i documenti",+ "noChatsFound": "Nessuna conversazione trovata.",+ "chatActions": "Azioni della conversazione",+ "chatHistory": "Cronologia chat",+ "newChat": "Nuova chat",+ "followAgents": "Segui gli agenti mentre lavorano",+ "stopFollowingAgents": "Smetti di seguire gli agenti mentre lavorano",+ "allChats": "Tutte le chat",+ "renameChat": "Rinomina",+ "saveChatTrace": "Salva traccia…",+ "chatTraceFailed": "Impossibile salvare la traccia della chat.",+ "deleteChat": "Elimina",+ "chatTitle": "Titolo della chat",+ "saveChatTitle": "Salva",+ "cancelChatAction": "Annulla",+ "deleteChatConfirmation": "Eliminare definitivamente questa chat?",+ "deleteChatDescription": "«{title}» e i suoi messaggi vengono eliminati. L’operazione non può essere annullata.",+ "chatDocumentHint": "Apri il documento della chat per continuare.",+ "chatReadOnly": "Questa chat appartiene a un altro documento. Aprilo per continuare.",+ "chatAgentReadOnly": "La conversazione con l’agente è salvata, ma non è ancora possibile riprendere la sessione qui. Avvia una nuova chat.",+ "chatStorageFailed": "Impossibile salvare la cronologia. Tieni aperta questa finestra e riprova.",+ "chatHistoryFailed": "Impossibile aggiornare la cronologia. Riprova.",+ "chatInterrupted": "Questa risposta è stata interrotta.",+ "chatAgentWorkingOn": "{agent} sta lavorando su «{page}»",+ "chatGoToPage": "Vai alla pagina",+ "connectProvider": "Collega un provider AI per iniziare a chattare.","connectionTestSuccess": "Connessione riuscita. Il modello è raggiungibile.","connectionTestMissingAPIKey": "Inserisci una chiave API prima della verifica.","connectionTestMissingSignIn": "Accedi prima della verifica.",@@ -17,6 +69,7 @@"connectionTestBrowserNetworkFailed": "Impossibile raggiungere questo endpoint dal browser. Prova l’app desktop o usa un endpoint con CORS abilitato.","connectionTestNetworkFailed": "Impossibile raggiungere l’endpoint. Controlla l’URL e la connessione di rete.","connectionTestUnknownFailed": "Verifica della connessione non riuscita. Controlla le impostazioni del provider e riprova.",+ "getProviderAPIKey": "Ottieni una chiave API {provider} →","oneKeyManyModels": "Una chiave per oltre 100 modelli di tutti i provider.","describeChange": "Descrivi una modifica…","describeCreateOrChange": "Descrivi cosa vuoi creare o cambiare.",@@ -80,8 +133,10 @@"permissionRequest": "{tool} richiede l’autorizzazione.","baseURLPlaceholder": "URL di base (es. http://localhost:11434/v1)","modelIDPlaceholder": "ID modello (es. llama-3.3-70b)",+ "provider": "Provider AI","providerSettings": "Impostazioni provider","openProviderSettings": "Apri impostazioni provider",+ "modelsTitle": "Modelli","modelsDescription": "Configura modelli riutilizzabili e le connessioni ai provider.","addModel": "Aggiungi modello","editModel": "Modifica modello",@@ -152,9 +207,12 @@"chatSignInExpired": "Il tuo accesso è scaduto. Accedi di nuovo nelle Impostazioni.","chatPlanForbidden": "Il tuo piano non può usare il modello selezionato. Scegline un altro nelle Impostazioni.","chatForbidden": "Questa chiave API non può usare il modello selezionato. Controlla l’accesso al modello.",+ "chatInsufficientCredit": "L’account del provider non dispone di credito o quota sufficiente. Ricaricalo e riprova.",+ "chatOutputLimit": "Il modello ha esaurito i token di output durante il ragionamento. Aumenta i token di output massimi o riduci lo sforzo di ragionamento.","chatModelNotFound": "Il modello selezionato non è disponibile. Scegli un altro modello nelle Impostazioni.","chatNetworkFailed": "OpenPencil non ha raggiunto il provider. Controlla connessione ed endpoint.","chatRateLimited": "È stato raggiunto il limite di richieste del provider. Attendi e riprova.",+ "chatRequestFailed": "La richiesta al modello non è riuscita. Controlla le impostazioni del provider e riprova.","openProviderSettingsAction": "Apri impostazioni","cloudWorkspace": "Area di lavoro","cloudWorkspaceHint": "L’area di lavoro il cui piano paga queste richieste.",@@ -170,9 +228,6 @@"cloudCreditsRenew": "Si rinnova il {date}","manageCloudPlanAction": "Gestisci piano","chatCloudUnavailable": "L’IA di OpenPencil Cloud non è disponibile. Accedi a OpenPencil Cloud e scegli un’area di lavoro nelle impostazioni.",- "chatInsufficientCredit": "L’account del provider non dispone di credito o quota sufficiente. Ricaricalo e riprova.",- "chatOutputLimit": "Il modello ha esaurito i token di output durante il ragionamento. Aumenta i token di output massimi o riduci lo sforzo di ragionamento.",- "chatRequestFailed": "La richiesta al modello non è riuscita. Controlla le impostazioni del provider e riprova.","visionModelUnavailable": "Scegli un modello Vision nelle Impostazioni prima di allegare immagini.","chatPiCompanionMissing": "Pi richiede il companion Harness. Avvia la configurazione guidata per installarlo.","chatPiCompanionOutdated": "Il companion Harness non corrisponde a questa versione di OpenPencil. Avvia la configurazione guidata per aggiornarlo.",@@ -181,59 +236,6 @@"chatPiModel": "Pi non ha un modello. Esegui pi in un terminale e digita /model, oppure scegline uno nelle Impostazioni.","completions": "Completions","responses": "Responses",- "connectProvider": "Collega un provider AI per iniziare a chattare.",- "getProviderAPIKey": "Ottieni una chiave API {provider} →",- "provider": "Provider AI",- "modelsTitle": "Modelli",- "chatHistory": "Cronologia chat",- "newChat": "Nuova chat",- "followAgents": "Segui gli agenti mentre lavorano",- "stopFollowingAgents": "Smetti di seguire gli agenti mentre lavorano",- "allChats": "Tutte le chat",- "renameChat": "Rinomina",- "saveChatTrace": "Salva traccia…",- "chatTraceFailed": "Impossibile salvare la traccia della chat.",- "deleteChat": "Elimina",- "chatTitle": "Titolo della chat",- "saveChatTitle": "Salva",- "cancelChatAction": "Annulla",- "deleteChatConfirmation": "Eliminare definitivamente questa chat?",- "deleteChatDescription": "«{title}» e i suoi messaggi vengono eliminati. L’operazione non può essere annullata.",- "chatDocumentHint": "Apri il documento della chat per continuare.",- "chatReadOnly": "Questa chat appartiene a un altro documento. Aprilo per continuare.",- "chatAgentReadOnly": "La conversazione con l’agente è salvata, ma non è ancora possibile riprendere la sessione qui. Avvia una nuova chat.",- "chatStorageFailed": "Impossibile salvare la cronologia. Tieni aperta questa finestra e riprova.",- "chatHistoryFailed": "Impossibile aggiornare la cronologia. Riprova.",- "chatInterrupted": "Questa risposta è stata interrotta.",- "searchChats": "Cerca conversazioni…",- "chatScope": "Ambito delle conversazioni",- "thisDocument": "Questo documento",- "allDocuments": "Tutti i documenti",- "noChatsFound": "Nessuna conversazione trovata.",- "chatActions": "Azioni della conversazione",- "continueChat": "Continua",- "chatSettings": "Chat",- "notificationsHint": "Solo mentre OpenPencil è in background o mostra un altro documento.",- "notifyNeedsInput": "Un agente ha bisogno di te",- "notifyNeedsInputHint": "Una richiesta di autorizzazione attende una risposta da qualche secondo.",- "notifyFinished": "Una risposta è terminata",- "notifyFailed": "Una risposta non è riuscita",- "notificationsAllow": "Consenti notifiche",- "notificationsAllowHint": "Il browser chiede una volta se OpenPencil può mostrare notifiche.",- "notificationsBlocked": "Le notifiche sono bloccate per questo sito. Consentile nelle impostazioni del sito del browser.",- "notificationsUnsupported": "Questo browser non può mostrare notifiche.",- "notificationsSystemHint": "Se non ne compare nessuna, consenti OpenPencil nelle impostazioni di notifica del sistema.",- "notifyTitle": "{agent} · {document}",- "notifyPermission": "Chiede un’autorizzazione.",- "notifyPermissionAction": "Chiede un’autorizzazione: {action}",- "notifyReplyFinished": "La risposta dell’IA è terminata.",- "notifyReplyFailed": "La risposta dell’IA si è interrotta con un errore.",- "reasoningDisplay": "Visualizzazione del ragionamento",- "reasoningCollapsed": "Compresso per impostazione predefinita",- "reasoningWhileThinking": "Espandi durante il ragionamento",- "reasoningExpanded": "Espanso per impostazione predefinita",- "jumpToLatest": "Vai all’ultimo messaggio",- "maxAgentStepsCustom": "Personalizzato…","aiSetupWelcomeTitle": "Benvenuto in OpenPencil","aiSetupWelcomeDescription": "Crea e modifica design su una tela aperta. Importa file Figma e falli tuoi.","aiSetupWelcomeAITitle": "Progetta con l’IA",@@ -259,69 +261,34 @@"modelProviderSetUp": "Configurato","aiSetupAccessAPI": "Account API","aiSetupAccessServer": "Modello locale o server aziendale",+ "aiSetupAccessMore": "Altri fornitori",+ "providerGroupAgents": "I tuoi agenti",+ "providerGroupProviders": "Fornitori",+ "aiSetupServerOther": "Altro server","aiSetupAccessServerDescription": "Qualsiasi server compatibile con l’API di OpenAI, come Ollama o LM Studio.","aiSetupConnectTitle": "Collega la tua IA","aiSetupNothingDescription": "Torna indietro per scegliere un altro accesso o configura l’IA nelle impostazioni avanzate.","aiSetupAgentDescription": "OpenPencil avvia {agent} quando invii un messaggio, con l’account a cui {agent} ha effettuato l’accesso.","aiSetupAgentInstall": "Se non è ancora installato, esegui:","aiSetupAgentInstallSupported": "Installa l’adattatore supportato:",- "aiSetupMeteredNote": "OpenRouter offre modelli di più fornitori con un solo account e una sola chiave.",- "aiSetupSkillsTitle": "Skill dei tuoi agenti di programmazione",- "aiSetupSkillsDescription": "La chat di design può usare le skill installate dai tuoi agenti di programmazione. La maggior parte sono flussi di sviluppo, quindi scegli solo quelle utili al design; puoi cambiarle in Impostazioni › Skill.",- "aiSetupReviewTitle": "Controlla la configurazione",- "aiSetupAgentModel": "Modello scelto dall’agente",- "aiSetupFinish": "Completa la configurazione",- "aiSetupSavedTitle": "L’IA è pronta",- "aiSetupSavedDescription": "Puoi cambiare modelli e ruoli in qualsiasi momento nelle Impostazioni.",- "aiSetupRun": "Avvia la configurazione guidata",- "aiSetupServerKeyHint": "Se il server non verifica le chiavi, inserisci un valore qualsiasi.",- "aiSetupAlreadyConnected": "Tutto ciò che hai selezionato è già collegato.",- "aiSetupOpenRouterSignIn": "Accedi con OpenRouter",- "aiSetupOpenRouterWaiting": "Completa l’accesso a OpenRouter nel browser.",- "aiSetupSignInReopen": "Apri di nuovo",- "aiSetupOpenRouterOrKey": "Oppure incolla una chiave API",- "aiSetupOpenRouterBlocked": "Il browser ha bloccato la finestra di accesso. Consenti i pop-up per OpenPencil e riprova.",- "aiSetupSignInCancelled": "L’accesso è stato annullato.",- "aiSetupSignInExpired": "L’accesso ha richiesto troppo tempo. Riprova.",- "aiSetupOpenRouterFailed": "Impossibile accedere a OpenRouter. Riprova o incolla una chiave API.",- "aiSetupOpenRouterSignedInTitle": "Accesso a OpenRouter eseguito",- "aiSetupSavedKeyHint": "Lascia vuoto per mantenere la chiave salvata.",- "aiSetupOpenRouterKeyLabel": "· chiave «{label}»",- "aiSetupOpenRouterVerifying": "Verifica della chiave OpenRouter…",- "aiSetupOpenRouterNoCredits": "Questo account OpenRouter non ha ancora crediti. Aggiungi crediti su OpenRouter per usare modelli a pagamento come quello consigliato.",- "aiSetupSignInChange": "Usa un altro account",- "aiSetupSignOut": "Esci",- "aiSetupAccessSubscriptions": "Abbonamenti",- "aiSetupAccessChatGPT": "Usa i modelli del tuo piano ChatGPT nell’agente di OpenPencil.",- "aiSetupChatGPTSignIn": "Accedi con ChatGPT",- "aiSetupChatGPTWaiting": "Completa l’accesso a ChatGPT nel browser.",- "aiSetupChatGPTSignedInTitle": "Accesso a ChatGPT eseguito",- "aiSetupChatGPTFailed": "Impossibile accedere a ChatGPT. Riprova.",- "aiSetupChatGPTPortInUse": "Un altro accesso, come `codex login`, sta usando la porta 1455. Completalo o chiudilo, poi riprova.",- "aiSetupChatGPTCallbackSignedIn": "Accesso a ChatGPT eseguito. Puoi chiudere questa scheda e tornare a OpenPencil.",- "aiSetupChatGPTCallbackCancelled": "L’accesso a ChatGPT è stato annullato. Puoi chiudere questa scheda.",- "aiSetupChatGPTCallbackStale": "Questo link di accesso appartiene a un tentativo precedente. Ricomincia da OpenPencil.",- "aiSetupChatGPTUsage": "Le risposte rientrano nei limiti di utilizzo del tuo piano ChatGPT.",- "aiSetupSavedSignInHint": "Verrà usato l’accesso salvato.",- "aiSetupUseRecommended": "Usa la configurazione consigliata",- "aiSetupRolesDescription": "Scegli un modello per ogni tipo di lavoro. Abbiamo scelto quelli consigliati tra ciò che hai collegato; tutto il resto che hai configurato resta invariato.",- "aiSetupGapDesign": "Nulla di ciò che hai scelto può creare e modificare design.",- "aiSetupGapVision": "Nulla di ciò che hai scelto può esaminare immagini, quindi la revisione visiva resterebbe disattivata.",- "aiSetupGapContinue": "Puoi continuare senza e aggiungerlo in seguito nelle Impostazioni.",- "aiSetupGapAddOpenRouter": "Aggiungi OpenRouter (a consumo)",- "aiSetupGapRemoveOpenRouter": "Non usare OpenRouter",- "aiSetupServerVision": "Questo modello può leggere immagini",- "aiSetupGapCoveredByOpenRouter": "OpenRouter coprirà ciò che le altre scelte non coprono, con addebito per richiesta.",- "aiSetupAccessMore": "Altri fornitori",- "providerGroupAgents": "I tuoi agenti",- "providerGroupProviders": "Fornitori",- "aiSetupServerOther": "Altro server","aiSetupAgentChecking": "Controllo di questo computer…","aiSetupAgentInstalled": "installato","aiSetupAgentNotFound": "non trovato","aiSetupAgentMCP": "Server MCP di OpenPencil","aiSetupAgentMCPInstall": "Gli agenti di programmazione accedono alla tela tramite il server MCP di OpenPencil. Installalo con:","aiSetupAgentPromptHint": "Usi già {agent} o un altro agente di programmazione? Copia il prompt di configurazione e incollalo lì: installerà ciò che serve a OpenPencil.",+ "aiSetupAgentNeedsAdapter": "installato · manca l’adattatore OpenPencil",+ "aiSetupAgentInstallAdapter": "Installa adattatore",+ "aiSetupAgentInstallMCP": "Installa server MCP",+ "aiSetupAgentUpdateMCP": "Aggiorna server MCP",+ "aiSetupAgentOutdated": "aggiornamento necessario",+ "aiSetupAgentInstalling": "Installazione…",+ "aiSetupAgentGetCLI": "Installa {agent}",+ "aiSetupAgentNeedsNpm": "Per installare serve npm, incluso in Node.js. Installa Node.js e poi controlla di nuovo.",+ "aiSetupAgentNeedsAdmin": "L’installazione richiede i diritti di amministratore, perché npm salva i pacchetti globali in una cartella protetta. Esegui il comando qui sotto in un terminale, oppure lascia che il tuo agente configuri una cartella tua.",+ "aiSetupAgentInstallFailed": "L’installazione non è stata completata. Controlla la connessione o esegui il comando manualmente.",+ "aiSetupAgentMCPStartFailed": "Il server MCP è installato ma non si è avviato. Riavvia OpenPencil e controlla di nuovo.",+ "aiSetupAgentLookupFailed": "Impossibile controllare questo computer. Riprova.","aiSetupAgentCopyPrompt": "Copia il prompt di configurazione","aiSetupAgentCheckAgain": "Controlla di nuovo","aiSetupAgentInstallRuns": "L’installazione esegue {command}.",@@ -356,20 +323,53 @@"piModelHint": "Un modello Pi come provider/model. Lascia vuoto per usare il modello predefinito di Pi.","aiSetupPiSignIn": "Per accedere a un provider o scegliere un modello predefinito, esegui pi in un terminale e digita /login o /model.","aiSetupGetDesktop": "Scarica l’app desktop",- "aiSetupAgentNeedsAdapter": "installato · manca l’adattatore OpenPencil",- "aiSetupAgentInstallAdapter": "Installa adattatore",- "aiSetupAgentInstallMCP": "Installa server MCP",- "aiSetupAgentUpdateMCP": "Aggiorna server MCP",- "aiSetupAgentOutdated": "aggiornamento necessario",- "aiSetupAgentInstalling": "Installazione…",- "aiSetupAgentGetCLI": "Installa {agent}",- "aiSetupAgentNeedsNpm": "Per installare serve npm, incluso in Node.js. Installa Node.js e poi controlla di nuovo.",- "aiSetupAgentNeedsAdmin": "L’installazione richiede i diritti di amministratore, perché npm salva i pacchetti globali in una cartella protetta. Esegui il comando qui sotto in un terminale, oppure lascia che il tuo agente configuri una cartella tua.",- "aiSetupAgentInstallFailed": "L’installazione non è stata completata. Controlla la connessione o esegui il comando manualmente.",- "aiSetupAgentMCPStartFailed": "Il server MCP è installato ma non si è avviato. Riavvia OpenPencil e controlla di nuovo.",- "aiSetupAgentLookupFailed": "Impossibile controllare questo computer. Riprova.",- "chatAgentWorkingOn": "{agent} sta lavorando su «{page}»",- "chatGoToPage": "Vai alla pagina",+ "aiSetupMeteredNote": "OpenRouter offre modelli di più fornitori con un solo account e una sola chiave.",+ "aiSetupSkillsTitle": "Skill dei tuoi agenti di programmazione",+ "aiSetupSkillsDescription": "La chat di design può usare le skill installate dai tuoi agenti di programmazione. La maggior parte sono flussi di sviluppo, quindi scegli solo quelle utili al design; puoi cambiarle in Impostazioni › Skill.",+ "aiSetupReviewTitle": "Controlla la configurazione",+ "aiSetupAgentModel": "Modello scelto dall’agente",+ "aiSetupFinish": "Completa la configurazione",+ "aiSetupSavedTitle": "L’IA è pronta",+ "aiSetupSavedDescription": "Puoi cambiare modelli e ruoli in qualsiasi momento nelle Impostazioni.",+ "aiSetupRun": "Avvia la configurazione guidata",+ "aiSetupServerKeyHint": "Se il server non verifica le chiavi, inserisci un valore qualsiasi.",+ "aiSetupGapDesign": "Nulla di ciò che hai scelto può creare e modificare design.",+ "aiSetupGapVision": "Nulla di ciò che hai scelto può esaminare immagini, quindi la revisione visiva resterebbe disattivata.",+ "aiSetupGapContinue": "Puoi continuare senza e aggiungerlo in seguito nelle Impostazioni.",+ "aiSetupGapAddOpenRouter": "Aggiungi OpenRouter (a consumo)",+ "aiSetupGapRemoveOpenRouter": "Non usare OpenRouter",+ "aiSetupGapCoveredByOpenRouter": "OpenRouter coprirà ciò che le altre scelte non coprono, con addebito per richiesta.",+ "aiSetupServerVision": "Questo modello può leggere immagini",+ "aiSetupSavedKeyHint": "Lascia vuoto per mantenere la chiave salvata.",+ "aiSetupAlreadyConnected": "Tutto ciò che hai selezionato è già collegato.",+ "aiSetupOpenRouterSignIn": "Accedi con OpenRouter",+ "aiSetupOpenRouterWaiting": "Completa l’accesso a OpenRouter nel browser.",+ "aiSetupSignInReopen": "Apri di nuovo",+ "aiSetupOpenRouterOrKey": "Oppure incolla una chiave API",+ "aiSetupOpenRouterBlocked": "Il browser ha bloccato la finestra di accesso. Consenti i pop-up per OpenPencil e riprova.",+ "aiSetupSignInCancelled": "L’accesso è stato annullato.",+ "aiSetupSignInExpired": "L’accesso ha richiesto troppo tempo. Riprova.",+ "aiSetupOpenRouterFailed": "Impossibile accedere a OpenRouter. Riprova o incolla una chiave API.",+ "aiSetupOpenRouterSignedInTitle": "Accesso a OpenRouter eseguito",+ "aiSetupOpenRouterKeyLabel": "· chiave «{label}»",+ "aiSetupOpenRouterVerifying": "Verifica della chiave OpenRouter…",+ "aiSetupOpenRouterNoCredits": "Questo account OpenRouter non ha ancora crediti. Aggiungi crediti su OpenRouter per usare modelli a pagamento come quello consigliato.",+ "aiSetupSignInChange": "Usa un altro account",+ "aiSetupSignOut": "Esci",+ "aiSetupAccessSubscriptions": "Abbonamenti",+ "aiSetupAccessChatGPT": "Usa i modelli del tuo piano ChatGPT nell’agente di OpenPencil.",+ "aiSetupChatGPTSignIn": "Accedi con ChatGPT",+ "aiSetupChatGPTWaiting": "Completa l’accesso a ChatGPT nel browser.",+ "aiSetupChatGPTSignedInTitle": "Accesso a ChatGPT eseguito",+ "aiSetupChatGPTFailed": "Impossibile accedere a ChatGPT. Riprova.",+ "aiSetupChatGPTPortInUse": "Un altro accesso, come `codex login`, sta usando la porta 1455. Completalo o chiudilo, poi riprova.",+ "aiSetupChatGPTCallbackSignedIn": "Accesso a ChatGPT eseguito. Puoi chiudere questa scheda e tornare a OpenPencil.",+ "aiSetupChatGPTCallbackCancelled": "L’accesso a ChatGPT è stato annullato. Puoi chiudere questa scheda.",+ "aiSetupChatGPTCallbackStale": "Questo link di accesso appartiene a un tentativo precedente. Ricomincia da OpenPencil.",+ "aiSetupChatGPTUsage": "Le risposte rientrano nei limiti di utilizzo del tuo piano ChatGPT.",+ "aiSetupSavedSignInHint": "Verrà usato l’accesso salvato.",+ "aiSetupUseRecommended": "Usa la configurazione consigliata",+ "aiSetupRolesDescription": "Scegli un modello per ogni tipo di lavoro. Abbiamo scelto quelli consigliati tra ciò che hai collegato; tutto il resto che hai configurato resta invariato.","chatReferenceLayers": "Livelli","chatReferencePages": "Pagine","chatReferenceSkills": "Skill",@@ -417,6 +417,31 @@"skillWarningLongDescription": "La descrizione supera i {max} caratteri.","skillErrorNoFrontmatter": "SKILL.md non inizia con un frontmatter YAML tra righe ---.","skillErrorInvalidFrontmatter": "Il frontmatter di SKILL.md non è valido: {detail}",+ "contextUsed": "Contesto: {percent}% usato",+ "contextTitle": "Contesto",+ "contextTokens": "{used} di {total} token",+ "contextCompactsAt": "Si compatta automaticamente a {tokens} token, lasciando spazio per la risposta.",+ "contextCompactsOff": "La compattazione automatica è disattivata.",+ "contextNearlyFull": "Contesto {percent}% usato",+ "compact": "Compatta",+ "compactCommand": "Riassumi la conversazione finora; il testo che segue dice cosa conservare",+ "compactAutomatically": "Compatta automaticamente",+ "compactAutomaticallyHint": "Riassume i messaggi precedenti quando la finestra di contesto si riempie.",+ "compacting": "Compattazione della conversazione…",+ "compactionFailed": "Impossibile compattare la conversazione. Non è stato cambiato nulla.",+ "compactAndRetry": "Compatta e riprova",+ "chatContextLimit": "La conversazione è più lunga di quanto il modello possa leggere.",+ "conversationCompacted": "Conversazione compattata",+ "compactionKeepsMessages": "Ora il modello riceve questo riepilogo al posto dei messaggi sopra; tu continui a vederli.",+ "agentCompactionKeepsMessages": "L’agente ora lavora sul proprio riepilogo dei messaggi sopra; tu continui a vederli.",+ "compactionTokens": "{before} → {after} token",+ "tokenUsage": "Uso dei token",+ "tokenUsageHint": "Mostra i token di ogni risposta.",+ "tokenUsageHover": "Al passaggio del mouse",+ "tokenUsageAlways": "Sempre",+ "tokenUsageHidden": "Nascosto",+ "replyTokens": "{input} in ingresso · {output} in uscita",+ "replyCachedTokens": "{cached} in cache","skillErrorNoDescription": "Il frontmatter di SKILL.md non ha una descrizione.","skillErrorNoName": "Il frontmatter di SKILL.md non ha un nome."}diff --git a/packages/vue/src/i18n/locales/ja/ai.json b/packages/vue/src/i18n/locales/ja/ai.jsonindex 0e3a0d8d2..45a8b0158 100644--- a/packages/vue/src/i18n/locales/ja/ai.json+++ b/packages/vue/src/i18n/locales/ja/ai.json@@ -1,7 +1,59 @@{+ "jumpToLatest": "最新へ移動",+ "chatSettings": "チャット",+ "notificationsHint": "OpenPencil がバックグラウンドにあるか、別のドキュメントを表示しているときだけ送ります。",+ "notifyNeedsInput": "エージェントが応答を待っているとき",+ "notifyNeedsInputHint": "許可のリクエストが数秒間応答されていないとき。",+ "notifyFinished": "返信が完了したとき",+ "notifyFailed": "返信が失敗したとき",+ "notificationsAllow": "通知を許可",+ "notificationsAllowHint": "OpenPencil に通知を許可するか、ブラウザが一度だけ確認します。",+ "notificationsBlocked": "このサイトの通知はブロックされています。ブラウザのサイト設定で許可してください。",+ "notificationsUnsupported": "このブラウザは通知を表示できません。",+ "notificationsSystemHint": "表示されない場合は、システムの通知設定で OpenPencil を許可してください。",+ "notifyTitle": "{agent} · {document}",+ "notifyPermission": "許可を求めています。",+ "notifyPermissionAction": "許可を求めています: {action}",+ "notifyReplyFinished": "AI の返信が完了しました。",+ "notifyReplyFailed": "AI の返信がエラーで停止しました。","maxAgentSteps": "メッセージごとの最大ステップ数",+ "maxAgentStepsCustom": "カスタム…","maxAgentStepsHint": "内蔵 AI のみが対象です。ACP と Pi は独自の上限を使用します。Enter キーまたは入力欄から移動したときに保存され、次のメッセージから適用されます。上限を増やすと費用が増える場合があります。","maxAgentStepsRange": "{min} から {max} までの整数を入力してください。",+ "reasoningDisplay": "推論の表示",+ "reasoningCollapsed": "既定で折りたたむ",+ "reasoningWhileThinking": "思考中に展開",+ "reasoningExpanded": "既定で展開",+ "continueChat": "続ける",+ "searchChats": "会話を検索…",+ "chatScope": "会話の範囲",+ "thisDocument": "このドキュメント",+ "allDocuments": "すべてのドキュメント",+ "noChatsFound": "会話が見つかりません。",+ "chatActions": "会話の操作",+ "chatHistory": "チャット履歴",+ "newChat": "新しいチャット",+ "followAgents": "作業中のエージェントを追従",+ "stopFollowingAgents": "作業中のエージェントの追従を停止",+ "allChats": "すべてのチャット",+ "renameChat": "名前を変更",+ "saveChatTrace": "トレースを保存…",+ "chatTraceFailed": "チャットのトレースを保存できませんでした。",+ "deleteChat": "削除",+ "chatTitle": "チャットのタイトル",+ "saveChatTitle": "保存",+ "cancelChatAction": "キャンセル",+ "deleteChatConfirmation": "このチャットを完全に削除しますか?",+ "deleteChatDescription": "「{title}」とそのメッセージは削除されます。元に戻すことはできません。",+ "chatDocumentHint": "続けるにはチャットのドキュメントを開いてください。",+ "chatReadOnly": "このチャットは別のドキュメントに属しています。続けるにはそのドキュメントを開いてください。",+ "chatAgentReadOnly": "エージェントとの会話は保存されていますが、ここではまだセッションを再開できません。新しいチャットを開始してください。",+ "chatStorageFailed": "チャット履歴を保存できませんでした。このウィンドウを開いたまま、もう一度お試しください。",+ "chatHistoryFailed": "チャット履歴を更新できませんでした。もう一度お試しください。",+ "chatInterrupted": "この応答は中断されました。",+ "chatAgentWorkingOn": "{agent}が「{page}」で作業中",+ "chatGoToPage": "ページへ移動",+ "connectProvider": "チャットを始めるには、AIプロバイダーを接続してください。","connectionTestSuccess": "接続しました。モデルにアクセスできます。","connectionTestMissingAPIKey": "テストする前にAPIキーを入力してください。","connectionTestMissingSignIn": "テストする前にサインインしてください。",@@ -17,6 +69,7 @@"connectionTestBrowserNetworkFailed": "ブラウザからこのエンドポイントに接続できませんでした。デスクトップアプリを試すか、CORSが有効なエンドポイントを使用してください。","connectionTestNetworkFailed": "エンドポイントに接続できませんでした。URLとネットワーク接続を確認してください。","connectionTestUnknownFailed": "接続テストに失敗しました。プロバイダー設定を確認して、もう一度お試しください。",+ "getProviderAPIKey": "{provider} からAPIキーを取得 →","oneKeyManyModels": "1つのキーで、すべてのプロバイダーの100以上のモデルに対応。","describeChange": "変更内容を入力…","describeCreateOrChange": "作成または変更したい内容を入力してください。",@@ -80,8 +133,10 @@"permissionRequest": "{tool}が権限を要求しています。","baseURLPlaceholder": "ベースURL (例: http://localhost:11434/v1)","modelIDPlaceholder": "モデルID (例: llama-3.3-70b)",+ "provider": "AIプロバイダー","providerSettings": "プロバイダー設定","openProviderSettings": "プロバイダー設定を開く",+ "modelsTitle": "モデル","modelsDescription": "再利用可能なモデルとプロバイダー接続を設定します。","addModel": "モデルを追加","editModel": "モデルを編集",@@ -152,9 +207,12 @@"chatSignInExpired": "サインインの有効期限が切れました。設定でもう一度サインインしてください。","chatPlanForbidden": "ご利用のプランでは選択したモデルを使用できません。設定で別のモデルを選んでください。","chatForbidden": "このAPIキーでは選択したモデルを使用できません。モデルへのアクセス権を確認してください。",+ "chatInsufficientCredit": "プロバイダーのアカウントに十分なクレジットまたは割り当てがありません。チャージして再試行してください。",+ "chatOutputLimit": "推論中にモデルの出力トークンが上限に達しました。最大出力トークンを増やすか、推論の強度を下げてください。","chatModelNotFound": "選択したモデルは利用できません。設定で別のモデルを選択してください。","chatNetworkFailed": "OpenPencilからプロバイダーに接続できませんでした。接続とエンドポイントを確認してください。","chatRateLimited": "プロバイダーのリクエスト制限に達しました。少し待ってから再試行してください。",+ "chatRequestFailed": "モデルへのリクエストに失敗しました。プロバイダー設定を確認して再試行してください。","openProviderSettingsAction": "設定を開く","cloudWorkspace": "ワークスペース","cloudWorkspaceHint": "これらのリクエストの料金を支払うプランのワークスペースです。",@@ -170,9 +228,6 @@"cloudCreditsRenew": "{date} に更新","manageCloudPlanAction": "プランを管理","chatCloudUnavailable": "OpenPencil Cloud の AI を利用できません。OpenPencil Cloud にサインインし、設定でワークスペースを選んでください。",- "chatInsufficientCredit": "プロバイダーのアカウントに十分なクレジットまたは割り当てがありません。チャージして再試行してください。",- "chatOutputLimit": "推論中にモデルの出力トークンが上限に達しました。最大出力トークンを増やすか、推論の強度を下げてください。",- "chatRequestFailed": "モデルへのリクエストに失敗しました。プロバイダー設定を確認して再試行してください。","visionModelUnavailable": "画像を添付する前に、設定でビジョンモデルを選択してください。","chatPiCompanionMissing": "Pi には Harness コンパニオンが必要です。ガイド付きセットアップを実行してインストールしてください。","chatPiCompanionOutdated": "Harness コンパニオンがこのバージョンの OpenPencil と一致しません。ガイド付きセットアップを実行して更新してください。",@@ -181,59 +236,6 @@"chatPiModel": "Pi に使用するモデルがありません。ターミナルで pi を実行して /model と入力するか、設定で選択してください。","completions": "入力補完","responses": "応答",- "connectProvider": "チャットを始めるには、AIプロバイダーを接続してください。",- "getProviderAPIKey": "{provider} からAPIキーを取得 →",- "provider": "AIプロバイダー",- "modelsTitle": "モデル",- "chatHistory": "チャット履歴",- "newChat": "新しいチャット",- "followAgents": "作業中のエージェントを追従",- "stopFollowingAgents": "作業中のエージェントの追従を停止",- "allChats": "すべてのチャット",- "renameChat": "名前を変更",- "saveChatTrace": "トレースを保存…",- "chatTraceFailed": "チャットのトレースを保存できませんでした。",- "deleteChat": "削除",- "chatTitle": "チャットのタイトル",- "saveChatTitle": "保存",- "cancelChatAction": "キャンセル",- "deleteChatConfirmation": "このチャットを完全に削除しますか?",- "deleteChatDescription": "「{title}」とそのメッセージは削除されます。元に戻すことはできません。",- "chatDocumentHint": "続けるにはチャットのドキュメントを開いてください。",- "chatReadOnly": "このチャットは別のドキュメントに属しています。続けるにはそのドキュメントを開いてください。",- "chatAgentReadOnly": "エージェントとの会話は保存されていますが、ここではまだセッションを再開できません。新しいチャットを開始してください。",- "chatStorageFailed": "チャット履歴を保存できませんでした。このウィンドウを開いたまま、もう一度お試しください。",- "chatHistoryFailed": "チャット履歴を更新できませんでした。もう一度お試しください。",- "chatInterrupted": "この応答は中断されました。",- "searchChats": "会話を検索…",- "chatScope": "会話の範囲",- "thisDocument": "このドキュメント",- "allDocuments": "すべてのドキュメント",- "noChatsFound": "会話が見つかりません。",- "chatActions": "会話の操作",- "continueChat": "続ける",- "chatSettings": "チャット",- "notificationsHint": "OpenPencil がバックグラウンドにあるか、別のドキュメントを表示しているときだけ送ります。",- "notifyNeedsInput": "エージェントが応答を待っているとき",- "notifyNeedsInputHint": "許可のリクエストが数秒間応答されていないとき。",- "notifyFinished": "返信が完了したとき",- "notifyFailed": "返信が失敗したとき",- "notificationsAllow": "通知を許可",- "notificationsAllowHint": "OpenPencil に通知を許可するか、ブラウザが一度だけ確認します。",- "notificationsBlocked": "このサイトの通知はブロックされています。ブラウザのサイト設定で許可してください。",- "notificationsUnsupported": "このブラウザは通知を表示できません。",- "notificationsSystemHint": "表示されない場合は、システムの通知設定で OpenPencil を許可してください。",- "notifyTitle": "{agent} · {document}",- "notifyPermission": "許可を求めています。",- "notifyPermissionAction": "許可を求めています: {action}",- "notifyReplyFinished": "AI の返信が完了しました。",- "notifyReplyFailed": "AI の返信がエラーで停止しました。",- "reasoningDisplay": "推論の表示",- "reasoningCollapsed": "既定で折りたたむ",- "reasoningWhileThinking": "思考中に展開",- "reasoningExpanded": "既定で展開",- "jumpToLatest": "最新へ移動",- "maxAgentStepsCustom": "カスタム…","aiSetupWelcomeTitle": "OpenPencil へようこそ","aiSetupWelcomeDescription": "オープンなキャンバスでデザインを作成・編集できます。Figma ファイルを読み込んで自由に使えます。","aiSetupWelcomeAITitle": "AI でデザインする",@@ -259,69 +261,34 @@"modelProviderSetUp": "設定済み","aiSetupAccessAPI": "API アカウント","aiSetupAccessServer": "ローカルモデルまたは社内サーバー",+ "aiSetupAccessMore": "その他のプロバイダー",+ "providerGroupAgents": "あなたのエージェント",+ "providerGroupProviders": "プロバイダー",+ "aiSetupServerOther": "その他のサーバー","aiSetupAccessServerDescription": "Ollama や LM Studio など、OpenAI API 互換のサーバー。","aiSetupConnectTitle": "AI を接続","aiSetupNothingDescription": "戻って別のものを選ぶか、詳細設定で AI を設定してください。","aiSetupAgentDescription": "メッセージを送ると、OpenPencil は {agent} がサインインしているアカウントで {agent} を起動します。","aiSetupAgentInstall": "まだインストールしていない場合は、次を実行してください:","aiSetupAgentInstallSupported": "対応しているアダプターをインストールします:",- "aiSetupMeteredNote": "OpenRouter なら、1 つのアカウントと 1 つのキーで複数ベンダーのモデルを使えます。",- "aiSetupSkillsTitle": "コーディングエージェントのスキル",- "aiSetupSkillsDescription": "デザインチャットでは、コーディングエージェントがインストールしたスキルを使えます。多くは開発用のワークフローなので、デザインに役立つものだけを選んでください。あとから 設定 › スキル で変更できます。",- "aiSetupReviewTitle": "設定を確認",- "aiSetupAgentModel": "モデルはエージェントが選択",- "aiSetupFinish": "設定を完了",- "aiSetupSavedTitle": "AI の準備ができました",- "aiSetupSavedDescription": "モデルと役割はいつでも設定で変更できます。",- "aiSetupRun": "ガイド付き設定を開始",- "aiSetupServerKeyHint": "サーバーがキーを確認しない場合は、任意の値を入力してください。",- "aiSetupAlreadyConnected": "選んだものはすべて接続済みです。",- "aiSetupOpenRouterSignIn": "OpenRouter でサインイン",- "aiSetupOpenRouterWaiting": "ブラウザで OpenRouter へのサインインを完了してください。",- "aiSetupSignInReopen": "もう一度開く",- "aiSetupOpenRouterOrKey": "または API キーを貼り付け",- "aiSetupOpenRouterBlocked": "ブラウザがサインイン用のウィンドウをブロックしました。OpenPencil のポップアップを許可してから、もう一度お試しください。",- "aiSetupSignInCancelled": "サインインはキャンセルされました。",- "aiSetupSignInExpired": "サインインに時間がかかりすぎました。もう一度お試しください。",- "aiSetupOpenRouterFailed": "OpenRouter にサインインできませんでした。もう一度試すか、API キーを貼り付けてください。",- "aiSetupOpenRouterSignedInTitle": "OpenRouter にサインインしました",- "aiSetupSavedKeyHint": "保存済みのキーを使う場合は空欄のままにしてください。",- "aiSetupOpenRouterKeyLabel": "・キー「{label}」",- "aiSetupOpenRouterVerifying": "OpenRouter のキーを確認しています…",- "aiSetupOpenRouterNoCredits": "この OpenRouter アカウントにはまだクレジットがありません。推奨モデルなどの有料モデルを使うには、OpenRouter でクレジットを追加してください。",- "aiSetupSignInChange": "別のアカウントを使う",- "aiSetupSignOut": "サインアウト",- "aiSetupAccessSubscriptions": "サブスクリプション",- "aiSetupAccessChatGPT": "ChatGPT プランのモデルを OpenPencil のエージェントで使います。",- "aiSetupChatGPTSignIn": "ChatGPT でサインイン",- "aiSetupChatGPTWaiting": "ブラウザで ChatGPT へのサインインを完了してください。",- "aiSetupChatGPTSignedInTitle": "ChatGPT にサインインしました",- "aiSetupChatGPTFailed": "ChatGPT にサインインできませんでした。もう一度お試しください。",- "aiSetupChatGPTPortInUse": "別のサインイン(`codex login` など)がポート 1455 を使用しています。完了するか閉じてから、もう一度お試しください。",- "aiSetupChatGPTCallbackSignedIn": "ChatGPT にサインインしました。このタブを閉じて OpenPencil に戻ってください。",- "aiSetupChatGPTCallbackCancelled": "ChatGPT へのサインインはキャンセルされました。このタブを閉じてください。",- "aiSetupChatGPTCallbackStale": "このサインインリンクは以前の試行のものです。OpenPencil からやり直してください。",- "aiSetupChatGPTUsage": "応答は ChatGPT プランの利用上限にカウントされます。",- "aiSetupSavedSignInHint": "保存済みのサインインを使用します。",- "aiSetupUseRecommended": "推奨の設定を使う",- "aiSetupRolesDescription": "作業の種類ごとにモデルを選んでください。接続したものから推奨モデルを選んであります。ほかに設定した内容はそのまま残ります。",- "aiSetupGapDesign": "選んだものではデザインの作成と編集ができません。",- "aiSetupGapVision": "選んだものでは画像を確認できないため、ビジュアルレビューはオフのままになります。",- "aiSetupGapContinue": "このまま続けて、あとから設定で追加することもできます。",- "aiSetupGapAddOpenRouter": "OpenRouter を追加(従量課金)",- "aiSetupGapRemoveOpenRouter": "OpenRouter を使わない",- "aiSetupServerVision": "このモデルは画像を読み取れます",- "aiSetupGapCoveredByOpenRouter": "ほかの選択で対応できない部分は OpenRouter が担当し、リクエストごとに課金されます。",- "aiSetupAccessMore": "その他のプロバイダー",- "providerGroupAgents": "あなたのエージェント",- "providerGroupProviders": "プロバイダー",- "aiSetupServerOther": "その他のサーバー","aiSetupAgentChecking": "このコンピューターを確認しています…","aiSetupAgentInstalled": "インストール済み","aiSetupAgentNotFound": "見つかりません","aiSetupAgentMCP": "OpenPencil MCP サーバー","aiSetupAgentMCPInstall": "コーディングエージェントは OpenPencil の MCP サーバー経由でキャンバスを操作します。次のコマンドでインストールしてください:","aiSetupAgentPromptHint": "{agent} などのコーディングエージェントをすでに使っていますか?セットアップ用プロンプトをコピーして貼り付けると、OpenPencil に必要なものをインストールします。",+ "aiSetupAgentNeedsAdapter": "インストール済み・OpenPencil アダプターがありません",+ "aiSetupAgentInstallAdapter": "アダプターをインストール",+ "aiSetupAgentInstallMCP": "MCP サーバーをインストール",+ "aiSetupAgentUpdateMCP": "MCP サーバーを更新",+ "aiSetupAgentOutdated": "更新が必要",+ "aiSetupAgentInstalling": "インストールしています…",+ "aiSetupAgentGetCLI": "{agent} をインストール",+ "aiSetupAgentNeedsNpm": "インストールには Node.js に含まれる npm が必要です。Node.js をインストールしてから、もう一度確認してください。",+ "aiSetupAgentNeedsAdmin": "npm はグローバルパッケージを保護されたフォルダーに置くため、インストールには管理者権限が必要です。下のコマンドをターミナルで実行するか、エージェントにあなた専用のフォルダーを設定させてください。",+ "aiSetupAgentInstallFailed": "インストールが完了しませんでした。接続を確認するか、コマンドを自分で実行してください。",+ "aiSetupAgentMCPStartFailed": "MCP サーバーはインストール済みですが起動しませんでした。OpenPencil を再起動してから、もう一度確認してください。",+ "aiSetupAgentLookupFailed": "このコンピューターを確認できませんでした。もう一度お試しください。","aiSetupAgentCopyPrompt": "セットアップ用プロンプトをコピー","aiSetupAgentCheckAgain": "もう一度確認","aiSetupAgentInstallRuns": "インストールでは {command} を実行します。",@@ -356,20 +323,53 @@"piModelHint": "provider/model 形式の Pi モデル。空欄にすると Pi のデフォルトモデルを使います。","aiSetupPiSignIn": "プロバイダーにサインインするかデフォルトモデルを選ぶには、ターミナルで pi を実行して /login または /model と入力します。","aiSetupGetDesktop": "デスクトップアプリを入手",- "aiSetupAgentNeedsAdapter": "インストール済み・OpenPencil アダプターがありません",- "aiSetupAgentInstallAdapter": "アダプターをインストール",- "aiSetupAgentInstallMCP": "MCP サーバーをインストール",- "aiSetupAgentUpdateMCP": "MCP サーバーを更新",- "aiSetupAgentOutdated": "更新が必要",- "aiSetupAgentInstalling": "インストールしています…",- "aiSetupAgentGetCLI": "{agent} をインストール",- "aiSetupAgentNeedsNpm": "インストールには Node.js に含まれる npm が必要です。Node.js をインストールしてから、もう一度確認してください。",- "aiSetupAgentNeedsAdmin": "npm はグローバルパッケージを保護されたフォルダーに置くため、インストールには管理者権限が必要です。下のコマンドをターミナルで実行するか、エージェントにあなた専用のフォルダーを設定させてください。",- "aiSetupAgentInstallFailed": "インストールが完了しませんでした。接続を確認するか、コマンドを自分で実行してください。",- "aiSetupAgentMCPStartFailed": "MCP サーバーはインストール済みですが起動しませんでした。OpenPencil を再起動してから、もう一度確認してください。",- "aiSetupAgentLookupFailed": "このコンピューターを確認できませんでした。もう一度お試しください。",- "chatAgentWorkingOn": "{agent}が「{page}」で作業中",- "chatGoToPage": "ページへ移動",+ "aiSetupMeteredNote": "OpenRouter なら、1 つのアカウントと 1 つのキーで複数ベンダーのモデルを使えます。",+ "aiSetupSkillsTitle": "コーディングエージェントのスキル",+ "aiSetupSkillsDescription": "デザインチャットでは、コーディングエージェントがインストールしたスキルを使えます。多くは開発用のワークフローなので、デザインに役立つものだけを選んでください。あとから 設定 › スキル で変更できます。",+ "aiSetupReviewTitle": "設定を確認",+ "aiSetupAgentModel": "モデルはエージェントが選択",+ "aiSetupFinish": "設定を完了",+ "aiSetupSavedTitle": "AI の準備ができました",+ "aiSetupSavedDescription": "モデルと役割はいつでも設定で変更できます。",+ "aiSetupRun": "ガイド付き設定を開始",+ "aiSetupServerKeyHint": "サーバーがキーを確認しない場合は、任意の値を入力してください。",+ "aiSetupGapDesign": "選んだものではデザインの作成と編集ができません。",+ "aiSetupGapVision": "選んだものでは画像を確認できないため、ビジュアルレビューはオフのままになります。",+ "aiSetupGapContinue": "このまま続けて、あとから設定で追加することもできます。",+ "aiSetupGapAddOpenRouter": "OpenRouter を追加(従量課金)",+ "aiSetupGapRemoveOpenRouter": "OpenRouter を使わない",+ "aiSetupGapCoveredByOpenRouter": "ほかの選択で対応できない部分は OpenRouter が担当し、リクエストごとに課金されます。",+ "aiSetupServerVision": "このモデルは画像を読み取れます",+ "aiSetupSavedKeyHint": "保存済みのキーを使う場合は空欄のままにしてください。",+ "aiSetupAlreadyConnected": "選んだものはすべて接続済みです。",+ "aiSetupOpenRouterSignIn": "OpenRouter でサインイン",+ "aiSetupOpenRouterWaiting": "ブラウザで OpenRouter へのサインインを完了してください。",+ "aiSetupSignInReopen": "もう一度開く",+ "aiSetupOpenRouterOrKey": "または API キーを貼り付け",+ "aiSetupOpenRouterBlocked": "ブラウザがサインイン用のウィンドウをブロックしました。OpenPencil のポップアップを許可してから、もう一度お試しください。",+ "aiSetupSignInCancelled": "サインインはキャンセルされました。",+ "aiSetupSignInExpired": "サインインに時間がかかりすぎました。もう一度お試しください。",+ "aiSetupOpenRouterFailed": "OpenRouter にサインインできませんでした。もう一度試すか、API キーを貼り付けてください。",+ "aiSetupOpenRouterSignedInTitle": "OpenRouter にサインインしました",+ "aiSetupOpenRouterKeyLabel": "・キー「{label}」",+ "aiSetupOpenRouterVerifying": "OpenRouter のキーを確認しています…",+ "aiSetupOpenRouterNoCredits": "この OpenRouter アカウントにはまだクレジットがありません。推奨モデルなどの有料モデルを使うには、OpenRouter でクレジットを追加してください。",+ "aiSetupSignInChange": "別のアカウントを使う",+ "aiSetupSignOut": "サインアウト",+ "aiSetupAccessSubscriptions": "サブスクリプション",+ "aiSetupAccessChatGPT": "ChatGPT プランのモデルを OpenPencil のエージェントで使います。",+ "aiSetupChatGPTSignIn": "ChatGPT でサインイン",+ "aiSetupChatGPTWaiting": "ブラウザで ChatGPT へのサインインを完了してください。",+ "aiSetupChatGPTSignedInTitle": "ChatGPT にサインインしました",+ "aiSetupChatGPTFailed": "ChatGPT にサインインできませんでした。もう一度お試しください。",+ "aiSetupChatGPTPortInUse": "別のサインイン(`codex login` など)がポート 1455 を使用しています。完了するか閉じてから、もう一度お試しください。",+ "aiSetupChatGPTCallbackSignedIn": "ChatGPT にサインインしました。このタブを閉じて OpenPencil に戻ってください。",+ "aiSetupChatGPTCallbackCancelled": "ChatGPT へのサインインはキャンセルされました。このタブを閉じてください。",+ "aiSetupChatGPTCallbackStale": "このサインインリンクは以前の試行のものです。OpenPencil からやり直してください。",+ "aiSetupChatGPTUsage": "応答は ChatGPT プランの利用上限にカウントされます。",+ "aiSetupSavedSignInHint": "保存済みのサインインを使用します。",+ "aiSetupUseRecommended": "推奨の設定を使う",+ "aiSetupRolesDescription": "作業の種類ごとにモデルを選んでください。接続したものから推奨モデルを選んであります。ほかに設定した内容はそのまま残ります。","chatReferenceLayers": "レイヤー","chatReferencePages": "ページ","chatReferenceSkills": "スキル",@@ -417,6 +417,31 @@"skillWarningLongDescription": "説明が {max} 文字を超えています。","skillErrorNoFrontmatter": "SKILL.md が --- 行で囲まれた YAML フロントマターで始まっていません。","skillErrorInvalidFrontmatter": "SKILL.md のフロントマターが無効です: {detail}",+ "contextUsed": "コンテキスト:{percent}% 使用",+ "contextTitle": "コンテキスト",+ "contextTokens": "{total} トークン中 {used}",+ "contextCompactsAt": "返信の余地を残し、{tokens} トークンで自動的に圧縮します。",+ "contextCompactsOff": "自動圧縮はオフです。",+ "contextNearlyFull": "コンテキスト {percent}% 使用",+ "compact": "圧縮",+ "compactCommand": "ここまでの会話を要約します。後に続く文で残す内容を指定します",+ "compactAutomatically": "自動的に圧縮",+ "compactAutomaticallyHint": "コンテキストウィンドウがいっぱいになると、古いメッセージを要約します。",+ "compacting": "会話を圧縮しています…",+ "compactionFailed": "会話を圧縮できませんでした。何も変更されていません。",+ "compactAndRetry": "圧縮して再試行",+ "chatContextLimit": "会話がモデルの読める長さを超えています。",+ "conversationCompacted": "会話を圧縮しました",+ "compactionKeepsMessages": "モデルは上のメッセージの代わりにこの要約を受け取ります。メッセージは引き続き表示されます。",+ "agentCompactionKeepsMessages": "エージェントは上のメッセージを自身で要約し、その要約をもとに作業します。メッセージは引き続き表示されます。",+ "compactionTokens": "{before} → {after} トークン",+ "tokenUsage": "トークン使用量",+ "tokenUsageHint": "各返信のトークンを表示します。",+ "tokenUsageHover": "ホバー時",+ "tokenUsageAlways": "常に",+ "tokenUsageHidden": "非表示",+ "replyTokens": "入力 {input} · 出力 {output}",+ "replyCachedTokens": "キャッシュ {cached}","skillErrorNoDescription": "SKILL.md のフロントマターに説明がありません。","skillErrorNoName": "SKILL.md のフロントマターに名前がありません。"}diff --git a/packages/vue/src/i18n/locales/pl/ai.json b/packages/vue/src/i18n/locales/pl/ai.jsonindex 292535b40..b29bf782c 100644--- a/packages/vue/src/i18n/locales/pl/ai.json+++ b/packages/vue/src/i18n/locales/pl/ai.json@@ -1,7 +1,59 @@{+ "jumpToLatest": "Przejdź do najnowszej wiadomości",+ "chatSettings": "Czat",+ "notificationsHint": "Tylko gdy OpenPencil działa w tle lub pokazuje inny dokument.",+ "notifyNeedsInput": "Agent potrzebuje ciebie",+ "notifyNeedsInputHint": "Prośba o zgodę od kilku sekund czeka na odpowiedź.",+ "notifyFinished": "Odpowiedź jest gotowa",+ "notifyFailed": "Odpowiedź się nie powiodła",+ "notificationsAllow": "Zezwól na powiadomienia",+ "notificationsAllowHint": "Przeglądarka raz zapyta, czy OpenPencil może pokazywać powiadomienia.",+ "notificationsBlocked": "Powiadomienia są zablokowane dla tej witryny. Zezwól na nie w ustawieniach witryny w przeglądarce.",+ "notificationsUnsupported": "Ta przeglądarka nie może pokazywać powiadomień.",+ "notificationsSystemHint": "Jeśli żadne się nie pojawiają, zezwól OpenPencil w systemowych ustawieniach powiadomień.",+ "notifyTitle": "{agent} · {document}",+ "notifyPermission": "Prosi o zgodę.",+ "notifyPermissionAction": "Prosi o zgodę: {action}",+ "notifyReplyFinished": "Odpowiedź AI jest gotowa.",+ "notifyReplyFailed": "Odpowiedź AI zatrzymała się z błędem.","maxAgentSteps": "Maksymalna liczba kroków na wiadomość",+ "maxAgentStepsCustom": "Własna wartość…","maxAgentStepsHint": "Tylko dla wbudowanej AI; ACP i Pi zarządzają własnymi limitami. Zapis po naciśnięciu Enter lub opuszczeniu pola, obowiązuje od następnej wiadomości. Wyższe limity mogą zwiększyć koszt.","maxAgentStepsRange": "Wpisz liczbę całkowitą od {min} do {max}.",+ "reasoningDisplay": "Wyświetlanie rozumowania",+ "reasoningCollapsed": "Domyślnie zwinięte",+ "reasoningWhileThinking": "Rozwijaj podczas rozumowania",+ "reasoningExpanded": "Domyślnie rozwinięte",+ "continueChat": "Kontynuuj",+ "searchChats": "Szukaj rozmów…",+ "chatScope": "Zakres rozmów",+ "thisDocument": "Ten dokument",+ "allDocuments": "Wszystkie dokumenty",+ "noChatsFound": "Nie znaleziono rozmów.",+ "chatActions": "Działania rozmowy",+ "chatHistory": "Historia czatów",+ "newChat": "Nowy czat",+ "followAgents": "Śledź agentów podczas pracy",+ "stopFollowingAgents": "Przestań śledzić agentów podczas pracy",+ "allChats": "Wszystkie czaty",+ "renameChat": "Zmień nazwę",+ "saveChatTrace": "Zapisz ślad…",+ "chatTraceFailed": "Nie można zapisać śladu czatu.",+ "deleteChat": "Usuń",+ "chatTitle": "Tytuł czatu",+ "saveChatTitle": "Zapisz",+ "cancelChatAction": "Anuluj",+ "deleteChatConfirmation": "Trwale usunąć ten czat?",+ "deleteChatDescription": "„{title}” i jej wiadomości zostaną usunięte. Tej operacji nie można cofnąć.",+ "chatDocumentHint": "Otwórz dokument czatu, aby kontynuować.",+ "chatReadOnly": "Ten czat należy do innego dokumentu. Otwórz go, aby kontynuować.",+ "chatAgentReadOnly": "Rozmowa z agentem została zapisana, ale nie można tu jeszcze wznowić jego sesji. Rozpocznij nowy czat.",+ "chatStorageFailed": "Nie udało się zapisać historii. Nie zamykaj tego okna i spróbuj ponownie.",+ "chatHistoryFailed": "Nie udało się zaktualizować historii. Spróbuj ponownie.",+ "chatInterrupted": "Ta odpowiedź została przerwana.",+ "chatAgentWorkingOn": "{agent} pracuje nad „{page}”",+ "chatGoToPage": "Przejdź do strony",+ "connectProvider": "Połącz dostawcę AI, aby rozpocząć czat.","connectionTestSuccess": "Połączono pomyślnie. Model jest dostępny.","connectionTestMissingAPIKey": "Wprowadź klucz API przed rozpoczęciem testu.","connectionTestMissingSignIn": "Zaloguj się przed rozpoczęciem testu.",@@ -17,6 +69,7 @@"connectionTestBrowserNetworkFailed": "Nie udało się połączyć z tym punktem końcowym z przeglądarki. Spróbuj użyć aplikacji komputerowej lub punktu końcowego z włączonym CORS.","connectionTestNetworkFailed": "Nie udało się połączyć z punktem końcowym. Sprawdź adres URL i połączenie sieciowe.","connectionTestUnknownFailed": "Test połączenia nie powiódł się. Sprawdź ustawienia dostawcy i spróbuj ponownie.",+ "getProviderAPIKey": "Pobierz klucz API {provider} →","oneKeyManyModels": "Jeden klucz do ponad 100 modeli od wszystkich dostawców.","describeChange": "Opisz zmianę…","describeCreateOrChange": "Opisz, co chcesz utworzyć lub zmienić.",@@ -80,8 +133,10 @@"permissionRequest": "{tool} prosi o uprawnienie.","baseURLPlaceholder": "Base URL (np. http://localhost:11434/v1)","modelIDPlaceholder": "Model ID (np. llama-3.3-70b)",+ "provider": "Dostawca AI","providerSettings": "Ustawienia dostawcy","openProviderSettings": "Otwórz ustawienia dostawcy",+ "modelsTitle": "Modele","modelsDescription": "Skonfiguruj modele wielokrotnego użytku i połączenia z dostawcami.","addModel": "Dodaj model","editModel": "Edytuj model",@@ -136,6 +191,12 @@"apiType": "Typ API","baseURL": "Bazowy URL","modelID": "ID modelu",+ "selectModel": "Wybierz model",+ "searchModels": "Szukaj modeli…",+ "recommendedModels": "Polecane",+ "latestModels": "Najnowsze",+ "allModels": "Wszystkie modele",+ "latest": "Nowy","customModelID": "Identyfikator modelu niestandardowego","customModel": "Model niestandardowy…","customModelGroup": "Własny model",@@ -146,9 +207,12 @@"chatSignInExpired": "Twoje logowanie wygasło. Zaloguj się ponownie w Ustawieniach.","chatPlanForbidden": "Twój plan nie pozwala używać wybranego modelu. Wybierz inny model w Ustawieniach.","chatForbidden": "Ten klucz API nie może używać wybranego modelu. Sprawdź dostęp do modelu.",+ "chatInsufficientCredit": "Konto dostawcy nie ma wystarczających środków lub limitu. Doładuj je i spróbuj ponownie.",+ "chatOutputLimit": "Model wyczerpał limit tokenów wyjściowych podczas rozumowania. Zwiększ maksymalną liczbę tokenów wyjściowych lub zmniejsz poziom rozumowania.","chatModelNotFound": "Wybrany model jest niedostępny. Wybierz inny model w Ustawieniach.","chatNetworkFailed": "OpenPencil nie mógł połączyć się z dostawcą. Sprawdź połączenie i endpoint.","chatRateLimited": "Osiągnięto limit żądań dostawcy. Poczekaj chwilę i spróbuj ponownie.",+ "chatRequestFailed": "Żądanie do modelu nie powiodło się. Sprawdź ustawienia dostawcy i spróbuj ponownie.","openProviderSettingsAction": "Otwórz ustawienia","cloudWorkspace": "Obszar roboczy","cloudWorkspaceHint": "Obszar roboczy, którego plan opłaca te żądania.",@@ -164,9 +228,6 @@"cloudCreditsRenew": "Odnawia się {date}","manageCloudPlanAction": "Zarządzaj planem","chatCloudUnavailable": "AI OpenPencil Cloud jest niedostępne. Zaloguj się do OpenPencil Cloud i wybierz obszar roboczy w ustawieniach.",- "chatInsufficientCredit": "Konto dostawcy nie ma wystarczających środków lub limitu. Doładuj je i spróbuj ponownie.",- "chatOutputLimit": "Model wyczerpał limit tokenów wyjściowych podczas rozumowania. Zwiększ maksymalną liczbę tokenów wyjściowych lub zmniejsz poziom rozumowania.",- "chatRequestFailed": "Żądanie do modelu nie powiodło się. Sprawdź ustawienia dostawcy i spróbuj ponownie.","visionModelUnavailable": "Przed dołączeniem obrazów wybierz model Vision w Ustawieniach.","chatPiCompanionMissing": "Pi potrzebuje programu towarzyszącego Harness. Uruchom konfigurację z przewodnikiem, aby go zainstalować.","chatPiCompanionOutdated": "Program towarzyszący Harness nie pasuje do tej wersji OpenPencil. Uruchom konfigurację z przewodnikiem, aby go zaktualizować.",@@ -175,65 +236,6 @@"chatPiModel": "Pi nie ma modelu. Uruchom pi w terminalu i wpisz /model albo wybierz model w Ustawieniach.","completions": "Completions","responses": "Responses",- "connectProvider": "Połącz dostawcę AI, aby rozpocząć czat.",- "getProviderAPIKey": "Pobierz klucz API {provider} →",- "provider": "Dostawca AI",- "modelsTitle": "Modele",- "selectModel": "Wybierz model",- "searchModels": "Szukaj modeli…",- "recommendedModels": "Polecane",- "latestModels": "Najnowsze",- "allModels": "Wszystkie modele",- "latest": "Nowy",- "chatHistory": "Historia czatów",- "newChat": "Nowy czat",- "followAgents": "Śledź agentów podczas pracy",- "stopFollowingAgents": "Przestań śledzić agentów podczas pracy",- "allChats": "Wszystkie czaty",- "renameChat": "Zmień nazwę",- "saveChatTrace": "Zapisz ślad…",- "chatTraceFailed": "Nie można zapisać śladu czatu.",- "deleteChat": "Usuń",- "chatTitle": "Tytuł czatu",- "saveChatTitle": "Zapisz",- "cancelChatAction": "Anuluj",- "deleteChatConfirmation": "Trwale usunąć ten czat?",- "deleteChatDescription": "„{title}” i jej wiadomości zostaną usunięte. Tej operacji nie można cofnąć.",- "chatDocumentHint": "Otwórz dokument czatu, aby kontynuować.",- "chatReadOnly": "Ten czat należy do innego dokumentu. Otwórz go, aby kontynuować.",- "chatAgentReadOnly": "Rozmowa z agentem została zapisana, ale nie można tu jeszcze wznowić jego sesji. Rozpocznij nowy czat.",- "chatStorageFailed": "Nie udało się zapisać historii. Nie zamykaj tego okna i spróbuj ponownie.",- "chatHistoryFailed": "Nie udało się zaktualizować historii. Spróbuj ponownie.",- "chatInterrupted": "Ta odpowiedź została przerwana.",- "searchChats": "Szukaj rozmów…",- "chatScope": "Zakres rozmów",- "thisDocument": "Ten dokument",- "allDocuments": "Wszystkie dokumenty",- "noChatsFound": "Nie znaleziono rozmów.",- "chatActions": "Działania rozmowy",- "continueChat": "Kontynuuj",- "chatSettings": "Czat",- "notificationsHint": "Tylko gdy OpenPencil działa w tle lub pokazuje inny dokument.",- "notifyNeedsInput": "Agent potrzebuje ciebie",- "notifyNeedsInputHint": "Prośba o zgodę od kilku sekund czeka na odpowiedź.",- "notifyFinished": "Odpowiedź jest gotowa",- "notifyFailed": "Odpowiedź się nie powiodła",- "notificationsAllow": "Zezwól na powiadomienia",- "notificationsAllowHint": "Przeglądarka raz zapyta, czy OpenPencil może pokazywać powiadomienia.",- "notificationsBlocked": "Powiadomienia są zablokowane dla tej witryny. Zezwól na nie w ustawieniach witryny w przeglądarce.",- "notificationsUnsupported": "Ta przeglądarka nie może pokazywać powiadomień.",- "notificationsSystemHint": "Jeśli żadne się nie pojawiają, zezwól OpenPencil w systemowych ustawieniach powiadomień.",- "notifyTitle": "{agent} · {document}",- "notifyPermission": "Prosi o zgodę.",- "notifyPermissionAction": "Prosi o zgodę: {action}",- "notifyReplyFinished": "Odpowiedź AI jest gotowa.",- "notifyReplyFailed": "Odpowiedź AI zatrzymała się z błędem.",- "reasoningDisplay": "Wyświetlanie rozumowania",- "reasoningCollapsed": "Domyślnie zwinięte",- "reasoningWhileThinking": "Rozwijaj podczas rozumowania",- "reasoningExpanded": "Domyślnie rozwinięte",- "jumpToLatest": "Przejdź do najnowszej wiadomości",- "maxAgentStepsCustom": "Własna wartość…","aiSetupWelcomeTitle": "Witamy w OpenPencil","aiSetupWelcomeDescription": "Twórz i edytuj projekty na otwartym płótnie. Importuj pliki Figma i dostosuj je do siebie.","aiSetupWelcomeAITitle": "Projektuj z AI",@@ -259,69 +261,34 @@"modelProviderSetUp": "Skonfigurowano","aiSetupAccessAPI": "Konta API","aiSetupAccessServer": "Model lokalny lub serwer firmowy",+ "aiSetupAccessMore": "Więcej dostawców",+ "providerGroupAgents": "Twoi agenci",+ "providerGroupProviders": "Dostawcy",+ "aiSetupServerOther": "Inny serwer","aiSetupAccessServerDescription": "Dowolny serwer zgodny z API OpenAI, np. Ollama lub LM Studio.","aiSetupConnectTitle": "Połącz AI","aiSetupNothingDescription": "Wróć, aby wybrać inny dostęp, albo skonfiguruj AI w ustawieniach zaawansowanych.","aiSetupAgentDescription": "OpenPencil uruchamia {agent}, gdy wyślesz wiadomość, z kontem, na którym {agent} jest zalogowany.","aiSetupAgentInstall": "Jeśli nie jest jeszcze zainstalowany, uruchom:","aiSetupAgentInstallSupported": "Zainstaluj obsługiwany adapter:",- "aiSetupMeteredNote": "OpenRouter daje dostęp do modeli wielu dostawców z jednym kontem i jednym kluczem.",- "aiSetupSkillsTitle": "Umiejętności twoich agentów programistycznych",- "aiSetupSkillsDescription": "Czat projektowy może używać umiejętności zainstalowanych przez twoich agentów programistycznych. Większość to procesy programistyczne, więc wybierz tylko te, które pomagają w projektowaniu; zmienisz je później w Ustawienia › Umiejętności.",- "aiSetupReviewTitle": "Sprawdź konfigurację",- "aiSetupAgentModel": "Model wybrany przez agenta",- "aiSetupFinish": "Zakończ konfigurację",- "aiSetupSavedTitle": "AI jest gotowe",- "aiSetupSavedDescription": "Modele i role możesz zmienić w dowolnej chwili w ustawieniach.",- "aiSetupRun": "Uruchom konfigurację z przewodnikiem",- "aiSetupServerKeyHint": "Jeśli serwer nie sprawdza kluczy, wpisz dowolną wartość.",- "aiSetupAlreadyConnected": "Wszystko, co wybrano, jest już połączone.",- "aiSetupOpenRouterSignIn": "Zaloguj się przez OpenRouter",- "aiSetupOpenRouterWaiting": "Dokończ logowanie do OpenRouter w przeglądarce.",- "aiSetupSignInReopen": "Otwórz ponownie",- "aiSetupOpenRouterOrKey": "Lub wklej klucz API",- "aiSetupOpenRouterBlocked": "Przeglądarka zablokowała okno logowania. Zezwól na wyskakujące okna dla OpenPencil i spróbuj ponownie.",- "aiSetupSignInCancelled": "Logowanie zostało anulowane.",- "aiSetupSignInExpired": "Logowanie trwało zbyt długo. Spróbuj ponownie.",- "aiSetupOpenRouterFailed": "Nie udało się zalogować do OpenRouter. Spróbuj ponownie lub wklej klucz API.",- "aiSetupOpenRouterSignedInTitle": "Zalogowano do OpenRouter",- "aiSetupSavedKeyHint": "Pozostaw puste, aby zachować zapisany klucz.",- "aiSetupOpenRouterKeyLabel": "· klucz „{label}”",- "aiSetupOpenRouterVerifying": "Sprawdzanie klucza OpenRouter…",- "aiSetupOpenRouterNoCredits": "To konto OpenRouter nie ma jeszcze środków. Doładuj je w OpenRouter, aby korzystać z płatnych modeli, takich jak polecany.",- "aiSetupSignInChange": "Użyj innego konta",- "aiSetupSignOut": "Wyloguj się",- "aiSetupAccessSubscriptions": "Subskrypcje",- "aiSetupAccessChatGPT": "Używaj modeli ze swojego planu ChatGPT we własnym agencie OpenPencil.",- "aiSetupChatGPTSignIn": "Zaloguj się przez ChatGPT",- "aiSetupChatGPTWaiting": "Dokończ logowanie do ChatGPT w przeglądarce.",- "aiSetupChatGPTSignedInTitle": "Zalogowano do ChatGPT",- "aiSetupChatGPTFailed": "Nie udało się zalogować do ChatGPT. Spróbuj ponownie.",- "aiSetupChatGPTPortInUse": "Inne logowanie, np. `codex login`, używa portu 1455. Dokończ je lub zamknij i spróbuj ponownie.",- "aiSetupChatGPTCallbackSignedIn": "Zalogowano do ChatGPT. Możesz zamknąć tę kartę i wrócić do OpenPencil.",- "aiSetupChatGPTCallbackCancelled": "Logowanie do ChatGPT zostało anulowane. Możesz zamknąć tę kartę.",- "aiSetupChatGPTCallbackStale": "Ten link logowania pochodzi z wcześniejszej próby. Zacznij od nowa w OpenPencil.",- "aiSetupChatGPTUsage": "Odpowiedzi wliczają się do limitów użycia twojego planu ChatGPT.",- "aiSetupSavedSignInHint": "Zostanie użyte zapisane logowanie.",- "aiSetupUseRecommended": "Użyj polecanej konfiguracji",- "aiSetupRolesDescription": "Wybierz model dla każdego rodzaju pracy. Spośród połączonych usług wybraliśmy polecane; pozostała konfiguracja się nie zmieni.",- "aiSetupGapDesign": "Żadna z wybranych opcji nie tworzy ani nie edytuje projektów.",- "aiSetupGapVision": "Żadna z wybranych opcji nie analizuje obrazów, więc przegląd wizualny pozostanie wyłączony.",- "aiSetupGapContinue": "Możesz kontynuować bez tego i dodać to później w ustawieniach.",- "aiSetupGapAddOpenRouter": "Dodaj OpenRouter (płatność za użycie)",- "aiSetupGapRemoveOpenRouter": "Nie używaj OpenRouter",- "aiSetupServerVision": "Ten model potrafi odczytywać obrazy",- "aiSetupGapCoveredByOpenRouter": "OpenRouter obsłuży to, czego nie obejmują pozostałe wybory, z opłatą za każde zapytanie.",- "aiSetupAccessMore": "Więcej dostawców",- "providerGroupAgents": "Twoi agenci",- "providerGroupProviders": "Dostawcy",- "aiSetupServerOther": "Inny serwer","aiSetupAgentChecking": "Sprawdzanie tego komputera…","aiSetupAgentInstalled": "zainstalowany","aiSetupAgentNotFound": "nie znaleziono","aiSetupAgentMCP": "Serwer MCP OpenPencil","aiSetupAgentMCPInstall": "Agenci programistyczni korzystają z płótna przez serwer MCP OpenPencil. Zainstaluj go poleceniem:","aiSetupAgentPromptHint": "Korzystasz już z {agent} lub innego agenta programistycznego? Skopiuj prompt konfiguracji i wklej go tam — zainstaluje to, czego potrzebuje OpenPencil.",+ "aiSetupAgentNeedsAdapter": "zainstalowany · brak adaptera OpenPencil",+ "aiSetupAgentInstallAdapter": "Zainstaluj adapter",+ "aiSetupAgentInstallMCP": "Zainstaluj serwer MCP",+ "aiSetupAgentUpdateMCP": "Zaktualizuj serwer MCP",+ "aiSetupAgentOutdated": "wymaga aktualizacji",+ "aiSetupAgentInstalling": "Instalowanie…",+ "aiSetupAgentGetCLI": "Zainstaluj {agent}",+ "aiSetupAgentNeedsNpm": "Instalacja wymaga npm, który jest częścią Node.js. Zainstaluj Node.js i sprawdź ponownie.",+ "aiSetupAgentNeedsAdmin": "Instalacja wymaga uprawnień administratora, ponieważ npm trzyma pakiety globalne w chronionym folderze. Uruchom poniższe polecenie w terminalu albo pozwól agentowi skonfigurować folder należący do Ciebie.",+ "aiSetupAgentInstallFailed": "Instalacja nie została ukończona. Sprawdź połączenie lub uruchom polecenie samodzielnie.",+ "aiSetupAgentMCPStartFailed": "Serwer MCP jest zainstalowany, ale się nie uruchomił. Uruchom ponownie OpenPencil i sprawdź jeszcze raz.",+ "aiSetupAgentLookupFailed": "Nie udało się sprawdzić tego komputera. Spróbuj ponownie.","aiSetupAgentCopyPrompt": "Kopiuj prompt konfiguracji","aiSetupAgentCheckAgain": "Sprawdź ponownie","aiSetupAgentInstallRuns": "Instalacja uruchamia {command}.",@@ -356,20 +323,53 @@"piModelHint": "Model Pi, np. provider/model. Pozostaw puste, aby użyć domyślnego modelu Pi.","aiSetupPiSignIn": "Aby zalogować się do dostawcy lub wybrać domyślny model, uruchom pi w terminalu i wpisz /login lub /model.","aiSetupGetDesktop": "Pobierz aplikację na komputer",- "aiSetupAgentNeedsAdapter": "zainstalowany · brak adaptera OpenPencil",- "aiSetupAgentInstallAdapter": "Zainstaluj adapter",- "aiSetupAgentInstallMCP": "Zainstaluj serwer MCP",- "aiSetupAgentUpdateMCP": "Zaktualizuj serwer MCP",- "aiSetupAgentOutdated": "wymaga aktualizacji",- "aiSetupAgentInstalling": "Instalowanie…",- "aiSetupAgentGetCLI": "Zainstaluj {agent}",- "aiSetupAgentNeedsNpm": "Instalacja wymaga npm, który jest częścią Node.js. Zainstaluj Node.js i sprawdź ponownie.",- "aiSetupAgentNeedsAdmin": "Instalacja wymaga uprawnień administratora, ponieważ npm trzyma pakiety globalne w chronionym folderze. Uruchom poniższe polecenie w terminalu albo pozwól agentowi skonfigurować folder należący do Ciebie.",- "aiSetupAgentInstallFailed": "Instalacja nie została ukończona. Sprawdź połączenie lub uruchom polecenie samodzielnie.",- "aiSetupAgentMCPStartFailed": "Serwer MCP jest zainstalowany, ale się nie uruchomił. Uruchom ponownie OpenPencil i sprawdź jeszcze raz.",- "aiSetupAgentLookupFailed": "Nie udało się sprawdzić tego komputera. Spróbuj ponownie.",- "chatAgentWorkingOn": "{agent} pracuje nad „{page}”",- "chatGoToPage": "Przejdź do strony",+ "aiSetupMeteredNote": "OpenRouter daje dostęp do modeli wielu dostawców z jednym kontem i jednym kluczem.",+ "aiSetupSkillsTitle": "Umiejętności twoich agentów programistycznych",+ "aiSetupSkillsDescription": "Czat projektowy może używać umiejętności zainstalowanych przez twoich agentów programistycznych. Większość to procesy programistyczne, więc wybierz tylko te, które pomagają w projektowaniu; zmienisz je później w Ustawienia › Umiejętności.",+ "aiSetupReviewTitle": "Sprawdź konfigurację",+ "aiSetupAgentModel": "Model wybrany przez agenta",+ "aiSetupFinish": "Zakończ konfigurację",+ "aiSetupSavedTitle": "AI jest gotowe",+ "aiSetupSavedDescription": "Modele i role możesz zmienić w dowolnej chwili w ustawieniach.",+ "aiSetupRun": "Uruchom konfigurację z przewodnikiem",+ "aiSetupServerKeyHint": "Jeśli serwer nie sprawdza kluczy, wpisz dowolną wartość.",+ "aiSetupGapDesign": "Żadna z wybranych opcji nie tworzy ani nie edytuje projektów.",+ "aiSetupGapVision": "Żadna z wybranych opcji nie analizuje obrazów, więc przegląd wizualny pozostanie wyłączony.",+ "aiSetupGapContinue": "Możesz kontynuować bez tego i dodać to później w ustawieniach.",+ "aiSetupGapAddOpenRouter": "Dodaj OpenRouter (płatność za użycie)",+ "aiSetupGapRemoveOpenRouter": "Nie używaj OpenRouter",+ "aiSetupGapCoveredByOpenRouter": "OpenRouter obsłuży to, czego nie obejmują pozostałe wybory, z opłatą za każde zapytanie.",+ "aiSetupServerVision": "Ten model potrafi odczytywać obrazy",+ "aiSetupSavedKeyHint": "Pozostaw puste, aby zachować zapisany klucz.",+ "aiSetupAlreadyConnected": "Wszystko, co wybrano, jest już połączone.",+ "aiSetupOpenRouterSignIn": "Zaloguj się przez OpenRouter",+ "aiSetupOpenRouterWaiting": "Dokończ logowanie do OpenRouter w przeglądarce.",+ "aiSetupSignInReopen": "Otwórz ponownie",+ "aiSetupOpenRouterOrKey": "Lub wklej klucz API",+ "aiSetupOpenRouterBlocked": "Przeglądarka zablokowała okno logowania. Zezwól na wyskakujące okna dla OpenPencil i spróbuj ponownie.",+ "aiSetupSignInCancelled": "Logowanie zostało anulowane.",+ "aiSetupSignInExpired": "Logowanie trwało zbyt długo. Spróbuj ponownie.",+ "aiSetupOpenRouterFailed": "Nie udało się zalogować do OpenRouter. Spróbuj ponownie lub wklej klucz API.",+ "aiSetupOpenRouterSignedInTitle": "Zalogowano do OpenRouter",+ "aiSetupOpenRouterKeyLabel": "· klucz „{label}”",+ "aiSetupOpenRouterVerifying": "Sprawdzanie klucza OpenRouter…",+ "aiSetupOpenRouterNoCredits": "To konto OpenRouter nie ma jeszcze środków. Doładuj je w OpenRouter, aby korzystać z płatnych modeli, takich jak polecany.",+ "aiSetupSignInChange": "Użyj innego konta",+ "aiSetupSignOut": "Wyloguj się",+ "aiSetupAccessSubscriptions": "Subskrypcje",+ "aiSetupAccessChatGPT": "Używaj modeli ze swojego planu ChatGPT we własnym agencie OpenPencil.",+ "aiSetupChatGPTSignIn": "Zaloguj się przez ChatGPT",+ "aiSetupChatGPTWaiting": "Dokończ logowanie do ChatGPT w przeglądarce.",+ "aiSetupChatGPTSignedInTitle": "Zalogowano do ChatGPT",+ "aiSetupChatGPTFailed": "Nie udało się zalogować do ChatGPT. Spróbuj ponownie.",+ "aiSetupChatGPTPortInUse": "Inne logowanie, np. `codex login`, używa portu 1455. Dokończ je lub zamknij i spróbuj ponownie.",+ "aiSetupChatGPTCallbackSignedIn": "Zalogowano do ChatGPT. Możesz zamknąć tę kartę i wrócić do OpenPencil.",+ "aiSetupChatGPTCallbackCancelled": "Logowanie do ChatGPT zostało anulowane. Możesz zamknąć tę kartę.",+ "aiSetupChatGPTCallbackStale": "Ten link logowania pochodzi z wcześniejszej próby. Zacznij od nowa w OpenPencil.",+ "aiSetupChatGPTUsage": "Odpowiedzi wliczają się do limitów użycia twojego planu ChatGPT.",+ "aiSetupSavedSignInHint": "Zostanie użyte zapisane logowanie.",+ "aiSetupUseRecommended": "Użyj polecanej konfiguracji",+ "aiSetupRolesDescription": "Wybierz model dla każdego rodzaju pracy. Spośród połączonych usług wybraliśmy polecane; pozostała konfiguracja się nie zmieni.","chatReferenceLayers": "Warstwy","chatReferencePages": "Strony","chatReferenceSkills": "Umiejętności",@@ -417,6 +417,31 @@"skillWarningLongDescription": "Opis jest dłuższy niż {max} znaki.","skillErrorNoFrontmatter": "SKILL.md nie zaczyna się od frontmattera YAML między wierszami ---.","skillErrorInvalidFrontmatter": "Frontmatter pliku SKILL.md jest nieprawidłowy: {detail}",+ "contextUsed": "Kontekst: {percent}% użyte",+ "contextTitle": "Kontekst",+ "contextTokens": "{used} z {total} tokenów",+ "contextCompactsAt": "Kompaktowanie automatycznie przy {tokens} tokenach, z miejscem na odpowiedź.",+ "contextCompactsOff": "Automatyczne kompaktowanie jest wyłączone.",+ "contextNearlyFull": "Kontekst {percent}% użyte",+ "compact": "Kompaktuj",+ "compactCommand": "Streść dotychczasową rozmowę; tekst po poleceniu mówi, co zachować",+ "compactAutomatically": "Kompaktuj automatycznie",+ "compactAutomaticallyHint": "Streszcza starsze wiadomości, gdy okno kontekstu się zapełnia.",+ "compacting": "Kompaktowanie rozmowy…",+ "compactionFailed": "Nie udało się skompaktować rozmowy. Nic nie zostało zmienione.",+ "compactAndRetry": "Kompaktuj i ponów",+ "chatContextLimit": "Rozmowa jest dłuższa, niż model może przeczytać.",+ "conversationCompacted": "Rozmowa skompaktowana",+ "compactionKeepsMessages": "Model dostaje teraz to streszczenie zamiast wiadomości powyżej; nadal je widzisz.",+ "agentCompactionKeepsMessages": "Agent pracuje teraz na własnym streszczeniu wiadomości powyżej; nadal je widzisz.",+ "compactionTokens": "{before} → {after} tokenów",+ "tokenUsage": "Użycie tokenów",+ "tokenUsageHint": "Pokazuje tokeny każdej odpowiedzi.",+ "tokenUsageHover": "Po najechaniu",+ "tokenUsageAlways": "Zawsze",+ "tokenUsageHidden": "Ukryte",+ "replyTokens": "{input} wej. · {output} wyj.",+ "replyCachedTokens": "{cached} w pamięci podręcznej","skillErrorNoDescription": "Frontmatter pliku SKILL.md nie ma opisu.","skillErrorNoName": "Frontmatter pliku SKILL.md nie ma nazwy."}diff --git a/packages/vue/src/i18n/locales/ru/ai.json b/packages/vue/src/i18n/locales/ru/ai.jsonindex a41f6b2f5..1c62a8d4a 100644--- a/packages/vue/src/i18n/locales/ru/ai.json+++ b/packages/vue/src/i18n/locales/ru/ai.json@@ -1,7 +1,59 @@{+ "jumpToLatest": "К последнему сообщению",+ "chatSettings": "Чат",+ "notificationsHint": "Только когда OpenPencil в фоне или показывает другой документ.",+ "notifyNeedsInput": "Агенту нужен ваш ответ",+ "notifyNeedsInputHint": "Запрос разрешения несколько секунд ждёт ответа.",+ "notifyFinished": "Ответ готов",+ "notifyFailed": "Ответ завершился ошибкой",+ "notificationsAllow": "Разрешить уведомления",+ "notificationsAllowHint": "Браузер один раз спросит, может ли OpenPencil показывать уведомления.",+ "notificationsBlocked": "Уведомления для этого сайта заблокированы. Разрешите их в настройках сайта в браузере.",+ "notificationsUnsupported": "Этот браузер не умеет показывать уведомления.",+ "notificationsSystemHint": "Если уведомления не появляются, разрешите их для OpenPencil в системных настройках уведомлений.",+ "notifyTitle": "{agent} · {document}",+ "notifyPermission": "Просит разрешения.",+ "notifyPermissionAction": "Просит разрешения: {action}",+ "notifyReplyFinished": "Ответ ИИ готов.",+ "notifyReplyFailed": "Ответ ИИ остановился с ошибкой.","maxAgentSteps": "Максимум шагов на сообщение",+ "maxAgentStepsCustom": "Своё значение…","maxAgentStepsHint": "Только для встроенного ИИ; ACP и Pi управляют своими лимитами. Сохраняется по Enter или при выходе из поля и применяется со следующего сообщения. Больший лимит может увеличить расходы.","maxAgentStepsRange": "Введите целое число от {min} до {max}.",+ "reasoningDisplay": "Отображение рассуждений",+ "reasoningCollapsed": "Свёрнуто по умолчанию",+ "reasoningWhileThinking": "Разворачивать во время размышлений",+ "reasoningExpanded": "Развёрнуто по умолчанию",+ "continueChat": "Продолжить",+ "searchChats": "Поиск по чатам…",+ "chatScope": "Область поиска чатов",+ "thisDocument": "Этот документ",+ "allDocuments": "Все документы",+ "noChatsFound": "Чаты не найдены.",+ "chatActions": "Действия с чатом",+ "chatHistory": "История чатов",+ "newChat": "Новый чат",+ "followAgents": "Следовать за агентами во время работы",+ "stopFollowingAgents": "Не следовать за агентами во время работы",+ "allChats": "Все чаты",+ "renameChat": "Переименовать",+ "saveChatTrace": "Сохранить трассировку…",+ "chatTraceFailed": "Не удалось сохранить трассировку чата.",+ "deleteChat": "Удалить",+ "chatTitle": "Название чата",+ "saveChatTitle": "Сохранить",+ "cancelChatAction": "Отмена",+ "deleteChatConfirmation": "Удалить этот чат навсегда?",+ "deleteChatDescription": "«{title}» и её сообщения будут удалены. Это действие нельзя отменить.",+ "chatDocumentHint": "Откройте документ чата, чтобы продолжить.",+ "chatReadOnly": "Этот чат относится к другому документу. Откройте его, чтобы продолжить.",+ "chatAgentReadOnly": "Переписка с агентом сохранена, но восстановление его сессии пока недоступно. Начните новый чат.",+ "chatStorageFailed": "Не удалось сохранить историю чата. Не закрывайте окно и попробуйте ещё раз.",+ "chatHistoryFailed": "Не удалось обновить историю чатов. Попробуйте ещё раз.",+ "chatInterrupted": "Этот ответ был прерван.",+ "chatAgentWorkingOn": "{agent} работает над «{page}»",+ "chatGoToPage": "Перейти к странице",+ "connectProvider": "Подключите AI-провайдера, чтобы начать чат.","connectionTestSuccess": "Подключение установлено. Модель доступна.","connectionTestMissingAPIKey": "Введите API-ключ перед проверкой.","connectionTestMissingSignIn": "Войдите перед проверкой.",@@ -17,6 +69,7 @@"connectionTestBrowserNetworkFailed": "Не удалось подключиться к этой конечной точке из браузера. Попробуйте настольное приложение или конечную точку с поддержкой CORS.","connectionTestNetworkFailed": "Не удалось подключиться к конечной точке. Проверьте URL и подключение к сети.","connectionTestUnknownFailed": "Не удалось проверить подключение. Проверьте настройки провайдера и повторите попытку.",+ "getProviderAPIKey": "Получить API-ключ {provider} →","oneKeyManyModels": "Один ключ для 100+ моделей от разных провайдеров.","describeChange": "Опишите изменение…","describeCreateOrChange": "Опишите, что вы хотите создать или изменить.",@@ -80,8 +133,10 @@"permissionRequest": "Инструмент «{tool}» запрашивает разрешение.","baseURLPlaceholder": "Base URL (например, http://localhost:11434/v1)","modelIDPlaceholder": "Model ID (например, llama-3.3-70b)",+ "provider": "Провайдер ИИ","providerSettings": "Настройки провайдера","openProviderSettings": "Открыть настройки провайдера",+ "modelsTitle": "Модели","modelsDescription": "Настройте переиспользуемые модели и подключения к провайдерам.","addModel": "Добавить модель","editModel": "Изменить модель",@@ -136,6 +191,12 @@"apiType": "Тип API","baseURL": "Базовый URL","modelID": "ID модели",+ "selectModel": "Выберите модель",+ "searchModels": "Поиск моделей…",+ "recommendedModels": "Рекомендуемые",+ "latestModels": "Новые",+ "allModels": "Все модели",+ "latest": "Новая","customModelID": "ID пользовательской модели","customModel": "Пользовательская модель…","customModelGroup": "Своя модель",@@ -146,9 +207,12 @@"chatSignInExpired": "Срок вашего входа истёк. Войдите снова в настройках.","chatPlanForbidden": "Ваш тариф не позволяет использовать выбранную модель. Выберите другую в настройках.","chatForbidden": "Этот API-ключ не может использовать выбранную модель. Проверьте доступ к модели.",+ "chatInsufficientCredit": "На счёте провайдера недостаточно средств или квоты. Пополните его и повторите попытку.",+ "chatOutputLimit": "Модель исчерпала лимит выходных токенов во время рассуждения. Увеличьте максимум выходных токенов или снизьте глубину рассуждения.","chatModelNotFound": "Выбранная модель недоступна. Выберите другую модель в настройках.","chatNetworkFailed": "OpenPencil не удалось связаться с провайдером. Проверьте соединение и адрес сервера.","chatRateLimited": "Достигнут лимит запросов провайдера. Подождите и повторите попытку.",+ "chatRequestFailed": "Запрос к модели завершился ошибкой. Проверьте настройки провайдера и повторите попытку.","openProviderSettingsAction": "Открыть настройки","cloudWorkspace": "Рабочее пространство","cloudWorkspaceHint": "Рабочее пространство, тариф которого оплачивает эти запросы.",@@ -164,9 +228,6 @@"cloudCreditsRenew": "Обновится {date}","manageCloudPlanAction": "Управлять тарифом","chatCloudUnavailable": "ИИ OpenPencil Cloud недоступен. Войдите в OpenPencil Cloud и выберите рабочее пространство в настройках.",- "chatInsufficientCredit": "На счёте провайдера недостаточно средств или квоты. Пополните его и повторите попытку.",- "chatOutputLimit": "Модель исчерпала лимит выходных токенов во время рассуждения. Увеличьте максимум выходных токенов или снизьте глубину рассуждения.",- "chatRequestFailed": "Запрос к модели завершился ошибкой. Проверьте настройки провайдера и повторите попытку.","visionModelUnavailable": "Перед добавлением изображений выберите модель для зрения в настройках.","chatPiCompanionMissing": "Pi нужен компаньон Harness. Запустите пошаговую настройку, чтобы установить его.","chatPiCompanionOutdated": "Компаньон Harness не подходит к этой версии OpenPencil. Запустите пошаговую настройку, чтобы обновить его.",@@ -175,65 +236,6 @@"chatPiModel": "У Pi нет модели. Запустите pi в терминале и введите /model или выберите модель в настройках.","completions": "Completions","responses": "Responses",- "connectProvider": "Подключите AI-провайдера, чтобы начать чат.",- "getProviderAPIKey": "Получить API-ключ {provider} →",- "provider": "Провайдер ИИ",- "modelsTitle": "Модели",- "selectModel": "Выберите модель",- "searchModels": "Поиск моделей…",- "recommendedModels": "Рекомендуемые",- "latestModels": "Новые",- "allModels": "Все модели",- "latest": "Новая",- "chatHistory": "История чатов",- "newChat": "Новый чат",- "followAgents": "Следовать за агентами во время работы",- "stopFollowingAgents": "Не следовать за агентами во время работы",- "allChats": "Все чаты",- "renameChat": "Переименовать",- "saveChatTrace": "Сохранить трассировку…",- "chatTraceFailed": "Не удалось сохранить трассировку чата.",- "deleteChat": "Удалить",- "chatTitle": "Название чата",- "saveChatTitle": "Сохранить",- "cancelChatAction": "Отмена",- "deleteChatConfirmation": "Удалить этот чат навсегда?",- "deleteChatDescription": "«{title}» и её сообщения будут удалены. Это действие нельзя отменить.",- "chatDocumentHint": "Откройте документ чата, чтобы продолжить.",- "chatReadOnly": "Этот чат относится к другому документу. Откройте его, чтобы продолжить.",- "chatAgentReadOnly": "Переписка с агентом сохранена, но восстановление его сессии пока недоступно. Начните новый чат.",- "chatStorageFailed": "Не удалось сохранить историю чата. Не закрывайте окно и попробуйте ещё раз.",- "chatHistoryFailed": "Не удалось обновить историю чатов. Попробуйте ещё раз.",- "chatInterrupted": "Этот ответ был прерван.",- "searchChats": "Поиск по чатам…",- "chatScope": "Область поиска чатов",- "thisDocument": "Этот документ",- "allDocuments": "Все документы",- "noChatsFound": "Чаты не найдены.",- "chatActions": "Действия с чатом",- "continueChat": "Продолжить",- "chatSettings": "Чат",- "notificationsHint": "Только когда OpenPencil в фоне или показывает другой документ.",- "notifyNeedsInput": "Агенту нужен ваш ответ",- "notifyNeedsInputHint": "Запрос разрешения несколько секунд ждёт ответа.",- "notifyFinished": "Ответ готов",- "notifyFailed": "Ответ завершился ошибкой",- "notificationsAllow": "Разрешить уведомления",- "notificationsAllowHint": "Браузер один раз спросит, может ли OpenPencil показывать уведомления.",- "notificationsBlocked": "Уведомления для этого сайта заблокированы. Разрешите их в настройках сайта в браузере.",- "notificationsUnsupported": "Этот браузер не умеет показывать уведомления.",- "notificationsSystemHint": "Если уведомления не появляются, разрешите их для OpenPencil в системных настройках уведомлений.",- "notifyTitle": "{agent} · {document}",- "notifyPermission": "Просит разрешения.",- "notifyPermissionAction": "Просит разрешения: {action}",- "notifyReplyFinished": "Ответ ИИ готов.",- "notifyReplyFailed": "Ответ ИИ остановился с ошибкой.",- "reasoningDisplay": "Отображение рассуждений",- "reasoningCollapsed": "Свёрнуто по умолчанию",- "reasoningWhileThinking": "Разворачивать во время размышлений",- "reasoningExpanded": "Развёрнуто по умолчанию",- "jumpToLatest": "К последнему сообщению",- "maxAgentStepsCustom": "Своё значение…","aiSetupWelcomeTitle": "Добро пожаловать в OpenPencil","aiSetupWelcomeDescription": "Создавайте и редактируйте дизайн на открытом холсте. Импортируйте файлы Figma и распоряжайтесь ими как своими.","aiSetupWelcomeAITitle": "Дизайн с ИИ",@@ -259,69 +261,34 @@"modelProviderSetUp": "Настроено","aiSetupAccessAPI": "Аккаунты API","aiSetupAccessServer": "Локальная модель или сервер компании",+ "aiSetupAccessMore": "Другие провайдеры",+ "providerGroupAgents": "Ваши агенты",+ "providerGroupProviders": "Провайдеры",+ "aiSetupServerOther": "Другой сервер","aiSetupAccessServerDescription": "Любой сервер с API, совместимым с OpenAI, например Ollama или LM Studio.","aiSetupConnectTitle": "Подключите ИИ","aiSetupNothingDescription": "Вернитесь и выберите другой доступ или настройте ИИ в расширенных настройках.","aiSetupAgentDescription": "OpenPencil запускает {agent}, когда вы отправляете сообщение, с аккаунтом, в который вошёл {agent}.","aiSetupAgentInstall": "Если он ещё не установлен, выполните:","aiSetupAgentInstallSupported": "Установите поддерживаемый адаптер:",- "aiSetupMeteredNote": "OpenRouter даёт доступ к моделям разных компаний с одним аккаунтом и одним ключом.",- "aiSetupSkillsTitle": "Навыки ваших агентов для кода",- "aiSetupSkillsDescription": "Чат для дизайна может пользоваться навыками, которые установили ваши агенты для кода. Большинство из них — процессы разработки, поэтому выберите только те, что помогают в дизайне; изменить выбор можно в разделе «Настройки › Навыки».",- "aiSetupReviewTitle": "Проверьте настройку",- "aiSetupAgentModel": "Модель выбирает агент",- "aiSetupFinish": "Завершить настройку",- "aiSetupSavedTitle": "ИИ готов к работе",- "aiSetupSavedDescription": "Модели и роли можно изменить в любой момент в настройках.",- "aiSetupRun": "Пройти пошаговую настройку",- "aiSetupServerKeyHint": "Если сервер не проверяет ключи, введите любое значение.",- "aiSetupAlreadyConnected": "Всё выбранное уже подключено.",- "aiSetupOpenRouterSignIn": "Войти через OpenRouter",- "aiSetupOpenRouterWaiting": "Завершите вход в OpenRouter в браузере.",- "aiSetupSignInReopen": "Открыть снова",- "aiSetupOpenRouterOrKey": "Или вставьте ключ API",- "aiSetupOpenRouterBlocked": "Браузер заблокировал окно входа. Разрешите всплывающие окна для OpenPencil и попробуйте снова.",- "aiSetupSignInCancelled": "Вход отменён.",- "aiSetupSignInExpired": "Вход занял слишком много времени. Попробуйте снова.",- "aiSetupOpenRouterFailed": "Не удалось войти в OpenRouter. Попробуйте снова или вставьте ключ API.",- "aiSetupOpenRouterSignedInTitle": "Вход в OpenRouter выполнен",- "aiSetupSavedKeyHint": "Оставьте поле пустым, чтобы использовать сохранённый ключ.",- "aiSetupOpenRouterKeyLabel": "· ключ «{label}»",- "aiSetupOpenRouterVerifying": "Проверяем ключ OpenRouter…",- "aiSetupOpenRouterNoCredits": "На этом аккаунте OpenRouter пока нет кредитов. Пополните баланс в OpenRouter, чтобы пользоваться платными моделями, например рекомендованной.",- "aiSetupSignInChange": "Использовать другой аккаунт",- "aiSetupSignOut": "Выйти",- "aiSetupAccessSubscriptions": "Подписки",- "aiSetupAccessChatGPT": "Используйте модели своего плана ChatGPT в собственном агенте OpenPencil.",- "aiSetupChatGPTSignIn": "Войти через ChatGPT",- "aiSetupChatGPTWaiting": "Завершите вход в ChatGPT в браузере.",- "aiSetupChatGPTSignedInTitle": "Вход в ChatGPT выполнен",- "aiSetupChatGPTFailed": "Не удалось войти в ChatGPT. Попробуйте ещё раз.",- "aiSetupChatGPTPortInUse": "Порт 1455 занят другим входом, например `codex login`. Завершите или закройте его и попробуйте снова.",- "aiSetupChatGPTCallbackSignedIn": "Вход в ChatGPT выполнен. Можно закрыть эту вкладку и вернуться в OpenPencil.",- "aiSetupChatGPTCallbackCancelled": "Вход в ChatGPT отменён. Можно закрыть эту вкладку.",- "aiSetupChatGPTCallbackStale": "Эта ссылка для входа относится к прошлой попытке. Начните заново в OpenPencil.",- "aiSetupChatGPTUsage": "Ответы расходуют лимиты вашего плана ChatGPT.",- "aiSetupSavedSignInHint": "Будет использован сохранённый вход.",- "aiSetupUseRecommended": "Использовать рекомендуемую настройку",- "aiSetupRolesDescription": "Выберите модель для каждого вида работы. Мы подобрали рекомендуемые из подключённого; остальные ваши настройки не изменятся.",- "aiSetupGapDesign": "Ничто из выбранного не умеет создавать и редактировать дизайн.",- "aiSetupGapVision": "Ничто из выбранного не умеет анализировать изображения, поэтому визуальная проверка останется выключенной.",- "aiSetupGapContinue": "Можно продолжить без этого и добавить позже в настройках.",- "aiSetupGapAddOpenRouter": "Добавить OpenRouter (оплата за использование)",- "aiSetupGapRemoveOpenRouter": "Не использовать OpenRouter",- "aiSetupServerVision": "Эта модель умеет читать изображения",- "aiSetupGapCoveredByOpenRouter": "OpenRouter возьмёт на себя то, что не покрывает остальной выбор, с оплатой за каждый запрос.",- "aiSetupAccessMore": "Другие провайдеры",- "providerGroupAgents": "Ваши агенты",- "providerGroupProviders": "Провайдеры",- "aiSetupServerOther": "Другой сервер","aiSetupAgentChecking": "Проверяем этот компьютер…","aiSetupAgentInstalled": "установлен","aiSetupAgentNotFound": "не найден","aiSetupAgentMCP": "MCP-сервер OpenPencil","aiSetupAgentMCPInstall": "Агенты для программирования работают с холстом через MCP-сервер OpenPencil. Установите его командой:","aiSetupAgentPromptHint": "Уже пользуетесь {agent} или другим агентом для программирования? Скопируйте промпт настройки и вставьте его туда — он установит всё нужное OpenPencil.",+ "aiSetupAgentNeedsAdapter": "установлен · нет адаптера OpenPencil",+ "aiSetupAgentInstallAdapter": "Установить адаптер",+ "aiSetupAgentInstallMCP": "Установить MCP-сервер",+ "aiSetupAgentUpdateMCP": "Обновить сервер MCP",+ "aiSetupAgentOutdated": "нужно обновить",+ "aiSetupAgentInstalling": "Устанавливаем…",+ "aiSetupAgentGetCLI": "Установить {agent}",+ "aiSetupAgentNeedsNpm": "Для установки нужен npm, который входит в Node.js. Установите Node.js и проверьте снова.",+ "aiSetupAgentNeedsAdmin": "Для установки нужны права администратора: npm хранит глобальные пакеты в защищённой папке. Выполните команду ниже в терминале или попросите агента настроить папку, принадлежащую вам.",+ "aiSetupAgentInstallFailed": "Установка не завершилась. Проверьте подключение или выполните команду вручную.",+ "aiSetupAgentMCPStartFailed": "MCP-сервер установлен, но не запустился. Перезапустите OpenPencil и проверьте снова.",+ "aiSetupAgentLookupFailed": "Не удалось проверить этот компьютер. Попробуйте снова.","aiSetupAgentCopyPrompt": "Скопировать промпт настройки","aiSetupAgentCheckAgain": "Проверить снова","aiSetupAgentInstallRuns": "Установка выполнит {command}.",@@ -356,20 +323,53 @@"piModelHint": "Модель Pi вида provider/model. Оставьте пустым, чтобы использовать модель Pi по умолчанию.","aiSetupPiSignIn": "Чтобы войти в провайдера или выбрать модель по умолчанию, запустите pi в терминале и введите /login или /model.","aiSetupGetDesktop": "Скачать настольное приложение",- "aiSetupAgentNeedsAdapter": "установлен · нет адаптера OpenPencil",- "aiSetupAgentInstallAdapter": "Установить адаптер",- "aiSetupAgentInstallMCP": "Установить MCP-сервер",- "aiSetupAgentUpdateMCP": "Обновить сервер MCP",- "aiSetupAgentOutdated": "нужно обновить",- "aiSetupAgentInstalling": "Устанавливаем…",- "aiSetupAgentGetCLI": "Установить {agent}",- "aiSetupAgentNeedsNpm": "Для установки нужен npm, который входит в Node.js. Установите Node.js и проверьте снова.",- "aiSetupAgentNeedsAdmin": "Для установки нужны права администратора: npm хранит глобальные пакеты в защищённой папке. Выполните команду ниже в терминале или попросите агента настроить папку, принадлежащую вам.",- "aiSetupAgentInstallFailed": "Установка не завершилась. Проверьте подключение или выполните команду вручную.",- "aiSetupAgentMCPStartFailed": "MCP-сервер установлен, но не запустился. Перезапустите OpenPencil и проверьте снова.",- "aiSetupAgentLookupFailed": "Не удалось проверить этот компьютер. Попробуйте снова.",- "chatAgentWorkingOn": "{agent} работает над «{page}»",- "chatGoToPage": "Перейти к странице",+ "aiSetupMeteredNote": "OpenRouter даёт доступ к моделям разных компаний с одним аккаунтом и одним ключом.",+ "aiSetupSkillsTitle": "Навыки ваших агентов для кода",+ "aiSetupSkillsDescription": "Чат для дизайна может пользоваться навыками, которые установили ваши агенты для кода. Большинство из них — процессы разработки, поэтому выберите только те, что помогают в дизайне; изменить выбор можно в разделе «Настройки › Навыки».",+ "aiSetupReviewTitle": "Проверьте настройку",+ "aiSetupAgentModel": "Модель выбирает агент",+ "aiSetupFinish": "Завершить настройку",+ "aiSetupSavedTitle": "ИИ готов к работе",+ "aiSetupSavedDescription": "Модели и роли можно изменить в любой момент в настройках.",+ "aiSetupRun": "Пройти пошаговую настройку",+ "aiSetupServerKeyHint": "Если сервер не проверяет ключи, введите любое значение.",+ "aiSetupGapDesign": "Ничто из выбранного не умеет создавать и редактировать дизайн.",+ "aiSetupGapVision": "Ничто из выбранного не умеет анализировать изображения, поэтому визуальная проверка останется выключенной.",+ "aiSetupGapContinue": "Можно продолжить без этого и добавить позже в настройках.",+ "aiSetupGapAddOpenRouter": "Добавить OpenRouter (оплата за использование)",+ "aiSetupGapRemoveOpenRouter": "Не использовать OpenRouter",+ "aiSetupGapCoveredByOpenRouter": "OpenRouter возьмёт на себя то, что не покрывает остальной выбор, с оплатой за каждый запрос.",+ "aiSetupServerVision": "Эта модель умеет читать изображения",+ "aiSetupSavedKeyHint": "Оставьте поле пустым, чтобы использовать сохранённый ключ.",+ "aiSetupAlreadyConnected": "Всё выбранное уже подключено.",+ "aiSetupOpenRouterSignIn": "Войти через OpenRouter",+ "aiSetupOpenRouterWaiting": "Завершите вход в OpenRouter в браузере.",+ "aiSetupSignInReopen": "Открыть снова",+ "aiSetupOpenRouterOrKey": "Или вставьте ключ API",+ "aiSetupOpenRouterBlocked": "Браузер заблокировал окно входа. Разрешите всплывающие окна для OpenPencil и попробуйте снова.",+ "aiSetupSignInCancelled": "Вход отменён.",+ "aiSetupSignInExpired": "Вход занял слишком много времени. Попробуйте снова.",+ "aiSetupOpenRouterFailed": "Не удалось войти в OpenRouter. Попробуйте снова или вставьте ключ API.",+ "aiSetupOpenRouterSignedInTitle": "Вход в OpenRouter выполнен",+ "aiSetupOpenRouterKeyLabel": "· ключ «{label}»",+ "aiSetupOpenRouterVerifying": "Проверяем ключ OpenRouter…",+ "aiSetupOpenRouterNoCredits": "На этом аккаунте OpenRouter пока нет кредитов. Пополните баланс в OpenRouter, чтобы пользоваться платными моделями, например рекомендованной.",+ "aiSetupSignInChange": "Использовать другой аккаунт",+ "aiSetupSignOut": "Выйти",+ "aiSetupAccessSubscriptions": "Подписки",+ "aiSetupAccessChatGPT": "Используйте модели своего плана ChatGPT в собственном агенте OpenPencil.",+ "aiSetupChatGPTSignIn": "Войти через ChatGPT",+ "aiSetupChatGPTWaiting": "Завершите вход в ChatGPT в браузере.",+ "aiSetupChatGPTSignedInTitle": "Вход в ChatGPT выполнен",+ "aiSetupChatGPTFailed": "Не удалось войти в ChatGPT. Попробуйте ещё раз.",+ "aiSetupChatGPTPortInUse": "Порт 1455 занят другим входом, например `codex login`. Завершите или закройте его и попробуйте снова.",+ "aiSetupChatGPTCallbackSignedIn": "Вход в ChatGPT выполнен. Можно закрыть эту вкладку и вернуться в OpenPencil.",+ "aiSetupChatGPTCallbackCancelled": "Вход в ChatGPT отменён. Можно закрыть эту вкладку.",+ "aiSetupChatGPTCallbackStale": "Эта ссылка для входа относится к прошлой попытке. Начните заново в OpenPencil.",+ "aiSetupChatGPTUsage": "Ответы расходуют лимиты вашего плана ChatGPT.",+ "aiSetupSavedSignInHint": "Будет использован сохранённый вход.",+ "aiSetupUseRecommended": "Использовать рекомендуемую настройку",+ "aiSetupRolesDescription": "Выберите модель для каждого вида работы. Мы подобрали рекомендуемые из подключённого; остальные ваши настройки не изменятся.","chatReferenceLayers": "Слои","chatReferencePages": "Страницы","chatReferenceSkills": "Навыки",@@ -417,6 +417,31 @@"skillWarningLongDescription": "Описание длиннее {max} символов.","skillErrorNoFrontmatter": "SKILL.md не начинается с YAML-frontmatter между строками ---.","skillErrorInvalidFrontmatter": "Frontmatter файла SKILL.md некорректен: {detail}",+ "contextUsed": "Контекст: занято {percent}%",+ "contextTitle": "Контекст",+ "contextTokens": "{used} из {total} токенов",+ "contextCompactsAt": "Сжимается автоматически на {tokens} токенах, оставляя место для ответа.",+ "contextCompactsOff": "Автоматическое сжатие выключено.",+ "contextNearlyFull": "Контекст занят на {percent}%",+ "compact": "Сжать",+ "compactCommand": "Кратко пересказать разговор; текст после команды говорит, что сохранить",+ "compactAutomatically": "Сжимать автоматически",+ "compactAutomaticallyHint": "Кратко пересказывает старые сообщения, когда окно контекста заполняется.",+ "compacting": "Сжатие разговора…",+ "compactionFailed": "Не удалось сжать разговор. Ничего не изменилось.",+ "compactAndRetry": "Сжать и повторить",+ "chatContextLimit": "Разговор длиннее, чем модель может прочитать.",+ "conversationCompacted": "Разговор сжат",+ "compactionKeepsMessages": "Теперь модель получает этот пересказ вместо сообщений выше; вы по-прежнему их видите.",+ "agentCompactionKeepsMessages": "Теперь агент работает со своим пересказом сообщений выше; вы по-прежнему их видите.",+ "compactionTokens": "{before} → {after} токенов",+ "tokenUsage": "Расход токенов",+ "tokenUsageHint": "Показывает токены каждого ответа.",+ "tokenUsageHover": "При наведении",+ "tokenUsageAlways": "Всегда",+ "tokenUsageHidden": "Скрыто",+ "replyTokens": "{input} на входе · {output} на выходе",+ "replyCachedTokens": "{cached} из кэша","skillErrorNoDescription": "Во frontmatter файла SKILL.md нет описания.","skillErrorNoName": "Во frontmatter файла SKILL.md нет имени."}diff --git a/packages/vue/src/i18n/locales/zh-cn/ai.json b/packages/vue/src/i18n/locales/zh-cn/ai.jsonindex 94ddd13d3..3320e29e5 100644--- a/packages/vue/src/i18n/locales/zh-cn/ai.json+++ b/packages/vue/src/i18n/locales/zh-cn/ai.json@@ -1,7 +1,59 @@{+ "jumpToLatest": "跳转到最新消息",+ "chatSettings": "聊天",+ "notificationsHint": "仅在 OpenPencil 处于后台或显示其他文档时发送。",+ "notifyNeedsInput": "智能体需要你处理",+ "notifyNeedsInputHint": "一个权限请求已等待几秒仍未回复。",+ "notifyFinished": "回复完成",+ "notifyFailed": "回复失败",+ "notificationsAllow": "允许通知",+ "notificationsAllowHint": "浏览器会询问一次是否允许 OpenPencil 显示通知。",+ "notificationsBlocked": "此网站的通知已被阻止。请在浏览器的网站设置中允许。",+ "notificationsUnsupported": "此浏览器无法显示通知。",+ "notificationsSystemHint": "如果没有显示,请在系统的通知设置中允许 OpenPencil。",+ "notifyTitle": "{agent} · {document}",+ "notifyPermission": "请求权限。",+ "notifyPermissionAction": "请求权限:{action}",+ "notifyReplyFinished": "AI 回复已完成。",+ "notifyReplyFailed": "AI 回复因错误而停止。","maxAgentSteps": "每条消息的最大步骤数",+ "maxAgentStepsCustom": "自定义…","maxAgentStepsHint": "仅适用于内置 AI;ACP 和 Pi 使用各自的限制。按 Enter 或离开输入框时保存,从下一条消息开始生效。提高上限可能增加费用。","maxAgentStepsRange": "请输入 {min} 到 {max} 之间的整数。",+ "reasoningDisplay": "推理显示",+ "reasoningCollapsed": "默认折叠",+ "reasoningWhileThinking": "思考时展开",+ "reasoningExpanded": "默认展开",+ "continueChat": "继续",+ "searchChats": "搜索对话…",+ "chatScope": "对话范围",+ "thisDocument": "此文档",+ "allDocuments": "所有文档",+ "noChatsFound": "未找到对话。",+ "chatActions": "对话操作",+ "chatHistory": "聊天记录",+ "newChat": "新建聊天",+ "followAgents": "工作时跟随智能体",+ "stopFollowingAgents": "停止在工作时跟随智能体",+ "allChats": "所有聊天",+ "renameChat": "重命名",+ "saveChatTrace": "保存追踪记录…",+ "chatTraceFailed": "无法保存聊天追踪记录。",+ "deleteChat": "删除",+ "chatTitle": "聊天标题",+ "saveChatTitle": "保存",+ "cancelChatAction": "取消",+ "deleteChatConfirmation": "永久删除此聊天?",+ "deleteChatDescription": "“{title}”及其消息将被删除,且无法撤销。",+ "chatDocumentHint": "打开聊天所属的文档以继续。",+ "chatReadOnly": "此聊天属于另一个文档。打开该文档以继续。",+ "chatAgentReadOnly": "与代理的对话已保存,但暂时无法在此恢复会话。请新建聊天。",+ "chatStorageFailed": "无法保存聊天记录。请保持此窗口打开并重试。",+ "chatHistoryFailed": "无法更新聊天记录。请重试。",+ "chatInterrupted": "此回复已中断。",+ "chatAgentWorkingOn": "{agent} 正在处理“{page}”",+ "chatGoToPage": "转到页面",+ "connectProvider": "连接 AI 提供商以开始聊天。","connectionTestSuccess": "连接成功。模型可访问。","connectionTestMissingAPIKey": "请在测试前输入 API 密钥。","connectionTestMissingSignIn": "请在测试前登录。",@@ -17,6 +69,7 @@"connectionTestBrowserNetworkFailed": "无法从浏览器访问此端点。请尝试桌面应用,或使用已启用 CORS 的端点。","connectionTestNetworkFailed": "无法访问端点。请检查 URL 和网络连接。","connectionTestUnknownFailed": "连接测试失败。请检查提供商设置,然后重试。",+ "getProviderAPIKey": "获取 {provider} API 密钥 →","oneKeyManyModels": "一个密钥即可使用来自所有提供商的 100+ 模型。","describeChange": "描述一个更改…","describeCreateOrChange": "描述你想创建或更改的内容。",@@ -80,8 +133,10 @@"permissionRequest": "{tool} 正在请求权限。","baseURLPlaceholder": "基础 URL(例如 http://localhost:11434/v1)","modelIDPlaceholder": "模型 ID(例如 llama-3.3-70b)",+ "provider": "AI 提供商","providerSettings": "提供商设置","openProviderSettings": "打开提供商设置",+ "modelsTitle": "模型","modelsDescription": "配置可复用模型及其提供商连接。","addModel": "添加模型","editModel": "编辑模型",@@ -152,9 +207,12 @@"chatSignInExpired": "你的登录已过期,请在设置中重新登录。","chatPlanForbidden": "你的套餐无法使用所选模型。请在设置中选择其他模型。","chatForbidden": "此API密钥无法使用所选模型。请检查模型访问权限。",+ "chatInsufficientCredit": "提供商账户的余额或配额不足。请充值后重试。",+ "chatOutputLimit": "模型在推理时耗尽了输出词元。请提高最大输出词元数或降低推理强度。","chatModelNotFound": "所选模型不可用。请在设置中选择其他模型。","chatNetworkFailed": "OpenPencil无法连接提供商。请检查网络和端点。","chatRateLimited": "已达到提供商请求限制。请稍候再试。",+ "chatRequestFailed": "模型请求失败。请检查提供商设置后重试。","openProviderSettingsAction": "打开设置","cloudWorkspace": "工作区","cloudWorkspaceHint": "由该工作区的方案为这些请求付费。",@@ -170,9 +228,6 @@"cloudCreditsRenew": "将于 {date} 续期","manageCloudPlanAction": "管理方案","chatCloudUnavailable": "OpenPencil Cloud AI 不可用。请登录 OpenPencil Cloud,并在设置中选择一个工作区。",- "chatInsufficientCredit": "提供商账户的余额或配额不足。请充值后重试。",- "chatOutputLimit": "模型在推理时耗尽了输出词元。请提高最大输出词元数或降低推理强度。",- "chatRequestFailed": "模型请求失败。请检查提供商设置后重试。","visionModelUnavailable": "附加图片前,请在设置中选择视觉模型。","chatPiCompanionMissing": "Pi 需要 Harness 配套程序。运行引导式设置来安装它。","chatPiCompanionOutdated": "Harness 配套程序与此版本的 OpenPencil 不匹配。运行引导式设置来更新它。",@@ -181,59 +236,6 @@"chatPiModel": "Pi 没有可用的模型。请在终端中运行 pi 并输入 /model,或在设置中选择一个。","completions": "Completions","responses": "Responses",- "connectProvider": "连接 AI 提供商以开始聊天。",- "getProviderAPIKey": "获取 {provider} API 密钥 →",- "provider": "AI 提供商",- "modelsTitle": "模型",- "chatHistory": "聊天记录",- "newChat": "新建聊天",- "followAgents": "工作时跟随智能体",- "stopFollowingAgents": "停止在工作时跟随智能体",- "allChats": "所有聊天",- "renameChat": "重命名",- "saveChatTrace": "保存追踪记录…",- "chatTraceFailed": "无法保存聊天追踪记录。",- "deleteChat": "删除",- "chatTitle": "聊天标题",- "saveChatTitle": "保存",- "cancelChatAction": "取消",- "deleteChatConfirmation": "永久删除此聊天?",- "deleteChatDescription": "“{title}”及其消息将被删除,且无法撤销。",- "chatDocumentHint": "打开聊天所属的文档以继续。",- "chatReadOnly": "此聊天属于另一个文档。打开该文档以继续。",- "chatAgentReadOnly": "与代理的对话已保存,但暂时无法在此恢复会话。请新建聊天。",- "chatStorageFailed": "无法保存聊天记录。请保持此窗口打开并重试。",- "chatHistoryFailed": "无法更新聊天记录。请重试。",- "chatInterrupted": "此回复已中断。",- "searchChats": "搜索对话…",- "chatScope": "对话范围",- "thisDocument": "此文档",- "allDocuments": "所有文档",- "noChatsFound": "未找到对话。",- "chatActions": "对话操作",- "continueChat": "继续",- "chatSettings": "聊天",- "notificationsHint": "仅在 OpenPencil 处于后台或显示其他文档时发送。",- "notifyNeedsInput": "智能体需要你处理",- "notifyNeedsInputHint": "一个权限请求已等待几秒仍未回复。",- "notifyFinished": "回复完成",- "notifyFailed": "回复失败",- "notificationsAllow": "允许通知",- "notificationsAllowHint": "浏览器会询问一次是否允许 OpenPencil 显示通知。",- "notificationsBlocked": "此网站的通知已被阻止。请在浏览器的网站设置中允许。",- "notificationsUnsupported": "此浏览器无法显示通知。",- "notificationsSystemHint": "如果没有显示,请在系统的通知设置中允许 OpenPencil。",- "notifyTitle": "{agent} · {document}",- "notifyPermission": "请求权限。",- "notifyPermissionAction": "请求权限:{action}",- "notifyReplyFinished": "AI 回复已完成。",- "notifyReplyFailed": "AI 回复因错误而停止。",- "reasoningDisplay": "推理显示",- "reasoningCollapsed": "默认折叠",- "reasoningWhileThinking": "思考时展开",- "reasoningExpanded": "默认展开",- "jumpToLatest": "跳转到最新消息",- "maxAgentStepsCustom": "自定义…","aiSetupWelcomeTitle": "欢迎使用 OpenPencil","aiSetupWelcomeDescription": "在开放的画布上创建和编辑设计。导入 Figma 文件,随心使用。","aiSetupWelcomeAITitle": "用 AI 设计",@@ -259,69 +261,34 @@"modelProviderSetUp": "已设置","aiSetupAccessAPI": "API 账户","aiSetupAccessServer": "本地模型或公司服务器",+ "aiSetupAccessMore": "更多服务商",+ "providerGroupAgents": "你的智能体",+ "providerGroupProviders": "服务商",+ "aiSetupServerOther": "其他服务器","aiSetupAccessServerDescription": "任何兼容 OpenAI API 的服务器,例如 Ollama 或 LM Studio。","aiSetupConnectTitle": "连接你的 AI","aiSetupNothingDescription": "返回选择其他服务,或在高级设置中配置 AI。","aiSetupAgentDescription": "发送消息时,OpenPencil 会使用 {agent} 已登录的账户启动 {agent}。","aiSetupAgentInstall": "如果尚未安装,请运行:","aiSetupAgentInstallSupported": "安装受支持的适配器:",- "aiSetupMeteredNote": "OpenRouter 让你用一个账户和一个密钥使用多家厂商的模型。",- "aiSetupSkillsTitle": "编程智能体的技能",- "aiSetupSkillsDescription": "设计聊天可以使用你的编程智能体安装的技能。其中大多是编程工作流,所以只选对设计有帮助的;之后可在“设置 › 技能”中更改。",- "aiSetupReviewTitle": "检查你的设置",- "aiSetupAgentModel": "模型由智能体选择",- "aiSetupFinish": "完成设置",- "aiSetupSavedTitle": "AI 已就绪",- "aiSetupSavedDescription": "你可以随时在设置中更改模型和角色。",- "aiSetupRun": "运行引导式设置",- "aiSetupServerKeyHint": "如果你的服务器不校验密钥,可以输入任意值。",- "aiSetupAlreadyConnected": "你选择的服务都已连接。",- "aiSetupOpenRouterSignIn": "使用 OpenRouter 登录",- "aiSetupOpenRouterWaiting": "请在浏览器中完成 OpenRouter 登录。",- "aiSetupSignInReopen": "再次打开",- "aiSetupOpenRouterOrKey": "或粘贴 API 密钥",- "aiSetupOpenRouterBlocked": "浏览器拦截了登录窗口。请允许 OpenPencil 弹出窗口后重试。",- "aiSetupSignInCancelled": "登录已取消。",- "aiSetupSignInExpired": "登录耗时过长,请重试。",- "aiSetupOpenRouterFailed": "无法登录 OpenRouter。请重试或粘贴 API 密钥。",- "aiSetupOpenRouterSignedInTitle": "已登录 OpenRouter",- "aiSetupSavedKeyHint": "留空即可继续使用已保存的密钥。",- "aiSetupOpenRouterKeyLabel": "· 密钥“{label}”",- "aiSetupOpenRouterVerifying": "正在检查你的 OpenRouter 密钥…",- "aiSetupOpenRouterNoCredits": "这个 OpenRouter 账户还没有额度。请在 OpenRouter 充值后再使用推荐模型等付费模型。",- "aiSetupSignInChange": "使用其他账户",- "aiSetupSignOut": "退出登录",- "aiSetupAccessSubscriptions": "订阅",- "aiSetupAccessChatGPT": "在 OpenPencil 自带的智能体中使用你的 ChatGPT 套餐模型。",- "aiSetupChatGPTSignIn": "使用 ChatGPT 登录",- "aiSetupChatGPTWaiting": "请在浏览器中完成 ChatGPT 登录。",- "aiSetupChatGPTSignedInTitle": "已登录 ChatGPT",- "aiSetupChatGPTFailed": "无法登录 ChatGPT,请重试。",- "aiSetupChatGPTPortInUse": "另一个登录(如 `codex login`)正在使用端口 1455。请完成或关闭它后重试。",- "aiSetupChatGPTCallbackSignedIn": "已登录 ChatGPT。你可以关闭此标签页并返回 OpenPencil。",- "aiSetupChatGPTCallbackCancelled": "ChatGPT 登录已取消。你可以关闭此标签页。",- "aiSetupChatGPTCallbackStale": "此登录链接属于之前的尝试。请从 OpenPencil 重新开始。",- "aiSetupChatGPTUsage": "回复会计入你的 ChatGPT 套餐用量限制。",- "aiSetupSavedSignInHint": "将使用已保存的登录。",- "aiSetupUseRecommended": "使用推荐设置",- "aiSetupRolesDescription": "为每类工作选择模型。我们已从你连接的服务中选好推荐模型,其他已配置的内容保持不变。",- "aiSetupGapDesign": "你选择的服务都无法创建和编辑设计。",- "aiSetupGapVision": "你选择的服务都无法查看图片,因此可视化审查将保持关闭。",- "aiSetupGapContinue": "你可以先继续,之后在设置中添加。",- "aiSetupGapAddOpenRouter": "添加 OpenRouter(按量付费)",- "aiSetupGapRemoveOpenRouter": "不使用 OpenRouter",- "aiSetupServerVision": "此模型可以读取图片",- "aiSetupGapCoveredByOpenRouter": "OpenRouter 会覆盖你其他选择无法完成的部分,按请求计费。",- "aiSetupAccessMore": "更多服务商",- "providerGroupAgents": "你的智能体",- "providerGroupProviders": "服务商",- "aiSetupServerOther": "其他服务器","aiSetupAgentChecking": "正在检查这台电脑…","aiSetupAgentInstalled": "已安装","aiSetupAgentNotFound": "未找到","aiSetupAgentMCP": "OpenPencil MCP 服务器","aiSetupAgentMCPInstall": "编程智能体通过 OpenPencil 的 MCP 服务器操作画布。使用以下命令安装:","aiSetupAgentPromptHint": "已经在用 {agent} 或其他编程智能体?复制设置提示词并粘贴进去,它会安装 OpenPencil 所需的内容。",+ "aiSetupAgentNeedsAdapter": "已安装 · 缺少 OpenPencil 适配器",+ "aiSetupAgentInstallAdapter": "安装适配器",+ "aiSetupAgentInstallMCP": "安装 MCP 服务器",+ "aiSetupAgentUpdateMCP": "更新 MCP 服务器",+ "aiSetupAgentOutdated": "需要更新",+ "aiSetupAgentInstalling": "正在安装…",+ "aiSetupAgentGetCLI": "安装 {agent}",+ "aiSetupAgentNeedsNpm": "安装需要 Node.js 自带的 npm。请先安装 Node.js,然后重新检查。",+ "aiSetupAgentNeedsAdmin": "安装需要管理员权限,因为 npm 将全局包放在受保护的文件夹中。请在终端中运行下方命令,或让你的智能体设置一个属于你的文件夹。",+ "aiSetupAgentInstallFailed": "安装未完成。请检查网络连接,或自行运行该命令。",+ "aiSetupAgentMCPStartFailed": "MCP 服务器已安装但未能启动。请重启 OpenPencil,然后重新检查。",+ "aiSetupAgentLookupFailed": "无法检查这台电脑,请重试。","aiSetupAgentCopyPrompt": "复制设置提示词","aiSetupAgentCheckAgain": "重新检查","aiSetupAgentInstallRuns": "安装将运行 {command}。",@@ -356,20 +323,53 @@"piModelHint": "Pi 模型,例如 provider/model。留空则使用 Pi 的默认模型。","aiSetupPiSignIn": "要登录提供商或选择默认模型,请在终端中运行 pi 并输入 /login 或 /model。","aiSetupGetDesktop": "获取桌面应用",- "aiSetupAgentNeedsAdapter": "已安装 · 缺少 OpenPencil 适配器",- "aiSetupAgentInstallAdapter": "安装适配器",- "aiSetupAgentInstallMCP": "安装 MCP 服务器",- "aiSetupAgentUpdateMCP": "更新 MCP 服务器",- "aiSetupAgentOutdated": "需要更新",- "aiSetupAgentInstalling": "正在安装…",- "aiSetupAgentGetCLI": "安装 {agent}",- "aiSetupAgentNeedsNpm": "安装需要 Node.js 自带的 npm。请先安装 Node.js,然后重新检查。",- "aiSetupAgentNeedsAdmin": "安装需要管理员权限,因为 npm 将全局包放在受保护的文件夹中。请在终端中运行下方命令,或让你的智能体设置一个属于你的文件夹。",- "aiSetupAgentInstallFailed": "安装未完成。请检查网络连接,或自行运行该命令。",- "aiSetupAgentMCPStartFailed": "MCP 服务器已安装但未能启动。请重启 OpenPencil,然后重新检查。",- "aiSetupAgentLookupFailed": "无法检查这台电脑,请重试。",- "chatAgentWorkingOn": "{agent} 正在处理“{page}”",- "chatGoToPage": "转到页面",+ "aiSetupMeteredNote": "OpenRouter 让你用一个账户和一个密钥使用多家厂商的模型。",+ "aiSetupSkillsTitle": "编程智能体的技能",+ "aiSetupSkillsDescription": "设计聊天可以使用你的编程智能体安装的技能。其中大多是编程工作流,所以只选对设计有帮助的;之后可在“设置 › 技能”中更改。",+ "aiSetupReviewTitle": "检查你的设置",+ "aiSetupAgentModel": "模型由智能体选择",+ "aiSetupFinish": "完成设置",+ "aiSetupSavedTitle": "AI 已就绪",+ "aiSetupSavedDescription": "你可以随时在设置中更改模型和角色。",+ "aiSetupRun": "运行引导式设置",+ "aiSetupServerKeyHint": "如果你的服务器不校验密钥,可以输入任意值。",+ "aiSetupGapDesign": "你选择的服务都无法创建和编辑设计。",+ "aiSetupGapVision": "你选择的服务都无法查看图片,因此可视化审查将保持关闭。",+ "aiSetupGapContinue": "你可以先继续,之后在设置中添加。",+ "aiSetupGapAddOpenRouter": "添加 OpenRouter(按量付费)",+ "aiSetupGapRemoveOpenRouter": "不使用 OpenRouter",+ "aiSetupGapCoveredByOpenRouter": "OpenRouter 会覆盖你其他选择无法完成的部分,按请求计费。",+ "aiSetupServerVision": "此模型可以读取图片",+ "aiSetupSavedKeyHint": "留空即可继续使用已保存的密钥。",+ "aiSetupAlreadyConnected": "你选择的服务都已连接。",+ "aiSetupOpenRouterSignIn": "使用 OpenRouter 登录",+ "aiSetupOpenRouterWaiting": "请在浏览器中完成 OpenRouter 登录。",+ "aiSetupSignInReopen": "再次打开",+ "aiSetupOpenRouterOrKey": "或粘贴 API 密钥",+ "aiSetupOpenRouterBlocked": "浏览器拦截了登录窗口。请允许 OpenPencil 弹出窗口后重试。",+ "aiSetupSignInCancelled": "登录已取消。",+ "aiSetupSignInExpired": "登录耗时过长,请重试。",+ "aiSetupOpenRouterFailed": "无法登录 OpenRouter。请重试或粘贴 API 密钥。",+ "aiSetupOpenRouterSignedInTitle": "已登录 OpenRouter",+ "aiSetupOpenRouterKeyLabel": "· 密钥“{label}”",+ "aiSetupOpenRouterVerifying": "正在检查你的 OpenRouter 密钥…",+ "aiSetupOpenRouterNoCredits": "这个 OpenRouter 账户还没有额度。请在 OpenRouter 充值后再使用推荐模型等付费模型。",+ "aiSetupSignInChange": "使用其他账户",+ "aiSetupSignOut": "退出登录",+ "aiSetupAccessSubscriptions": "订阅",+ "aiSetupAccessChatGPT": "在 OpenPencil 自带的智能体中使用你的 ChatGPT 套餐模型。",+ "aiSetupChatGPTSignIn": "使用 ChatGPT 登录",+ "aiSetupChatGPTWaiting": "请在浏览器中完成 ChatGPT 登录。",+ "aiSetupChatGPTSignedInTitle": "已登录 ChatGPT",+ "aiSetupChatGPTFailed": "无法登录 ChatGPT,请重试。",+ "aiSetupChatGPTPortInUse": "另一个登录(如 `codex login`)正在使用端口 1455。请完成或关闭它后重试。",+ "aiSetupChatGPTCallbackSignedIn": "已登录 ChatGPT。你可以关闭此标签页并返回 OpenPencil。",+ "aiSetupChatGPTCallbackCancelled": "ChatGPT 登录已取消。你可以关闭此标签页。",+ "aiSetupChatGPTCallbackStale": "此登录链接属于之前的尝试。请从 OpenPencil 重新开始。",+ "aiSetupChatGPTUsage": "回复会计入你的 ChatGPT 套餐用量限制。",+ "aiSetupSavedSignInHint": "将使用已保存的登录。",+ "aiSetupUseRecommended": "使用推荐设置",+ "aiSetupRolesDescription": "为每类工作选择模型。我们已从你连接的服务中选好推荐模型,其他已配置的内容保持不变。","chatReferenceLayers": "图层","chatReferencePages": "页面","chatReferenceSkills": "技能",@@ -417,6 +417,31 @@"skillWarningLongDescription": "描述超过 {max} 个字符。","skillErrorNoFrontmatter": "SKILL.md 没有以 --- 行之间的 YAML frontmatter 开头。","skillErrorInvalidFrontmatter": "SKILL.md 的 frontmatter 无效:{detail}",+ "contextUsed": "上下文:已用 {percent}%",+ "contextTitle": "上下文",+ "contextTokens": "{used} / {total} 词元",+ "contextCompactsAt": "在 {tokens} 词元时自动压缩,为回复留出空间。",+ "contextCompactsOff": "自动压缩已关闭。",+ "contextNearlyFull": "上下文已用 {percent}%",+ "compact": "压缩",+ "compactCommand": "总结目前为止的对话;其后的文字说明要保留的内容",+ "compactAutomatically": "自动压缩",+ "compactAutomaticallyHint": "上下文窗口快满时总结较早的消息。",+ "compacting": "正在压缩对话…",+ "compactionFailed": "无法压缩对话。未做任何更改。",+ "compactAndRetry": "压缩并重试",+ "chatContextLimit": "对话超出了模型能读取的长度。",+ "conversationCompacted": "对话已压缩",+ "compactionKeepsMessages": "模型现在收到这份总结,而不是上面的消息;你仍然能看到它们。",+ "agentCompactionKeepsMessages": "智能体现在基于它自己对上面消息的总结工作;你仍然能看到它们。",+ "compactionTokens": "{before} → {after} 词元",+ "tokenUsage": "词元用量",+ "tokenUsageHint": "显示每条回复的词元。",+ "tokenUsageHover": "悬停时",+ "tokenUsageAlways": "始终",+ "tokenUsageHidden": "隐藏",+ "replyTokens": "输入 {input} · 输出 {output}",+ "replyCachedTokens": "缓存 {cached}","skillErrorNoDescription": "SKILL.md 的 frontmatter 中没有描述。","skillErrorNoName": "SKILL.md 的 frontmatter 中没有名称。"}diff --git a/packages/vue/src/i18n/messages/ai.ts b/packages/vue/src/i18n/messages/ai.tsindex abd9ab200..756c2a3a7 100644--- a/packages/vue/src/i18n/messages/ai.ts+++ b/packages/vue/src/i18n/messages/ai.ts@@ -480,6 +480,35 @@ export const aiMessageDefaults = {skillWarningLongDescription: params('The description is longer than {max} characters.'),skillErrorNoFrontmatter: 'SKILL.md does not start with YAML frontmatter between --- lines.',skillErrorInvalidFrontmatter: params('The SKILL.md frontmatter is invalid: {detail}'),+ contextUsed: params('Context: {percent}% used'),+ contextTitle: 'Context',+ contextTokens: params('{used} of {total} tokens'),+ contextCompactsAt: params(+ 'Compacts automatically at {tokens} tokens, keeping room for the reply.'+ ),+ contextCompactsOff: 'Automatic compaction is off.',+ contextNearlyFull: params('Context {percent}% used'),+ compact: 'Compact',+ compactCommand: 'Summarize the conversation so far; text after it says what to keep',+ compactAutomatically: 'Compact automatically',+ compactAutomaticallyHint: 'Summarizes older messages when the context window fills up.',+ compacting: 'Compacting the conversation…',+ compactionFailed: 'The conversation could not be compacted. Nothing was changed.',+ compactAndRetry: 'Compact and retry',+ chatContextLimit: 'The conversation is longer than the model can read.',+ conversationCompacted: 'Conversation compacted',+ compactionKeepsMessages:+ 'The model now gets this summary instead of the messages above; you still see them.',+ agentCompactionKeepsMessages:+ 'The agent now works from its own summary of the messages above; you still see them.',+ compactionTokens: params('{before} → {after} tokens'),+ tokenUsage: 'Token usage',+ tokenUsageHint: "Shows each reply's tokens.",+ tokenUsageHover: 'On hover',+ tokenUsageAlways: 'Always',+ tokenUsageHidden: 'Hidden',+ replyTokens: params('{input} in · {output} out'),+ replyCachedTokens: params('{cached} cached'),skillErrorNoDescription: 'The SKILL.md frontmatter has no description.',skillErrorNoName: 'The SKILL.md frontmatter has no name.'} as constdiff --git a/src/app/ai/agents/pi/process.ts b/src/app/ai/agents/pi/process.tsindex 2c129a809..8225a2250 100644--- a/src/app/ai/agents/pi/process.ts+++ b/src/app/ai/agents/pi/process.ts@@ -30,6 +30,12 @@ const harnessTurnEventSchema = v.variant('type', [// Companions before usage reporting send none.usage: v.optional(tokenUsageSchema)}),+ v.object({+ type: v.literal('compaction'),+ trigger: v.picklist(['manual', 'auto']),+ summary: v.string(),+ tokensBefore: v.nullable(v.number())+ }),v.object({ type: v.literal('error'), message: v.string() })])diff --git a/src/app/ai/chat/compaction/limits.ts b/src/app/ai/chat/compaction/limits.tsnew file mode 100644index 000000000..85792386e--- /dev/null+++ b/src/app/ai/chat/compaction/limits.ts@@ -0,0 +1,124 @@+import { computedAsync } from '@vueuse/core'+import type { UIMessage } from 'ai'+import { computed, type Ref } from 'vue'++import { contextTokensOf, usageOf } from '@/app/ai/chat/metadata'+import { resolveModelsDevModel } from '@/app/ai/models/catalog'+import { resolveLanguageModelID } from '@/app/ai/models/language-model'+import { resolveProviderModel } from '@/app/ai/models/reasoning/floors'+import { designModelConnection, designModelProfile } from '@/app/ai/models/store'++import { compactionOf, messagesSinceCompaction } from './marker'++/** What a model can hold, prompt and reply together, and how much of it a reply may take. */+export interface ContextLimits {+ contextWindow: number+ maxOutputTokens: number+}++/**+ * The Design model's limits, when the conversation runs on a model the chat calls itself and+ * its catalog gives a window. Agents keep their own context.+ */+export async function designContextLimits(): Promise<ContextLimits | null> {+ const profile = designModelProfile.value+ const providerID = designModelConnection.value?.providerID+ if (!profile || !providerID || providerID.startsWith('acp:') || providerID === 'harness:pi')+ return null+ const modelID = resolveLanguageModelID({+ providerID,+ modelID: profile.modelID,+ customModelID: profile.customModelID+ })+ const listed = await resolveProviderModel(providerID, modelID)+ const contextWindow =+ listed?.contextWindow ?? (await resolveModelsDevModel(providerID, modelID))?.contextWindow+ return contextWindow ? { contextWindow, maxOutputTokens: profile.maxOutputTokens } : null+}++/**+ * Where automatic compaction starts: the window less the whole reply allowance, which providers+ * reserve from the window, and a tenth of the rest for the next message. A reply allowance past+ * half the window counts as half, so some conversation still fits.+ */+export function autoCompactAt({ contextWindow, maxOutputTokens }: ContextLimits): number {+ const reply = Math.min(maxOutputTokens, contextWindow / 2)+ return Math.floor((contextWindow - reply) * 0.9)+}++/** About four characters to a token, for text no request has counted yet. */+const CHARACTERS_PER_TOKEN = 4++/**+ * How many characters of the conversation a summary request may carry: what fits below the+ * automatic threshold, which leaves the summary its reply allowance.+ */+export function summaryBudget(limits: ContextLimits): number {+ return autoCompactAt(limits) * CHARACTERS_PER_TOKEN+}++/** An estimate of the tokens `text` takes, before a request has counted it. */+export function estimatedTokens(text: string): number {+ return Math.ceil(text.length / CHARACTERS_PER_TOKEN)+}++/** The text a message holds, for estimating its tokens. */+function messageText(message: UIMessage): string {+ return message.parts.map((part) => (part.type === 'text' ? part.text : '')).join('')+}++/**+ * What every request carries before any history, its instructions and tools: from the latest+ * reply that opened a context, the conversation's first or the first after a compaction, its+ * first request less the summary and the request it answered.+ */+function requestBaseline(messages: readonly UIMessage[]): number {+ for (let index = messages.length - 1; index >= 1; index--) {+ const first = usageOf(messages[index])?.firstRequestTokens+ const request = messages[index - 1]+ if (first === undefined || request.role !== 'user') continue+ const before = index >= 2 ? messages[index - 2] : undefined+ const summary = before ? compactionOf(before)?.summary : undefined+ if (index > 1 && summary === undefined) continue+ return Math.max(+ 0,+ first - estimatedTokens(messageText(request)) - estimatedTokens(summary ?? '')+ )+ }+ return 0+}++/**+ * The tokens the next request starts from: what the last reply since the latest compaction+ * reported, or, right after a compaction, an estimate of its summary with what every request+ * carries.+ */+export function contextTokensSinceCompaction(messages: readonly UIMessage[]): number | null {+ const since = messagesSinceCompaction(messages)+ const reported = contextTokensOf(since)+ if (reported !== null) return reported+ const compaction = since.at(0) ? compactionOf(since[0]) : null+ if (!compaction) return null+ return requestBaseline(messages) + estimatedTokens(compaction.summary)+}++/** How full the Design model's context is for `messages`, for the chat's context meter. */+export function useChatContext(messages: Ref<readonly UIMessage[]>) {+ const limits = computedAsync(+ () => {+ // Read before the await, so the meter follows a change of model.+ void designModelProfile.value?.modelID+ void designModelProfile.value?.customModelID+ void designModelConnection.value?.providerID+ return designContextLimits()+ },+ null,+ { onError: () => undefined }+ )+ const used = computed(() => contextTokensSinceCompaction(messages.value))+ const ratio = computed(() =>+ limits.value && used.value !== null ? used.value / limits.value.contextWindow : null+ )+ const compactsAt = computed(() => (limits.value ? autoCompactAt(limits.value) : null))+ return { limits, used, ratio, compactsAt }+}diff --git a/src/app/ai/chat/compaction/marker.ts b/src/app/ai/chat/compaction/marker.tsnew file mode 100644index 000000000..975371d4c--- /dev/null+++ b/src/app/ai/chat/compaction/marker.ts@@ -0,0 +1,105 @@+import { generateId, type UIMessage } from 'ai'+import * as v from 'valibot'++import { messageMetadata } from '@/app/ai/chat/metadata'++/**+ * A compaction: the summary that stands for the conversation before it, whether the person or+ * the context filling up asked for it, and what the conversation held when it ran. An agent+ * that keeps its own context, such as Pi, compacts it there and may report no summary; its+ * compaction is only drawn, and the chat's own requests read past it.+ */+const compactionSchema = v.object({+ summary: v.string(),+ trigger: v.picklist(['manual', 'auto']),+ tokensBefore: v.nullable(v.number()),+ agent: v.optional(v.literal(true))+})++export type Compaction = v.InferOutput<typeof compactionSchema>++/**+ * Compactions that ran between a reply's steps, kept on the reply in the order they ran, each+ * with the step its kept part starts from. A long reply can compact more than once.+ */+const stepCompactionsSchema = v.array(v.object({ ...compactionSchema.entries, step: v.number() }))++export type StepCompaction = v.InferOutput<typeof stepCompactionsSchema>[number]++export function compactionOf(message: UIMessage): Compaction | null {+ const parsed = v.safeParse(compactionSchema, messageMetadata(message).compaction)+ return parsed.success ? parsed.output : null+}++/** What the model reads in place of the conversation a compaction summarized. */+export function summaryText(summary: string): string {+ return `The conversation so far, summarized when it was compacted:\n\n${summary}`+}++/**+ * The message a compaction adds to the conversation. The transcript draws it as a divider; the+ * model reads its text as the conversation so far, so a backend that knows nothing of+ * compaction still gets the summary.+ */+export function compactionMessage(compaction: Compaction, id = generateId()): UIMessage {+ return {+ id,+ role: 'user',+ parts: [{ type: 'text', text: summaryText(compaction.summary) }],+ metadata: { compaction }+ }+}++/** The divider for a compaction an agent ran in its own context and reported no summary of. */+export function agentCompactionMessage(trigger: Compaction['trigger']): UIMessage {+ const compaction: Compaction = { summary: '', trigger, tokensBefore: null, agent: true }+ return { id: generateId(), role: 'user', parts: [], metadata: { compaction } }+}++/** Whether the message is a compaction's summary, which a model reads. */+function summarizes(message: UIMessage): boolean {+ const compaction = compactionOf(message)+ return (compaction !== null && !compaction.agent) || replyCompactions(message).length > 0+}++/** Where the reply's `step`th step starts, each with a `step-start` part; its end past the last. */+function stepStart(reply: UIMessage, step: number): number {+ let seen = 0+ const at = reply.parts.findIndex((part) => part.type === 'step-start' && seen++ === step)+ return at === -1 ? reply.parts.length : at+}++/** The reply's parts from its `from`th step to before its `to`th, or to its end. */+export function replySteps(reply: UIMessage, from: number, to?: number): UIMessage['parts'] {+ return reply.parts.slice(+ stepStart(reply, from),+ to === undefined ? undefined : stepStart(reply, to)+ )+}++/** The compactions that ran between the reply's steps, oldest first. */+export function replyCompactions(message: UIMessage): StepCompaction[] {+ if (message.role !== 'assistant') return []+ const parsed = v.safeParse(stepCompactionsSchema, messageMetadata(message).compactions)+ return parsed.success ? parsed.output : []+}++/**+ * The messages a model reads: from the latest compaction on, its summary standing for everything+ * before it, and for one that ran within a reply, the reply's steps after its latest. The person still+ * sees the whole conversation.+ */+export function messagesSinceCompaction(messages: readonly UIMessage[]): UIMessage[] {+ // An agent's own compaction holds nothing for a model to read.+ const read = messages.filter((message) => !compactionOf(message)?.agent)+ const at = read.findLastIndex(summarizes)+ if (at === -1) return read+ const message = read[at]+ const compaction = replyCompactions(message).at(-1)+ if (!compaction) return read.slice(at)+ return [+ compactionMessage(compaction, `${message.id}-summary`),+ { ...message, parts: replySteps(message, compaction.step) },+ ...read.slice(at + 1)+ ]+}diff --git a/src/app/ai/chat/compaction/prompt.md b/src/app/ai/chat/compaction/prompt.mdnew file mode 100644index 000000000..a448bad31--- /dev/null+++ b/src/app/ai/chat/compaction/prompt.md@@ -0,0 +1,10 @@+You are compacting a conversation between a person and a design assistant working in OpenPencil, so the assistant can continue with a summary in place of the messages. Write the summary the assistant will read as everything that came before.++Keep what the assistant needs to continue:++- What the person asked for, in their words where it matters, including preferences and corrections they gave.+- The current state of the design: pages, frames, and layers the assistant created or changed, by name and ID, with the decisions behind them such as sizes, colors, fonts, spacing, and variables.+- What is done, what is in progress, and what the person asked for that is not done yet.+- Problems found and how they were solved, so they are not repeated.++Leave out tool output, images, and exploration that led nowhere. Do not invent anything the conversation does not say. Write plain Markdown: short headings and bullets, no preamble.diff --git a/src/app/ai/chat/compaction/steps.ts b/src/app/ai/chat/compaction/steps.tsnew file mode 100644index 000000000..0d57ba46d--- /dev/null+++ b/src/app/ai/chat/compaction/steps.ts@@ -0,0 +1,109 @@+import type { LanguageModel, LanguageModelUsage, ModelMessage, UIMessage } from 'ai'++import { compactAutomatically } from '@/app/ai/chat/preferences'+import { createDeferred } from '@/app/runtime/deferred'++import { autoCompactAt, designContextLimits, summaryBudget, type ContextLimits } from './limits'+import { compactionOf, summaryText, type StepCompaction } from './marker'+import { summarizeModelMessages } from './summarize'++/** The model's limits, or null when they cannot be read or the reply is stopped first. */+async function readLimits(+ contextLimits: () => Promise<ContextLimits | null>,+ signal: AbortSignal | undefined+): Promise<ContextLimits | null> {+ const lookup = contextLimits().catch(() => null)+ if (!signal) return lookup+ if (signal.aborted) return null+ // A stalled catalog fetch must not hold a stopped reply open.+ const stopped = createDeferred<null>()+ const stop = () => stopped.resolve(null)+ signal.addEventListener('abort', stop, { once: true })+ try {+ return await Promise.race([lookup, stopped.promise])+ } finally {+ signal.removeEventListener('abort', stop)+ }+}++interface StepState {+ stepNumber: number+ steps: readonly { usage: LanguageModelUsage }[]+ messages: ModelMessage[]+}++/**+ * Compaction between the steps of one reply, for a long run whose requests fill the context+ * before it ends. The last step's call and results stay for the model to go on from, and+ * everything before them becomes a summary. The reply records where it was compacted, which+ * the transcript draws and later requests start from.+ */+export function createStepCompaction(+ model: LanguageModel,+ contextLimits: () => Promise<ContextLimits | null> = designContextLimits+) {+ let limits: ContextLimits | null = null+ let abortSignal: AbortSignal | undefined+ let summaryFirst = false+ /** The reply's compactions so far; the metadata carries the whole list, which replaces the last. */+ let compactions: StepCompaction[] = []+ /** Whether the reply has yet to record the latest; it goes with the next step's start. */+ let unrecorded = false++ /** Before a reply: whether it may compact, read once, and what its request starts with. */+ async function begin(sent: readonly UIMessage[], signal: AbortSignal | undefined) {+ limits = compactAutomatically.value ? await readLimits(contextLimits, signal) : null+ abortSignal = signal+ const first = sent.at(0)+ summaryFirst = first !== undefined && compactionOf(first) !== null+ compactions = []+ unrecorded = false+ }++ /** The step's messages, compacted when the last step's request passed the threshold. */+ async function prepareStep({ stepNumber, steps, messages }: StepState) {+ const usage = steps.at(-1)?.usage+ if (!limits || stepNumber === 0 || usage?.inputTokens === undefined) return undefined+ const held = usage.inputTokens + (usage.outputTokens ?? 0)+ if (held < autoCompactAt(limits)) return undefined+ const last = messages.findLastIndex((message) => message.role === 'assistant')+ if (last <= 0) return undefined+ let summary: string+ try {+ summary = await summarizeModelMessages(messages.slice(0, last), {+ model,+ summaryFirst,+ budget: summaryBudget(limits),+ abortSignal+ })+ } catch {+ // The step goes on uncompacted; a request that then overflows fails as any other would.+ return undefined+ }+ summaryFirst = true+ compactions = [+ ...compactions,+ { summary, trigger: 'auto', tokensBefore: held, step: stepNumber - 1 }+ ]+ unrecorded = true+ return {+ messages: [+ // Shaped as the summary message converts, so a saved trace rebuilds this request.+ {+ role: 'user',+ content: [{ type: 'text', text: summaryText(summary) }]+ } satisfies ModelMessage,+ ...messages.slice(last)+ ]+ }+ }++ /** The reply's metadata at a step's start, carrying a compaction made before it. */+ function metadataFor(part: { type: string }) {+ if (part.type !== 'start-step' || !unrecorded) return undefined+ unrecorded = false+ return { compactions }+ }++ return { begin, prepareStep, metadataFor }+}diff --git a/src/app/ai/chat/compaction/summarize.ts b/src/app/ai/chat/compaction/summarize.tsnew file mode 100644index 000000000..d489fda97--- /dev/null+++ b/src/app/ai/chat/compaction/summarize.ts@@ -0,0 +1,184 @@+import { convertToModelMessages, generateText } from 'ai'+import type { LanguageModel, ModelMessage, UIMessage } from 'ai'++import { isContextLimitError } from '@/app/ai/chat/failure'++import { compactionOf, messagesSinceCompaction } from './marker'+import prompt from './prompt.md?raw'++/** How much of one tool's input or result the summary request keeps. */+const TOOL_LIMIT = 4000+/** How much of one message's text it keeps: a prompt pasted whole still leaves room. */+const TEXT_LIMIT = 16000+/** How much of the conversation the summary request keeps, with no window known to fit. */+export const SUMMARY_BUDGET = 400_000+/**+ * The budget is counted at about four characters a token; text as dense as one a token, such as+ * Chinese or Japanese, can still overflow, and the request is tried again with a quarter of it.+ */+const DENSE_TEXT_RETRY = 4++/** `value` as text, cut to its start when it is longer than `limit`. */+function shortened(value: unknown, limit: number): string {+ const text = typeof value === 'string' ? value : JSON.stringify(value)+ if (text.length <= limit) return text+ return `${text.slice(0, limit)}… (${text.length - limit} more characters left out)`+}++type ContentPart = Exclude<ModelMessage['content'], string>[number]++/** How much of one message's text, and of one tool's input or result, the summary keeps. */+interface PartLimits {+ text: number+ tool: number+}++const PART_LIMITS: PartLimits = { text: TEXT_LIMIT, tool: TOOL_LIMIT }++/** The shortest a part is cut to, so a message too long for the budget still says something. */+const SHORTEST_PART = 200++/** The part as the summary reads it: no images or files, long text and tool data cut short. */+function boundedPart(part: ContentPart, limits: PartLimits): ContentPart[] {+ switch (part.type) {+ case 'image':+ case 'file':+ return []+ case 'text':+ case 'reasoning':+ return [{ ...part, text: shortened(part.text, limits.text) }]+ case 'tool-call':+ return [{ ...part, input: shortened(part.input, limits.tool) }]+ case 'tool-result': {+ // A result's images are left out, as a message's are; its text stays.+ const output =+ part.output.type === 'content'+ ? { ...part.output, value: part.output.value.filter((item) => item.type === 'text') }+ : part.output+ if (JSON.stringify(output).length <= limits.tool) return [{ ...part, output }]+ const value = output.type === 'text' || output.type === 'json' ? output.value : output+ return [{ ...part, output: { type: 'text', value: shortened(value, limits.tool) } }]+ }+ default:+ return [part]+ }+}++function boundedMessage(message: ModelMessage, limits = PART_LIMITS): ModelMessage {+ if (typeof message.content === 'string')+ return { ...message, content: shortened(message.content, limits.text) } as ModelMessage+ return {+ ...message,+ content: message.content.flatMap((part) => boundedPart(part, limits))+ } as ModelMessage+}++const size = (message: ModelMessage) => JSON.stringify(message).length++/** The message cut shorter, part by part, until it fits `budget` or its parts are at their shortest. */+function fitted(message: ModelMessage, budget: number): ModelMessage {+ let limits = PART_LIMITS+ let bounded = boundedMessage(message, limits)+ while (size(bounded) > budget && limits.tool > SHORTEST_PART) {+ limits = {+ text: Math.max(SHORTEST_PART, Math.floor(limits.text / 2)),+ tool: Math.max(SHORTEST_PART, Math.floor(limits.tool / 2))+ }+ bounded = boundedMessage(message, limits)+ }+ return bounded+}++/**+ * The conversation as the summary request reads it: no images or files, long text, tool inputs,+ * and tool results cut short, and, past `budget` characters, the oldest messages left out but+ * the summary they follow and the newest cut to fit, so a conversation too long for its model+ * can still be summarized.+ * `summaryFirst` says the first message is an earlier compaction's summary.+ */+export function summarySource(+ messages: readonly ModelMessage[],+ { summaryFirst = false, budget = SUMMARY_BUDGET } = {}+): ModelMessage[] {+ const earlier = summaryFirst ? messages.slice(0, 1).map((message) => boundedMessage(message)) : []+ let left = budget - earlier.reduce((total, message) => total + size(message), 0)+ const kept: ModelMessage[] = []+ for (const message of messages.slice(earlier.length).toReversed()) {+ // The newest message stays even past the budget, cut shorter to fit what is left.+ const bounded = kept.length === 0 ? fitted(message, left) : boundedMessage(message)+ left -= size(bounded)+ if (left < 0 && kept.length > 0) break+ kept.unshift(bounded)+ }+ // What is kept starts with a request, as providers expect, and never with a tool result+ // whose call was left out.+ while (earlier.length === 0 && kept.length > 1 && kept[0].role !== 'user') kept.shift()+ while (kept[0]?.role === 'tool') kept.shift()+ return [...earlier, ...kept]+}++export interface SummaryOptions {+ model: LanguageModel+ /** What the person asked the summary to keep or focus on. */+ instructions?: string+ /** How many characters of the conversation the request may carry. */+ budget?: number+ abortSignal?: AbortSignal+}++/**+ * A summary of `messages`, as the model reads them, written by the conversation's own model.+ * Between a reply's steps the conversation is already model messages.+ */+export async function summarizeModelMessages(+ messages: readonly ModelMessage[],+ {+ model,+ instructions,+ budget = SUMMARY_BUDGET,+ abortSignal,+ summaryFirst+ }: SummaryOptions & {+ summaryFirst: boolean+ }+): Promise<string> {+ const ask = instructions?.trim()+ ? `Summarize the conversation above. Also follow these instructions for the summary: ${instructions.trim()}`+ : 'Summarize the conversation above.'+ const request = (within: number) =>+ generateText({+ model,+ system: prompt.trim(),+ messages: [+ ...summarySource(messages, { summaryFirst, budget: within }),+ { role: 'user', content: ask }+ ],+ abortSignal+ })+ const result = await request(budget).catch((error: unknown) => {+ if (!isContextLimitError(error)) throw error+ return request(Math.floor(budget / DENSE_TEXT_RETRY))+ })+ const summary = result.text.trim()+ if (!summary) throw new Error('The model wrote no summary')+ return summary+}++/** A summary of the conversation, from its latest compaction on. */+export async function summarizeConversation(+ messages: readonly UIMessage[],+ options: SummaryOptions+): Promise<string> {+ const since = messagesSinceCompaction(messages)+ // Images and files are left out before conversion, which would otherwise inline them.+ const textual = since.map((message) => ({+ ...message,+ parts: message.parts.filter((part) => part.type !== 'file')+ }))+ const request = await convertToModelMessages(textual, { ignoreIncompleteToolCalls: true })+ const first = since.at(0)+ return summarizeModelMessages(request, {+ ...options,+ summaryFirst: first !== undefined && compactionOf(first) !== null+ })+}diff --git a/src/app/ai/chat/compaction/use.ts b/src/app/ai/chat/compaction/use.tsnew file mode 100644index 000000000..431a08f88--- /dev/null+++ b/src/app/ai/chat/compaction/use.ts@@ -0,0 +1,161 @@+import type { UIMessage } from 'ai'+import { ref, type Ref } from 'vue'++import { compactAutomatically } from '@/app/ai/chat/preferences'+import type { ChatInstance } from '@/app/ai/chat/submission/types'+import { createAIModelRuntime } from '@/app/ai/models/runtime'++import {+ autoCompactAt,+ contextTokensSinceCompaction,+ designContextLimits,+ estimatedTokens,+ summaryBudget+} from './limits'+import { agentCompactionMessage, compactionMessage, type Compaction } from './marker'+import { summarizeConversation } from './summarize'++interface CompactionOptions {+ chat: Ref<ChatInstance | null>+ ensureChat: () => Promise<ChatInstance | null>+ flush?: () => Promise<void>+ /** Asks an agent that keeps its own context, such as Pi, to compact it. */+ compactAgent?: (instructions?: string) => Promise<boolean>+}++interface CompactRequest {+ trigger: Compaction['trigger']+ instructions?: string+ /** Compacts only the messages before this one, which stays after the summary to send again. */+ before?: string+ chat?: ChatInstance+}++/** The chat is replying, so a summary now would cut its reply off from the next request. */+function replying(chat: ChatInstance): boolean {+ return chat.status === 'streaming' || chat.status === 'submitted'+}++/** The chat still starts with `covered`, which no edit or regenerate replaced meanwhile. */+function unchanged(chat: ChatInstance, covered: readonly UIMessage[]): boolean {+ return covered.every((message, index) => chat.messages[index] === message)+}++/**+ * Compacting a conversation: its model summarizes it, and the summary stands for everything+ * before it in later requests. A failed compaction leaves the conversation as it was.+ */+export function useChatCompaction(options: CompactionOptions) {+ const compacting = ref(false)+ /** The last compaction that failed, for its Retry; cleared by the next one. */+ const failed = ref<Omit<CompactRequest, 'chat'> | null>(null)+ let abort: AbortController | null = null+ /** The compaction in progress, which a message sent meanwhile waits for. */+ let pending: Promise<boolean> | null = null++ async function run(request: CompactRequest): Promise<boolean> {+ const target = request.chat ?? options.chat.value ?? (await options.ensureChat())+ if (!target || target.messages.length === 0 || replying(target)) return false+ const runtime = await createAIModelRuntime('design')+ if (runtime?.kind === 'harness' && request.trigger === 'manual')+ return compactAgent(target, request)+ if (runtime?.kind !== 'direct') return false+ const at = request.before+ ? target.messages.findIndex((message) => message.id === request.before)+ : target.messages.length+ if (at <= 0) return false+ const covered = target.messages.slice(0, at)+ failed.value = null+ abort = new AbortController()+ try {+ const limits = await designContextLimits()+ const summary = await summarizeConversation(covered, {+ model: runtime.model,+ instructions: request.instructions,+ budget: limits ? summaryBudget(limits) : undefined,+ abortSignal: abort.signal+ })+ // A conversation switched, replying, or changed meanwhile is no longer the one summarized.+ if (options.chat.value !== target || replying(target) || !unchanged(target, covered))+ return false+ const marker = compactionMessage({+ summary,+ trigger: request.trigger,+ tokensBefore: contextTokensSinceCompaction(covered)+ })+ // Messages added after the summarized ones meanwhile stay after the summary.+ target.messages = [...covered, marker, ...target.messages.slice(at)]+ await options.flush?.().catch(() => undefined)+ return true+ } catch {+ if (!abort.signal.aborted) {+ const { chat: _chat, ...retry } = request+ failed.value = retry+ }+ return false+ } finally {+ abort = null+ }+ }++ /**+ * An agent compacts its own context. Pi reports no summary of a compaction it ran between+ * turns, so the chat draws its own divider once the agent confirms it.+ */+ async function compactAgent(target: ChatInstance, request: CompactRequest): Promise<boolean> {+ if (!options.compactAgent) return false+ failed.value = null+ try {+ if (!(await options.compactAgent(request.instructions))) return false+ // A conversation switched meanwhile keeps its messages as they were.+ if (options.chat.value === target)+ target.messages = [...target.messages, agentCompactionMessage(request.trigger)]+ await options.flush?.().catch(() => undefined)+ return true+ } catch {+ const { chat: _chat, ...retry } = request+ failed.value = retry+ return false+ }+ }++ /**+ * Compacts the conversation; one compaction runs at a time. It shows as compacting from the+ * start, while the chat and its model are still being reached.+ */+ function compact(request: CompactRequest): Promise<boolean> {+ if (pending) return Promise.resolve(false)+ compacting.value = true+ pending = run(request).finally(() => {+ compacting.value = false+ pending = null+ })+ return pending+ }++ /**+ * Before `text` is sent: waits for a compaction in progress, then compacts when the last+ * request since the latest summary, with `text` added, passes the threshold.+ */+ async function compactIfFull(chat: ChatInstance, text: string): Promise<void> {+ if (pending) await pending+ if (!compactAutomatically.value) return+ const used = contextTokensSinceCompaction(chat.messages)+ if (used === null) return+ const limits = await designContextLimits()+ if (limits && used + estimatedTokens(text) >= autoCompactAt(limits))+ await compact({ trigger: 'auto', chat })+ }++ /** Stops a compaction in progress; the conversation stays as it was. */+ function cancel(): void {+ abort?.abort()+ }++ function retry(): Promise<boolean> {+ const last = failed.value+ return last ? compact(last) : Promise.resolve(false)+ }++ return { compacting, failed, compact, compactIfFull, cancel, retry }+}diff --git a/src/app/ai/chat/failure.ts b/src/app/ai/chat/failure.tsindex 1affe33a1..a7410b56a 100644--- a/src/app/ai/chat/failure.ts+++ b/src/app/ai/chat/failure.ts@@ -5,6 +5,7 @@ export type AIChatFailureReason =| 'forbidden'| 'insufficient-credit'| 'cloud-credits-exhausted'+ | 'context-limit'| 'model-not-found'| 'network'| 'output-limit'@@ -75,6 +76,26 @@ export function isInsufficientCreditError(error: unknown): boolean {].some((phrase) => text.includes(phrase))}+/**+ * The request held more than the model reads: HTTP 413, or the code and wording providers give a+ * prompt past the context window (OpenAI `context_length_exceeded`, Anthropic "prompt is too+ * long", Gemini's input token count).+ */+export function isContextLimitError(error: unknown): boolean {+ if (providerErrorStatus(error) === 413) return true+ const body = APICallError.isInstance(error) ? (error.responseBody ?? '') : ''+ const text = `${normalizedErrorText(error)} ${body.toLowerCase()}`+ return [+ 'context_length_exceeded',+ 'prompt is too long',+ 'maximum context length',+ 'context window',+ 'input token count',+ 'too many tokens',+ 'request_too_large'+ ].some((phrase) => text.includes(phrase))+}+function statusFailureReason(status: number | null): AIChatFailureReason | null {if (status === 401) return 'authentication'if (status === 402) return 'insufficient-credit'@@ -86,6 +107,7 @@ function statusFailureReason(status: number | null): AIChatFailureReason | null}function failureReason(error: unknown): AIChatFailureReason {+ if (isContextLimitError(error)) return 'context-limit'const statusReason = statusFailureReason(providerErrorStatus(error))if (statusReason) return statusReasonif (isInsufficientCreditError(error)) return 'insufficient-credit'diff --git a/src/app/ai/chat/metadata.ts b/src/app/ai/chat/metadata.tsindex 4e7927739..65db8f317 100644--- a/src/app/ai/chat/metadata.ts+++ b/src/app/ai/chat/metadata.ts@@ -59,3 +59,32 @@ export function undoOf(message: UIMessage): ReplyUndo | null {export function withUndo(message: UIMessage, undo: ReplyUndo): UIMessage {return withMetadata(message, { undo })}++/**+ * The tokens a reply used: what its requests read and wrote in all, and what its last request+ * held, prompt and answer, which the next request starts from.+ */+const replyUsageSchema = v.object({+ contextTokens: v.number(),+ /** What its first request held: the instructions and tools every request carries, and history. */+ firstRequestTokens: v.optional(v.number()),+ inputTokens: v.number(),+ outputTokens: v.number(),+ cacheReadTokens: v.nullable(v.number())+})++export type ReplyUsage = v.InferOutput<typeof replyUsageSchema>++export function usageOf(message: UIMessage): ReplyUsage | null {+ const parsed = v.safeParse(replyUsageSchema, messageMetadata(message).usage)+ return parsed.success ? parsed.output : null+}++/** What the conversation's last request held, from the latest reply that reported its usage. */+export function contextTokensOf(messages: readonly UIMessage[]): number | null {+ for (let index = messages.length - 1; index >= 0; index--) {+ const usage = usageOf(messages[index])+ if (usage) return usage.contextTokens+ }+ return null+}diff --git a/src/app/ai/chat/preferences.ts b/src/app/ai/chat/preferences.tsindex 9e95b7bda..dcbbf80f5 100644--- a/src/app/ai/chat/preferences.ts+++ b/src/app/ai/chat/preferences.ts@@ -4,7 +4,8 @@ import { resolveAgentStepLimit } from '@/app/ai/reply/step-limit'import {appPreferences,type ChangePreviewSize,- type ReasoningDisplay+ type ReasoningDisplay,+ type TokenUsageDisplay} from '@/app/settings/preferences/store'export const maxAgentSteps = computed({@@ -36,3 +37,23 @@ export const changePreviewSize = computed({}}})++export const compactAutomatically = computed({+ get: () => appPreferences.value.chat.compactAutomatically,+ set: (compactAutomatically: boolean) => {+ appPreferences.value = {+ ...appPreferences.value,+ chat: { ...appPreferences.value.chat, compactAutomatically }+ }+ }+})++export const tokenUsageDisplay = computed({+ get: () => appPreferences.value.chat.tokenUsage,+ set: (tokenUsage: TokenUsageDisplay) => {+ appPreferences.value = {+ ...appPreferences.value,+ chat: { ...appPreferences.value.chat, tokenUsage }+ }+ }+})diff --git a/src/app/ai/chat/references/candidates.ts b/src/app/ai/chat/references/candidates.tsindex 6196a2c28..de46d5849 100644--- a/src/app/ai/chat/references/candidates.ts+++ b/src/app/ai/chat/references/candidates.ts@@ -3,9 +3,10 @@ import { compact } from 'es-toolkit'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import type { AgentCommand } from '@/app/ai/agents/acp/commands'-import { runnableSkills } from '@/app/ai/skills/invoke'+import { runnableSkills, skillCommand } from '@/app/ai/skills/invoke'import type { Skill } from '@/app/ai/skills/types'+import { commandLink } from './command'import type { ChatReference } from './link'/** Matching layers past this many are left out of `@` completions; typing more narrows them. */@@ -84,23 +85,33 @@ export function referenceCandidates(]}-/** What `/` offers: an ACP agent's own commands, or else the skills the user can run. */-export function commandCandidates(- agentCommands: readonly AgentCommand[] | null,+/** A command as `/` offers it, from an ACP agent or the chat itself. */+function commandCandidate(command: AgentCommand): CommandCandidate {+ return {+ kind: 'agent',+ label: `/${command.name}`,+ detail: command.description,+ insert: `${commandLink(command.name)} `+ }+}++/** What `/` offers with an ACP agent: its own commands, which run its own skills too. */+export function agentCommandCandidates(commands: readonly AgentCommand[]): CommandCandidate[] {+ return commands.map(commandCandidate)+}++/** What `/` offers otherwise: the chat's own commands, such as `/compact`, then the user's skills. */+export function chatCommandCandidates(+ commands: readonly AgentCommand[],skills: readonly Skill[]): CommandCandidate[] {- if (agentCommands) {- return agentCommands.map((command) => ({- kind: 'agent' as const,- label: `/${command.name}`,- detail: command.description,- insert: `/${command.name} `+ return [+ ...commands.map(commandCandidate),+ ...runnableSkills(skills).map((skill) => ({+ kind: 'skill' as const,+ label: `/${skillCommand(skill.name)}`,+ detail: skill.description,+ insert: `${commandLink(skillCommand(skill.name))} `}))- }- return runnableSkills(skills).map((skill) => ({- kind: 'skill' as const,- label: `/skill:${skill.name}`,- detail: skill.description,- insert: `/skill:${skill.name} `- }))+ ]}diff --git a/src/app/ai/chat/references/command.ts b/src/app/ai/chat/references/command.tsnew file mode 100644index 000000000..c62138620--- /dev/null+++ b/src/app/ai/chat/references/command.ts@@ -0,0 +1,38 @@+import { findReferences, referenceLink } from './link'++/**+ * Commands chosen from `/`, such as `/compact` or `/skill:grid`: a reference of the `command`+ * kind, so the composer shows a chip and the chat reads the command from the link, never by+ * matching what was typed.+ */+export function commandLink(name: string): string {+ return referenceLink({ kind: 'command', id: name, label: `/${name}` })+}++export interface LeadingCommand {+ name: string+ /** What follows the command, such as what a summary should keep. */+ rest: string+}++/** The command a message starts with, and the text after it; null when it starts with none. */+export function leadingCommand(text: string): LeadingCommand | null {+ const first = findReferences(text).at(0)+ if (first?.reference.kind !== 'command' || text.slice(0, first.start).trim()) return null+ return { name: first.reference.id, rest: text.slice(first.end).trim() }+}++/**+ * The text with each command written out as typed, for whoever reads the message: agents+ * and Pi run their own commands from the text, and a model reads `/skill:grid` as written.+ */+export function commandsAsText(text: string): string {+ let result = ''+ let at = 0+ for (const { reference, start, end } of findReferences(text)) {+ if (reference.kind !== 'command') continue+ result += text.slice(at, start) + reference.label+ at = end+ }+ return result + text.slice(at)+}diff --git a/src/app/ai/chat/references/link.ts b/src/app/ai/chat/references/link.tsindex 688831bb2..8ad694171 100644--- a/src/app/ai/chat/references/link.ts+++ b/src/app/ai/chat/references/link.ts@@ -1,13 +1,14 @@/*** References to things in OpenPencil, written in chat text as Markdown links with the* `openpencil:` scheme: `[Hero](openpencil://node/12:34)`. People insert them from the- * composer and the model cites what it touched with them; the chat shows them as chips.+ * composer and the model cites what it touched with them; the chat shows them as chips. A+ * command chosen from `/` is one too, named by the command (`./command.ts`).*/-export type ChatReferenceKind = 'node' | 'page' | 'skill'+export type ChatReferenceKind = 'node' | 'page' | 'skill' | 'command'export interface ChatReference {kind: ChatReferenceKind- /** A node or page ID, or a skill's name. */+ /** A node or page ID, a skill's name, or a command's name without its `/`. */id: string/** The name when the reference was written, shown when the target is gone. */label: string@@ -20,7 +21,7 @@ export interface ChatReferenceMatch {}const SCHEME = 'openpencil://'-const KINDS: ReadonlySet<string> = new Set<ChatReferenceKind>(['node', 'page', 'skill'])+const KINDS: ReadonlySet<string> = new Set<ChatReferenceKind>(['node', 'page', 'skill', 'command'])/** A link whose label holds no unescaped `]` or line break and whose URL has no space. */const LINK = /\[((?:\\.|[^\]\\\n])*)\]\(openpencil:\/\/([a-z]+)\/([^)\s]+)\)/gdiff --git a/src/app/ai/chat/references/resolve.ts b/src/app/ai/chat/references/resolve.tsindex edc4b7797..9e52b1dab 100644--- a/src/app/ai/chat/references/resolve.ts+++ b/src/app/ai/chat/references/resolve.ts@@ -29,6 +29,9 @@ export function resolveReference(const present = skillNames.has(reference.id)return { ...reference, name: reference.id, present, node: null }}+ // A command names nothing to show; it reads as written.+ if (reference.kind === 'command')+ return { ...reference, name: reference.label, present: true, node: null }const node = store?.graph.getNode(reference.id)const fits = reference.kind === 'page' ? node?.type === 'CANVAS' : node && node.type !== 'CANVAS'if (!node || !fits) return { ...reference, name: reference.label, present: false, node: null }@@ -42,6 +45,7 @@ export function resolveReference(/** Shows what a reference names: a layer on its page, a page, or a skill in Settings. */export async function openReference(store: EditorStore, reference: ChatReference): Promise<void> {+ if (reference.kind === 'command') returnif (reference.kind === 'skill') requestSkillSettings(reference.id)else if (reference.kind === 'page') await store.switchPage(reference.id)else await focusNodesOnTheirPage(store, [reference.id])diff --git a/src/app/ai/chat/session.ts b/src/app/ai/chat/session.tsindex dfc1b102b..d1d9ec9c4 100644--- a/src/app/ai/chat/session.ts+++ b/src/app/ai/chat/session.ts@@ -102,7 +102,7 @@ export function createChatSessionManager({const currentChatMessages = new WeakMap<EditorStore, UIMessage[]>()let chat: Chat<UIMessage> | null = nulllet acpTransportInstance: { destroy(): Promise<void> } | null = null- let harnessTransportInstance: { stop(): Promise<void> } | null = null+ let harnessTransportInstance: Pick<HarnessChatTransport, 'stop' | 'compact'> | null = nulllet overrideTransport: (() => ChatTransport<UIMessage>) | null = nulllet activeProviderError: unknown = nullconst runRecorder = createRunRecorder(createTraceStore())@@ -328,5 +328,18 @@ export function createChatSessionManager({markTransportDirty()}- return { ensureChat, resetChat, markTransportDirty, setOverrideTransport, failure, clearFailure }+ /** Asks the chat's agent to compact its own context; false when it has none to compact yet. */+ async function compactAgent(instructions?: string): Promise<boolean> {+ return (await harnessTransportInstance?.compact(instructions)) ?? false+ }++ return {+ ensureChat,+ resetChat,+ markTransportDirty,+ setOverrideTransport,+ compactAgent,+ failure,+ clearFailure+ }}diff --git a/src/app/ai/chat/submission/text.ts b/src/app/ai/chat/submission/text.tsnew file mode 100644index 000000000..9d8d839f3--- /dev/null+++ b/src/app/ai/chat/submission/text.ts@@ -0,0 +1,22 @@+import { setVisibleMessageText } from '@/app/ai/chat/presentation'+import type { ChatInstance, ChatSubmission } from '@/app/ai/chat/submission/types'++type WithTurn = (chat: ChatInstance, send: () => Promise<void>) => Promise<void>++/** Sends a message without attachments; the chat adds it at once and shows the written text. */+export async function sendText(+ chat: ChatInstance,+ submission: ChatSubmission,+ dispatch: () => void,+ withTurn: WithTurn+): Promise<void> {+ const previousIds = new Set(chat.messages.map((message) => message.id))+ dispatch()+ await withTurn(chat, () =>+ chat.sendMessage({ text: submission.modelText }).catch(() => undefined)+ )+ const message = chat.messages.find(+ (candidate) => candidate.role === 'user' && !previousIds.has(candidate.id)+ )+ if (message) setVisibleMessageText(message.id, submission.displayText)+}diff --git a/src/app/ai/chat/submission/use.ts b/src/app/ai/chat/submission/use.tsindex e359e711c..29b6e3291 100644--- a/src/app/ai/chat/submission/use.ts+++ b/src/app/ai/chat/submission/use.ts@@ -1,4 +1,4 @@-import { computed, markRaw, ref, type Ref } from 'vue'+import { computed, markRaw, ref, shallowReadonly, shallowRef, type Ref } from 'vue'import { designMessageWithImageFindings } from '@/app/ai/attachment/image/analyze'import { revokeImagePreviewURL } from '@/app/ai/attachment/image/prepare'@@ -13,10 +13,12 @@ import {} from '@/app/ai/attachment/presentation/store'import { appendSkillContext } from '@/app/ai/chat/context'import { setVisibleMessageText } from '@/app/ai/chat/presentation'+import { commandsAsText } from '@/app/ai/chat/references/command'import { mentionedNodes } from '@/app/ai/chat/references/nodes'import { reportSubmissionError, type SubmissionErrorOptions } from '@/app/ai/chat/submission/errors'import { prepareSubmittedImages } from '@/app/ai/chat/submission/images'import { chatToResend } from '@/app/ai/chat/submission/resend'+import { sendText } from '@/app/ai/chat/submission/text'import type { ChatInstance, ChatSubmission } from '@/app/ai/chat/submission/types'import { restoreTurn, revertTurn } from '@/app/ai/reply/turns'import { useUndoRecords } from '@/app/ai/reply/undo'@@ -29,10 +31,13 @@ interface SubmissionOptions extends SubmissionErrorOptions {flush?: () => Promise<void>clearFailure: () => voidgetEditor: () => EditorStore+ prepare?: (chat: ChatInstance, text: string) => Promise<void> // e.g. compacting before `text`}export function useChatSubmission(options: SubmissionOptions) {const isPreparingAttachments = ref(false)+ /** A message sent but not in the chat yet, shown while the chat connects or compacts first. */+ const sending = shallowRef<ChatSubmission | null>(null)let operationVersion = 0const undone = useUndoRecords(options)@@ -50,22 +55,6 @@ export function useChatSubmission(options: SubmissionOptions) {await options.flush?.().catch(() => undefined)}- async function sendText(- currentChat: ChatInstance,- submission: ChatSubmission,- dispatch: () => void- ): Promise<void> {- const previousIds = new Set(currentChat.messages.map((message) => message.id))- dispatch()- await withTurn(currentChat, () =>- currentChat.sendMessage({ text: submission.modelText }).catch(() => undefined)- )- const message = currentChat.messages.find(- (candidate) => candidate.role === 'user' && !previousIds.has(candidate.id)- )- if (message) setVisibleMessageText(message.id, submission.displayText)- }-/*** Shows the message at once and sends it once its images are prepared. A failure before it* is sent takes the message back out, so the composer can restore the draft.@@ -150,6 +139,7 @@ export function useChatSubmission(options: SubmissionOptions) {const dispatch = () => {sent = true}+ sending.value = submissionisPreparingAttachments.value = submission.images.length > 0options.clearFailure()try {@@ -163,9 +153,13 @@ export function useChatSubmission(options: SubmissionOptions) {}const note = undone.note(submission.modelText, currentChat.messages)const noted = { ...submission, modelText: appendSkillContext(note.text, skill) }+ await options.prepare?.(currentChat, noted.modelText)+ if (version !== operationVersion) return falseconst previousIds = new Set(currentChat.messages.map((message) => message.id))+ // Both ways of sending add the message to the chat at once, which shows it from then on.+ sending.value = nullif (submission.images.length === 0 && submission.nodes.length === 0) {- await sendText(currentChat, noted, dispatch)+ await sendText(currentChat, noted, dispatch, withTurn)} else {await sendAttachments(currentChat, noted, version, dispatch)}@@ -179,7 +173,10 @@ export function useChatSubmission(options: SubmissionOptions) {return sent} finally {await options.flush?.().catch(() => undefined)- if (version === operationVersion) isPreparingAttachments.value = false+ if (version === operationVersion) {+ isPreparingAttachments.value = false+ sending.value = null+ }}}@@ -216,7 +213,7 @@ export function useChatSubmission(options: SubmissionOptions) {options.clearFailure()for (const message of later) if (message.role === 'assistant') revertTurn(message.id)// Replies after the edited message are replaced; what it reported needs a new report.- const note = undone.note(trimmed, currentChat.messages.slice(0, index))+ const note = undone.note(commandsAsText(trimmed), currentChat.messages.slice(0, index))const skill = await invokedSkill(trimmed)setVisibleMessageText(messageId, trimmed)// The layers the edited text mentions replace the previews the message showed.@@ -240,12 +237,14 @@ export function useChatSubmission(options: SubmissionOptions) {function cancel(): void {operationVersion += 1isPreparingAttachments.value = false+ sending.value = null}const busy = computed(() => isPreparingAttachments.value)return {busy,+ sending: shallowReadonly(sending),cancel,stop: () => options.chat.value?.stop(),submit,diff --git a/src/app/ai/chat/tool-calls/display.ts b/src/app/ai/chat/tool-calls/display.tsindex 0198082d0..04fdcec4b 100644--- a/src/app/ai/chat/tool-calls/display.ts+++ b/src/app/ai/chat/tool-calls/display.ts@@ -130,13 +130,26 @@ export function toolHasInput(part: ToolCallPart): boolean {export type MessagePartGroup =| { kind: 'part'; part: ChatMessagePart; index: number }| { kind: 'tools'; parts: { part: ToolCallPart; index: number }[] }--/** Consecutive tool calls form one group, so a long run can collapse into a single row. */-export function groupMessageParts(parts: readonly ChatMessagePart[]): MessagePartGroup[] {+ | { kind: 'compaction'; index: number; compaction: number }++/**+ * Consecutive tool calls form one group, so a long run can collapse into a single row. Each+ * compaction within the reply, before a step in `compactedSteps`, sits between groups and names+ * its place in that list.+ */+export function groupMessageParts(+ parts: readonly ChatMessagePart[],+ compactedSteps: readonly number[] = []+): MessagePartGroup[] {const groups: MessagePartGroup[] = []+ let step = 0parts.forEach((part, index) => {// Step boundaries are not rendered, so they must not split a run of calls.- if (part.type === 'step-start') return+ if (part.type === 'step-start') {+ const compaction = compactedSteps.indexOf(step++)+ if (compaction !== -1) groups.push({ kind: 'compaction', index, compaction })+ return+ }if (!isToolUIPart(part)) {groups.push({ kind: 'part', part, index })returndiff --git a/src/app/ai/chat/trace/rebuild.ts b/src/app/ai/chat/trace/rebuild.tsindex 067f49642..17074ee3f 100644--- a/src/app/ai/chat/trace/rebuild.ts+++ b/src/app/ai/chat/trace/rebuild.ts@@ -1,22 +1,21 @@import { convertToModelMessages } from 'ai'import type { ModelMessage, ToolSet, UIMessage } from 'ai'+import {+ compactionMessage,+ messagesSinceCompaction,+ replyCompactions,+ replySteps+} from '@/app/ai/chat/compaction/marker'import { requestMessages } from '@/app/ai/chat/history/continuation'import { fingerprint } from './fingerprint'import type { RunTrace } from './types'-/** The reply's parts before its `step`th step, each of which starts with a `step-start` part. */-function stepsBefore(reply: UIMessage, step: number): UIMessage | null {- let seen = 0- const end = reply.parts.findIndex((part) => part.type === 'step-start' && seen++ === step)- const parts = end === -1 ? reply.parts : reply.parts.slice(0, end)- return parts.length > 0 ? { ...reply, parts } : null-}-/*** The messages a run's `step` sent to the model, rebuilt from the conversation: what the run- * sent, as `requestMessages` prepared it, then the reply's earlier steps.+ * sent, as `requestMessages` and compaction prepared it, then the reply's earlier steps. After+ * a compaction within the reply, the request starts again from the latest summary before it.*/export async function rebuildStepMessages(conversation: UIMessage[],@@ -25,10 +24,15 @@ export async function rebuildStepMessages(tools: ToolSet): Promise<ModelMessage[]> {const through = conversation.findIndex((message) => message.id === run.input.through)- const sent = requestMessages(conversation.slice(0, through + 1))+ const sent = messagesSinceCompaction(requestMessages(conversation.slice(0, through + 1)))const reply = conversation.at(through + 1)- const earlier = reply?.role === 'assistant' && step > 0 ? stepsBefore(reply, step) : null- return convertToModelMessages(earlier ? [...sent, earlier] : sent, { tools })+ if (reply?.role !== 'assistant' || step === 0) return convertToModelMessages(sent, { tools })+ const resumed = replyCompactions(reply).findLast((compaction) => compaction.step < step)+ const earlier = { ...reply, parts: replySteps(reply, resumed?.step ?? 0, step) }+ const before = resumed ? [compactionMessage(resumed, `${reply.id}-summary`)] : sent+ return convertToModelMessages(earlier.parts.length > 0 ? [...before, earlier] : before, {+ tools+ })}/** Whether the rebuilt request of a run's step is the one the model received. */diff --git a/src/app/ai/chat/use.ts b/src/app/ai/chat/use.tsindex abbe44123..8f3ea5ff1 100644--- a/src/app/ai/chat/use.ts+++ b/src/app/ai/chat/use.ts@@ -83,6 +83,7 @@ export function useAIChat() {history,ensureChat: history.ensureChat,resetChat: history.newChat,+ compactAgent: chatSession.compactAgent,chatFailure: chatSession.failure,clearChatFailure: chatSession.clearFailure}diff --git a/src/app/ai/models/catalog/index.ts b/src/app/ai/models/catalog/index.tsindex c0994ce98..42b75cfb6 100644--- a/src/app/ai/models/catalog/index.ts+++ b/src/app/ai/models/catalog/index.ts@@ -30,7 +30,7 @@ type ModelsDevModel = {status?: unknownrelease_date?: unknownmodalities?: { output?: unknown }- limit?: { output?: unknown }+ limit?: { output?: unknown; context?: unknown }}type ModelsDevProvider = {@@ -47,7 +47,9 @@ const modelsDevCatalogSchema = v.record(v.string(),v.looseObject({modalities: v.optional(v.looseObject({ output: v.optional(v.unknown()) })),- limit: v.optional(v.looseObject({ output: v.optional(v.unknown()) }))+ limit: v.optional(+ v.looseObject({ output: v.optional(v.unknown()), context: v.optional(v.unknown()) })+ )})))@@ -73,6 +75,10 @@ function normalizeModel(id: string, model: ModelsDevModel): ModelOption {if (typeof output === 'number' && Number.isFinite(output)) {normalized.recommendedMaxOutputTokens = Math.min(128_000, Math.max(1024, output))}+ const context = model.limit?.context+ if (typeof context === 'number' && Number.isFinite(context) && context > 0) {+ normalized.contextWindow = context+ }if (typeof model.release_date === 'string') normalized.releaseDate = model.release_datereturn normalized}@@ -118,7 +124,8 @@ function mergeCuratedModels(curated: ModelOption[], catalog: ModelOption[]): Mod...model,capabilities: catalogById.get(model.id)?.capabilities ?? model.capabilities,recommendedMaxOutputTokens:- catalogById.get(model.id)?.recommendedMaxOutputTokens ?? model.recommendedMaxOutputTokens+ catalogById.get(model.id)?.recommendedMaxOutputTokens ?? model.recommendedMaxOutputTokens,+ contextWindow: catalogById.get(model.id)?.contextWindow ?? model.contextWindow}))const curatedIds = new Set(curated.map((model) => model.id))const remaining = catalogdiff --git a/src/app/ai/models/catalog/schema.ts b/src/app/ai/models/catalog/schema.tsindex 97eb61070..40c6ce945 100644--- a/src/app/ai/models/catalog/schema.ts+++ b/src/app/ai/models/catalog/schema.ts@@ -11,6 +11,7 @@ export const modelOptionsSchema = v.array(tag: v.optional(v.string()),capabilities: v.optional(v.array(v.picklist(['tools', 'vision']))),recommendedMaxOutputTokens: v.optional(v.number()),+ contextWindow: v.optional(v.pipe(v.number(), v.minValue(1))),releaseDate: v.optional(v.string()),status: v.optional(v.picklist(['active', 'beta', 'deprecated'])),minReasoningEffort: v.optional(v.picklist(REASONING_EFFORTS))diff --git a/src/app/ai/models/reasoning/floors.ts b/src/app/ai/models/reasoning/floors.tsindex d3b7a770d..fc4c298d8 100644--- a/src/app/ai/models/reasoning/floors.ts+++ b/src/app/ai/models/reasoning/floors.ts@@ -11,6 +11,7 @@ const openRouterModelSchema = v.looseObject({id: v.optional(v.unknown()),name: v.optional(v.unknown()),supported_parameters: v.optional(v.unknown()),+ context_length: v.optional(v.unknown()),architecture: v.nullish(v.looseObject({ input_modalities: v.optional(v.unknown()) })),top_provider: v.nullish(v.looseObject({ max_completion_tokens: v.optional(v.unknown()) })),reasoning: v.nullish(@@ -74,6 +75,10 @@ export function normalizeOpenRouterModel(model: OpenRouterModel): ModelOption |if (typeof maxOutputTokens === 'number' && Number.isFinite(maxOutputTokens)) {normalized.recommendedMaxOutputTokens = Math.min(128_000, Math.max(1024, maxOutputTokens))}+ const context = model.context_length+ if (typeof context === 'number' && Number.isFinite(context) && context > 0) {+ normalized.contextWindow = context+ }const minEffort = minReasoningEffort(model)if (minEffort) normalized.minReasoningEffort = minEffortreturn normalizeddiff --git a/src/app/ai/reply/undo.ts b/src/app/ai/reply/undo.tsindex 58f2709cc..e28398049 100644--- a/src/app/ai/reply/undo.ts+++ b/src/app/ai/reply/undo.ts@@ -59,7 +59,10 @@ export function useUndoRecords(options: UndoRecordOptions) {updateMessage(chat, reply, (message) => withUndo(message, undo))}- /** `text` with a note about the undone edits `history` has not reported, and those reports. */+ /**+ * `text` with a note about the undone edits `history` has not reported, and those reports. An+ * edit undone after a compaction is noted too, since the summary still describes it as made.+ */function note(text: string, history: readonly UIMessage[]) {const reports = undoToReport(history)const calls = {diff --git a/src/app/ai/skills/invoke.ts b/src/app/ai/skills/invoke.tsindex dcc320226..4d096f5eb 100644--- a/src/app/ai/skills/invoke.ts+++ b/src/app/ai/skills/invoke.ts@@ -1,8 +1,14 @@+import { leadingCommand } from '@/app/ai/chat/references/command'+import { appSkillLibrary, type SkillLibrary } from './library'import type { Skill } from './types'-/** How a message runs a skill by name, as in pi: `/skill:brand-review check the hero`. */-const SKILL_COMMAND = /^\/skill:([^\s]+)/+/** The command that runs a skill by name, as in pi: `/skill:brand-review check the hero`. */+const SKILL_COMMAND = 'skill:'++export function skillCommand(name: string): string {+ return `${SKILL_COMMAND}${name}`+}/** The skills the user can run by name: those switched on that allow it. */export function runnableSkills(skills: readonly Skill[]): Skill[] {@@ -14,8 +20,9 @@ export async function invokedSkill(text: string,library: SkillLibrary = appSkillLibrary): Promise<Skill | null> {- const name = SKILL_COMMAND.exec(text.trimStart())?.[1]- if (!name) return null+ const command = leadingCommand(text)?.name+ if (!command?.startsWith(SKILL_COMMAND)) return null+ const name = command.slice(SKILL_COMMAND.length)await library.refresh()return runnableSkills(library.enabled()).find((skill) => skill.name === name) ?? null}diff --git a/src/app/ai/transports/pi.ts b/src/app/ai/transports/pi.tsindex d9a1d76ce..43a5a0d69 100644--- a/src/app/ai/transports/pi.ts+++ b/src/app/ai/transports/pi.ts@@ -8,6 +8,7 @@ import type {} from '@open-pencil/harness'import { spawnHarnessProcess, type HarnessProcess } from '@/app/ai/agents/pi/process'+import { compactionOf, type StepCompaction } from '@/app/ai/chat/compaction/marker'import { createReplyStream, type ReplyStream } from '@/app/ai/reply/stream'interface PendingRequest {@@ -15,6 +16,10 @@ interface PendingRequest {resolve: (message: HarnessSidecarMessage) => voidreject: (error: Error) => voidstream: ReplyStream+ /** The reply's steps so far; a compaction starts the next one. */+ steps: number+ /** The reply's compactions so far; its metadata carries the whole list. */+ compactions: StepCompaction[]}function requestID(): string {@@ -47,8 +52,29 @@ function close(pending: PendingRequest): void {controller?.close()}-function mapEvent(event: HarnessTurnEvent, { stream }: PendingRequest): UIMessageChunk[] {+function mapEvent(event: HarnessTurnEvent, pending: PendingRequest): UIMessageChunk[] {+ const { stream } = pendingswitch (event.type) {+ case 'compaction': {+ // A manual compaction ran between turns, and the chat drew its divider when Pi confirmed it.+ if (event.trigger === 'manual') return []+ // The reply draws the compaction where it ran, as the built-in chat's between steps.+ pending.compactions = [+ ...pending.compactions,+ {+ summary: event.summary,+ trigger: event.trigger,+ tokensBefore: event.tokensBefore,+ step: pending.steps+++ }+ ]+ return [+ ...stream.end(),+ { type: 'finish-step' },+ { type: 'start-step' },+ { type: 'message-metadata', messageMetadata: { compactions: pending.compactions } }+ ]+ }case 'text-delta':return stream.text(event.text)case 'reasoning-delta':@@ -93,7 +119,10 @@ export class HarnessChatTransport implements ChatTransport<UIMessage> {})this.sessionCreated = true}- const lastUserMessage = [...messages].reverse().find((message) => message.role === 'user')+ // A compaction's divider is not something the person said.+ const lastUserMessage = messages.findLast(+ (message) => message.role === 'user' && compactionOf(message) === null+ )const text =lastUserMessage?.parts.filter((part): part is { type: 'text'; text: string } => part.type === 'text')@@ -149,6 +178,19 @@ export class HarnessChatTransport implements ChatTransport<UIMessage> {})}+ /**+ * Asks Pi to compact its context, steered by `instructions`. Pi writes the summary itself and+ * reports it on the next turn. False when no session has started, so there is nothing to compact.+ */+ async compact(instructions?: string): Promise<boolean> {+ if (!this.sessionCreated || this.destroyed) return false+ await this.request({+ method: 'session.compact',+ params: { sessionId: this.sessionId, ...(instructions && { instructions }) }+ })+ return true+ }+async reconnectToStream(): Promise<ReadableStream<UIMessageChunk> | null> {return null}@@ -193,7 +235,9 @@ export class HarnessChatTransport implements ChatTransport<UIMessage> {return {resolve: () => undefined,reject: () => undefined,- stream: createReplyStream(`turn-${id}`)+ stream: createReplyStream(`turn-${id}`),+ steps: 1,+ compactions: []}}@@ -207,7 +251,9 @@ export class HarnessChatTransport implements ChatTransport<UIMessage> {this.pending.set(id, {resolve,reject,- stream: createReplyStream(`turn-${id}`)+ stream: createReplyStream(`turn-${id}`),+ steps: 1,+ compactions: []})void process.send({ id, ...request }).catch(reject)})diff --git a/src/app/ai/transports/tool-loop.ts b/src/app/ai/transports/tool-loop.tsindex d7adbc6f6..aaf3cb905 100644--- a/src/app/ai/transports/tool-loop.ts+++ b/src/app/ai/transports/tool-loop.ts@@ -5,7 +5,11 @@ import { toMerged } from 'es-toolkit'import type { AIProviderID, ReasoningEffort } from '@open-pencil/core/constants'+import type { ContextLimits } from '@/app/ai/chat/compaction/limits'+import { messagesSinceCompaction } from '@/app/ai/chat/compaction/marker'+import { createStepCompaction } from '@/app/ai/chat/compaction/steps'import { resumableTransport } from '@/app/ai/chat/history/continuation'+import type { ReplyUsage } from '@/app/ai/chat/metadata'import { maxAgentSteps } from '@/app/ai/chat/preferences'import SYSTEM_PROMPT from '@/app/ai/chat/system-prompt'import type { RunRecorder, RunRecording } from '@/app/ai/chat/trace/recorder'@@ -53,6 +57,8 @@ export type ToolLoopTransportOptions = {* current step's tool calls finish, and the chat sends that message next.*/yieldWhen?: () => boolean+ /** The model's context limits, for compacting between steps; the Design model's by default. */+ contextLimits?: () => Promise<ContextLimits | null>}function callSettings(@@ -86,7 +92,8 @@ export function createToolLoopTransport({diagnosticContext = {},recorder,skills = appSkillLibrary,- yieldWhen = () => false+ yieldWhen = () => false,+ contextLimits}: ToolLoopTransportOptions) {const tools: AITools = {...createAITools(@@ -114,11 +121,16 @@ export function createToolLoopTransport({preview.finish(toolCallId)const cacheProviderOptions = promptCachingOptions(providerID, effectiveModelID)let recording: RunRecording | undefined+ // The last step's tokens: what the reply's final request held, which the next one starts from.+ let lastStep: { inputTokens: number; outputTokens: number } | null = null+ let firstRequestTokens: number | undefined+ const stepCompaction = createStepCompaction(model, contextLimits)const agent = new ToolLoopAgent({model,instructions: SYSTEM_PROMPT,tools,maxOutputTokens,+ prepareStep: (step) => stepCompaction.prepareStep(step),// Kept only to fingerprint each step's request for its trace.include: { requestMessages: recorder !== undefined },prepareCall: (options) => {@@ -148,6 +160,11 @@ export function createToolLoopTransport({},onStepFinish: (step) => {const { usage } = step+ // A step without a count says nothing of what the request held, so the last counted stands.+ if (usage.inputTokens !== undefined) {+ lastStep = { inputTokens: usage.inputTokens, outputTokens: usage.outputTokens ?? 0 }+ firstRequestTokens ??= usage.inputTokens+ }preview.clear()recordStep(store)recording?.step(step)@@ -174,14 +191,33 @@ export function createToolLoopTransport({}const transport = new DirectChatTransport({agent,- onError: handleError+ onError: handleError,+ // The reply keeps its tokens, which the transcript shows and the context meter reads.+ messageMetadata: ({ part }) => {+ const compacted = stepCompaction.metadataFor(part)+ if (compacted) return compacted+ if (part.type !== 'finish' || !lastStep) return undefined+ const usage: ReplyUsage = {+ contextTokens: lastStep.inputTokens + lastStep.outputTokens,+ firstRequestTokens,+ inputTokens: part.totalUsage.inputTokens ?? 0,+ outputTokens: part.totalUsage.outputTokens ?? 0,+ cacheReadTokens: part.totalUsage.inputTokenDetails.cacheReadTokens ?? null+ }+ return { usage }+ }}) as ChatTransport<UIMessage>return resumableTransport({reconnectToStream: (options) => transport.reconnectToStream(options),- async sendMessages(options) {+ async sendMessages(sent) {+ // A compacted conversation reaches the model as its summary and what followed it.+ const options = { ...sent, messages: messagesSinceCompaction(sent.messages) }// The run starts as the message is sent, so a Stop before the model is reached ends it.const started = startRun(store, maxAgentSteps.value, effectiveModelID)run = started+ lastStep = null+ firstRequestTokens = undefined+ await stepCompaction.begin(options.messages, options.abortSignal)await skills.refresh()offeredSkills = modelSkills()const catalog = skillCatalog(offeredSkills)diff --git a/src/app/i18n/number.ts b/src/app/i18n/number.tsindex 4d3cde36a..6fe3002f2 100644--- a/src/app/i18n/number.ts+++ b/src/app/i18n/number.ts@@ -12,3 +12,16 @@ export function formatNumber(value: number): string {}return format.format(value)}++const compactFormats = new Map<string, Intl.NumberFormat>()++/** A large count in the app's language, shortened as people say it: 84K, 1.2M. */+export function formatCompactNumber(value: number): string {+ const language = locale.get()+ let format = compactFormats.get(language)+ if (!format) {+ format = new Intl.NumberFormat(language, { notation: 'compact', maximumFractionDigits: 1 })+ compactFormats.set(language, format)+ }+ return format.format(value)+}diff --git a/src/app/settings/preferences/store.ts b/src/app/settings/preferences/store.tsindex 0922d2d3a..15cda6b8e 100644--- a/src/app/settings/preferences/store.ts+++ b/src/app/settings/preferences/store.ts@@ -29,6 +29,10 @@ export const CHANGE_PREVIEW_SIZES = ['off', 'small', 'medium', 'large'] as const/** How large the before/after images kept for each AI edit are; `off` keeps only the JSX diff. */export type ChangePreviewSize = (typeof CHANGE_PREVIEW_SIZES)[number]+export const TOKEN_USAGE_DISPLAYS = ['hover', 'always', 'hidden'] as const+/** When a reply shows the tokens it used: while hovered, always, or never. */+export type TokenUsageDisplay = (typeof TOKEN_USAGE_DISPLAYS)[number]+/** Multipliers for how far each wheel or pinch event zooms the canvas; 1 is Figma's rate. */export const ZOOM_SPEEDS = [0.1, 0.25, 0.5, 0.75, 1, 1.5, 2] as constexport type ZoomSpeed = (typeof ZOOM_SPEEDS)[number]@@ -93,6 +97,9 @@ export interface AppPreferences {changePreviewSize: ChangePreviewSize/** Whether the view follows our AI agents while they work. */followAgents: boolean+ /** Whether a conversation is compacted when its context window fills up. */+ compactAutomatically: boolean+ tokenUsage: TokenUsageDisplay}files: { recentLimit: number }version: 1@@ -121,7 +128,9 @@ export const DEFAULT_APP_PREFERENCES: Readonly<AppPreferences> = {reasoningDisplay: 'collapsed',maxAgentSteps: DEFAULT_AGENT_STEPS,changePreviewSize: 'medium',- followAgents: true+ followAgents: true,+ compactAutomatically: true,+ tokenUsage: 'hover'},files: { recentLimit: DEFAULT_RECENT_FILES_LIMIT },version: 1,@@ -172,7 +181,9 @@ const appPreferencesSchema = section({v.picklist(CHANGE_PREVIEW_SIZES),defaults.chat.changePreviewSize),- followAgents: v.fallback(v.boolean(), defaults.chat.followAgents)+ followAgents: v.fallback(v.boolean(), defaults.chat.followAgents),+ compactAutomatically: v.fallback(v.boolean(), defaults.chat.compactAutomatically),+ tokenUsage: v.fallback(v.picklist(TOKEN_USAGE_DISPLAYS), defaults.chat.tokenUsage)}),files: section({recentLimit: v.fallback(recentFilesLimitSchema, defaults.files.recentLimit)diff --git a/src/components/chat/ChatComposer.vue b/src/components/chat/ChatComposer.vueindex ccff38f94..7e7d33f12 100644--- a/src/components/chat/ChatComposer.vue+++ b/src/components/chat/ChatComposer.vue@@ -29,7 +29,6 @@ const emit = defineEmits<{stop: []/** Escape while the agent works: stop it and send what is waiting. */interrupt: []- settings: []paste: [event: ClipboardEvent]}>()const { ai } = useI18n()@@ -76,7 +75,11 @@ function restoreDraft(draft: string): boolean {editor.setText(draft)return true}-defineExpose({ restoreDraft, insert: editor.insert, focus: editor.focus })+defineExpose({+ restoreDraft,+ insert: editor.insert,+ focus: editor.focus+})</script><template><TooltipProvider>@@ -96,14 +99,6 @@ defineExpose({ restoreDraft, insert: editor.insert, focus: editor.focus })<template #model><slot name="model" /></template><template #actions>- <IconButton- :label="ai.providerSettings"- size="sm"- data-test-id="provider-settings-trigger"- @click="emit('settings')"- >- <icon-lucide-settings class="size-3.5" />- </IconButton><IconButtonv-if="showStop":label="ai.stopGenerating"diff --git a/src/components/chat/ChatContextMeter.vue b/src/components/chat/ChatContextMeter.vuenew file mode 100644index 000000000..2c4117333--- /dev/null+++ b/src/components/chat/ChatContextMeter.vue@@ -0,0 +1,90 @@+<script setup lang="ts">+import { PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'+import { computed } from 'vue'++import { useI18n } from '@open-pencil/vue/i18n'++import { compactAutomatically } from '@/app/ai/chat/preferences'+import { formatCompactNumber } from '@/app/i18n/number'+import ChatCreditBalance from '@/components/chat/ChatCreditBalance.vue'+import { usePopoverUI } from '@/components/ui/overlay/popover'++import { chatContextTheme } from './ui'++/**+ * How full the conversation's context is, as a meter in the chat's header. Its popover tells the+ * tokens, when the conversation compacts, and what Cloud credits are left; compaction itself is+ * a setting and `/compact`.+ */+const {+ used,+ contextWindow,+ compactsAt,+ replying = false+} = defineProps<{+ used: number+ contextWindow: number+ compactsAt: number+ replying?: boolean+}>()+const { ai } = useI18n()+const ui = chatContextTheme()+const popover = usePopoverUI({ content: ui.popover() })++/** The share past which the meter warns, as the bar over the message field does. */+const FULL = 0.7++const ratio = computed(() => Math.min(1, used / contextWindow))+const percent = computed(() => Math.round(ratio.value * 100))+const full = computed(() => ratio.value >= FULL)+</script>++<template>+ <PopoverRoot>+ <PopoverTrigger+ :class="ui.meter()"+ :aria-label="ai.contextUsed({ percent: percent })"+ data-test-id="chat-context-meter"+ >+ <span :class="ui.miniBar()" aria-hidden="true">+ <span :class="ui.barValue()" :data-full="full" :style="{ width: `${percent}%` }" />+ </span>+ {{ percent }}%+ </PopoverTrigger>+ <PopoverPortal>+ <PopoverContent+ side="bottom"+ align="end"+ :side-offset="4"+ :collision-padding="8"+ :class="popover.content"+ data-test-id="chat-context-popover"+ >+ <div :class="ui.popoverHeader()">+ <span :class="ui.popoverTitle()">{{ ai.contextTitle }}</span>+ <span :class="ui.popoverValue()">+ {{+ ai.contextTokens({+ used: formatCompactNumber(used),+ total: formatCompactNumber(contextWindow)+ })+ }}+ </span>+ </div>+ <div :class="ui.bar()">+ <div :class="ui.barValue()" :data-full="full" :style="{ width: `${percent}%` }" />+ </div>+ <p :class="ui.note()">+ {{+ compactAutomatically+ ? ai.contextCompactsAt({ tokens: formatCompactNumber(compactsAt) })+ : ai.contextCompactsOff+ }}+ </p>+ <div :class="ui.credits()">+ <ChatCreditBalance :replying="replying" />+ </div>+ </PopoverContent>+ </PopoverPortal>+ </PopoverRoot>+</template>diff --git a/src/components/chat/ChatContextWarning.vue b/src/components/chat/ChatContextWarning.vuenew file mode 100644index 000000000..53a52ad50--- /dev/null+++ b/src/components/chat/ChatContextWarning.vue@@ -0,0 +1,25 @@+<script setup lang="ts">+import { useI18n } from '@open-pencil/vue/i18n'++import AppButton from '@/components/ui/button/AppButton.vue'++import { chatContextTheme } from './ui'++/** Over the message field once the context is nearly full, with a way to compact it now. */+const { percent, compacting = false } = defineProps<{ percent: number; compacting?: boolean }>()+const emit = defineEmits<{ compact: [] }>()+const { ai } = useI18n()+const ui = chatContextTheme()+</script>++<template>+ <div :class="ui.warning()" role="status" data-test-id="chat-context-warning">+ <icon-lucide-gauge class="size-3.5 shrink-0" aria-hidden="true" />+ <span :class="ui.warningLabel()">+ {{ compacting ? ai.compacting : ai.contextNearlyFull({ percent }) }}+ </span>+ <AppButton v-if="!compacting" size="xs" variant="ghost" @click="emit('compact')">+ {{ ai.compact }}+ </AppButton>+ </div>+</template>diff --git a/src/components/chat/ChatHistory.vue b/src/components/chat/ChatHistory.vueindex bad2a4197..c64030116 100644--- a/src/components/chat/ChatHistory.vue+++ b/src/components/chat/ChatHistory.vue@@ -108,10 +108,11 @@ function closeMenu(event: Event) {<div :class="styles.root()"><div :class="styles.header()"><PopoverRoot v-model:open="open">- <PopoverTrigger :class="styles.trigger()" :disabled="disabled" :aria-label="ai.chatHistory">- <span :class="styles.title()">{{ selected?.title || ai.newChat }}</span>- <icon-lucide-chevron-down :class="styles.icon()" />- </PopoverTrigger>+ <Tip :label="ai.chatHistory">+ <PopoverTrigger :class="triggerClass" :disabled="disabled" :aria-label="ai.chatHistory">+ <icon-lucide-panel-left :class="styles.icon()" />+ </PopoverTrigger>+ </Tip><PopoverPortal><PopoverContentalign="start"@@ -164,6 +165,9 @@ function closeMenu(event: Event) {</PopoverContent></PopoverPortal></PopoverRoot>+ <span :class="styles.heading()" data-test-id="chat-title">{{+ selected?.title || ai.newChat+ }}</span><slot name="actions" /><IconButton :label="ai.newChat" :disabled="disabled" size="sm" @click="emit('create')"><icon-lucide-plus :class="styles.icon()"diff --git a/src/components/chat/ChatInput.vue b/src/components/chat/ChatInput.vueindex a350a625a..0c9dbd9e1 100644--- a/src/components/chat/ChatInput.vue+++ b/src/components/chat/ChatInput.vue@@ -11,8 +11,6 @@ import { takeBackMessages } from '@/app/ai/chat/queue'import type { ChatSubmission } from '@/app/ai/chat/submission/types'import { useAIChat } from '@/app/ai/chat/use'import { designModelProfile } from '@/app/ai/models'-import { openSettingsDialog } from '@/app/settings/dialog'-import ChatCreditBalance from '@/components/chat/ChatCreditBalance.vue'import ChatProfileSelect from '@/components/chat/ChatProfileSelect.vue'import ChatThinkingSelect from '@/components/chat/ChatThinkingSelect.vue'import { useComposerCompletions } from '@/components/chat/composer/useComposerCompletions'@@ -83,8 +81,6 @@ function restoreDraft(submission: ChatSubmission): void {else for (const image of submission.images) revokeImagePreviewURL(image.previewURL)}-/** A reply is on its way, so the credit balance waits to update until it ends. */-const replying = computed(() => status === 'streaming' || status === 'submitted')/** Why images dropped now would not be attached, or null when they would. */const dropRefusal = computed(() => {if (disabled) return ai.value.dropImagesAfterReply@@ -144,7 +140,6 @@ const selectedProfileName = computed(@stop="emit('stop')"@interrupt="emit('interrupt')"@paste="handlePaste"- @settings="openSettingsDialog('ai')"><template v-if="images.length" #attachment><div class="flex flex-wrap gap-1.5">@@ -215,7 +210,6 @@ const selectedProfileName = computed(</template></ChatProfileSelect><ChatThinkingSelect />- <ChatCreditBalance :replying="replying" /></template></div></template>diff --git a/src/components/chat/ChatMessage.stories.ts b/src/components/chat/ChatMessage.stories.tsindex 0da4e33e1..d49152bbc 100644--- a/src/components/chat/ChatMessage.stories.ts+++ b/src/components/chat/ChatMessage.stories.ts@@ -82,6 +82,7 @@ const partlyUndoneMessage: UIMessage = {type ChatMessageStoryArgs = {message: UIMessagestreaming?: boolean+ canRegenerate?: boolean}const meta = {@@ -125,3 +126,33 @@ export const PartlyUndone: Story = {await expect(undone).toHaveLength(1)}}++/** A finished reply with the tokens it used, which the default setting shows on hover. */+export const WithUsage: Story = {+ args: {+ message: {+ id: 'usage-message',+ role: 'assistant',+ parts: [+ {+ type: 'text',+ text: 'I added two more rectangles, green and magenta, each 160×120 with 8px corners. They sit in a second row under the first pair, and I zoomed the view to show all four rectangles.'+ }+ ],+ metadata: {+ usage: {+ contextTokens: 29_300,+ inputTokens: 28_700,+ outputTokens: 609,+ cacheReadTokens: null+ }+ }+ },+ canRegenerate: true+ },+ play: async ({ canvasElement }) => {+ await expect(canvasElement.querySelector('[data-slot="chat-reply-usage"]')).toHaveTextContent(+ '28.7K in · 609 out'+ )+ }+}diff --git a/src/components/chat/ChatMessage.vue b/src/components/chat/ChatMessage.vueindex 2e578a33c..5162d00ce 100644--- a/src/components/chat/ChatMessage.vue+++ b/src/components/chat/ChatMessage.vue@@ -1,5 +1,5 @@<script setup lang="ts">-import { refAutoReset, useClipboard } from '@vueuse/core'+import { useClipboard } from '@vueuse/core'import { isReasoningUIPart, isTextUIPart } from 'ai'import type { UIMessage } from 'ai'import { computed, ref } from 'vue'@@ -9,8 +9,12 @@ import { vTestId } from '@open-pencil/vue/testing'import { attachmentsForMessage } from '@/app/ai/attachment/presentation/store'import type { AttachmentPresentation } from '@/app/ai/attachment/presentation/types'-import { undoOf, wasStopped } from '@/app/ai/chat/metadata'-import { reasoningDisplay as preferredReasoningDisplay } from '@/app/ai/chat/preferences'+import { replyCompactions } from '@/app/ai/chat/compaction/marker'+import { undoOf, usageOf, wasStopped } from '@/app/ai/chat/metadata'+import {+ reasoningDisplay as preferredReasoningDisplay,+ tokenUsageDisplay+} from '@/app/ai/chat/preferences'import { visibleUserMessageText } from '@/app/ai/chat/presentation'import { groupMessageParts, type MessagePartGroup } from '@/app/ai/chat/tool-calls/display'import type { ReasoningDisplay } from '@/app/settings/preferences/store'@@ -19,11 +23,15 @@ import ChatMarkdown from '@/components/chat/ChatMarkdown.vue'import ChatReasoning from '@/components/chat/ChatReasoning.vue'import ChatReferenceText from '@/components/chat/reference/ChatReferenceText.vue'import ChatToolCallGroup from '@/components/chat/tool/ChatToolCallGroup.vue'+import ChatCompactionDivider from '@/components/chat/turn/ChatCompactionDivider.vue'import ChatMessageEditor from '@/components/chat/turn/ChatMessageEditor.vue'import ChatTurnActions from '@/components/chat/turn/ChatTurnActions.vue'import AppButton from '@/components/ui/button/AppButton.vue'import IconButton from '@/components/ui/button/IconButton.vue'+import { usageParts } from './turn/usage'+import { chatReplyTheme } from './ui'+const {message,streaming = false,@@ -77,18 +85,26 @@ function saveEdit(text: string): void {const firstAssistantTextPartIndex = computed(() =>message.parts.findIndex((part) => isTextUIPart(part) && part.text.length > 0))-const copied = refAutoReset(false, 1500)-const { copy, isSupported: clipboardSupported } = useClipboard()--async function copyResponse(): Promise<void> {- if (!assistantText.value || !clipboardSupported.value) return- await copy(assistantText.value)- copied.value = true-}+const lastAssistantTextPartIndex = computed(() =>+ message.parts.findLastIndex((part) => isTextUIPart(part) && part.text.length > 0)+)+const { copy, copied, isSupported: clipboardSupported } = useClipboard({ copiedDuring: 1500 })+const ui = chatReplyTheme()+/** The text the copy button sits on: the reply's first, when there is text to copy. */+const copyPartIndex = computed(() =>+ assistantText.value && clipboardSupported.value ? firstAssistantTextPartIndex.value : -1+)// The AI SDK updates parts in place and replaces only the message, so copy each part for// the cards' computed state to see the new values.const undo = computed(() => undoOf(message))+const usage = computed(() => usageOf(message))+/** With usage shown on hover, the reply's last text shows it on hover, beside the copy button. */+const usageOnHover = computed(() =>+ usage.value && tokenUsageDisplay.value === 'hover'+ ? usageParts(ai.value, usage.value).join(' · ')+ : undefined+)const undoneCalls = computed(() => new Set(undo.value?.undone))const reverted = computed(() =>@@ -99,16 +115,25 @@ const reverted = computed(const stopped = computed(() => wasStopped(message))// A request that failed once its reply had started leaves the reply without content.const empty = computed(() => message.parts.every((part) => part.type === 'step-start'))-const groups = computed(() => groupMessageParts(message.parts.map((part) => ({ ...part }))))+/** Compactions between the reply's steps, which the reply draws where they ran. */+const compactions = computed(() => replyCompactions(message))+const groups = computed(() =>+ groupMessageParts(+ message.parts.map((part) => ({ ...part })),+ compactions.value.map((compaction) => compaction.step)+ )+)function groupKey(group: MessagePartGroup): string {- return group.kind === 'tools' ? `tools-${group.parts[0]?.index}` : `part-${group.index}`+ if (group.kind === 'tools') return `tools-${group.parts[0]?.index}`+ return `${group.kind}-${group.index}`}</script><template><divv-test-id="`chat-message-${message.role}`"+ class="group/reply":class="message.role === 'user' ? 'flex justify-end' : ''"><div@@ -124,8 +149,20 @@ function groupKey(group: MessagePartGroup): string {:data-reverted="reverted"><template v-for="group in groups" :key="groupKey(group)">+ <template v-if="group.kind === 'compaction'">+ <!-- Only the latest compaction's request is the one the reply's usage ends on. -->+ <ChatCompactionDivider+ v-if="compactions[group.compaction]"+ :compaction="compactions[group.compaction]"+ :tokens-after="+ streaming || group.compaction < compactions.length - 1+ ? null+ : (usage?.contextTokens ?? null)+ "+ />+ </template><ChatToolCallGroup- v-if="group.kind === 'tools'"+ v-else-if="group.kind === 'tools'":parts="group.parts.map(({ part }) => part)":undone="undoneCalls"/>@@ -148,19 +185,38 @@ function groupKey(group: MessagePartGroup): string {class="group/response relative rounded-xl rounded-tl-md bg-hover px-3 py-2 text-xs leading-relaxed text-surface"><ChatMarkdown :content="group.part.text" :mode="markdownMode" />- <IconButton+ <!-- With usage shown on hover, the usage and the copy button appear in the last+ text's corner over the bubble's own colour, fading the line's end out under+ them, so they take no room at rest; otherwise the button sits there alone. -->+ <divv-if="- group.index === firstAssistantTextPartIndex && assistantText && clipboardSupported+ (usageOnHover && group.index === lastAssistantTextPartIndex) ||+ group.index === copyPartIndex+ "+ :class="+ ui.corner({+ usage: !!usageOnHover && group.index === lastAssistantTextPartIndex+ })"- :label="copied ? ai.responseCopied : ai.copyResponse"- size="xs"- data-slot="chat-copy-response"- class="absolute right-1 bottom-1 opacity-0 focus-visible:opacity-100 group-hover/response:opacity-100"- @click="copyResponse">- <icon-lucide-check v-if="copied" class="size-3 text-success" />- <icon-lucide-copy v-else class="size-3" />- </IconButton>+ <span+ v-if="usageOnHover && group.index === lastAssistantTextPartIndex"+ class="px-1"+ data-slot="chat-reply-usage"+ >+ {{ usageOnHover }}+ </span>+ <IconButton+ v-if="group.index === copyPartIndex"+ :label="copied ? ai.responseCopied : ai.copyResponse"+ size="xs"+ data-slot="chat-copy-response"+ @click="copy(assistantText)"+ >+ <icon-lucide-check v-if="copied" class="size-3 text-success" />+ <icon-lucide-copy v-else class="size-3" />+ </IconButton>+ </div></div></template></div>@@ -173,6 +229,7 @@ function groupKey(group: MessagePartGroup): string {:stopped="stopped":undone="undoneCalls.size":edits="undo?.edits.length ?? 0"+ :usage="usage"@regenerate="emit('regenerate')"@revert="emit('revert')"@restore="emit('restore')"diff --git a/src/components/chat/ChatPanel.vue b/src/components/chat/ChatPanel.vueindex 1bfd323c0..6cfc73c91 100644--- a/src/components/chat/ChatPanel.vue+++ b/src/components/chat/ChatPanel.vue@@ -6,6 +6,9 @@ import { computed, shallowRef, useTemplateRef, watch } from 'vue'import { useI18n } from '@open-pencil/vue/i18n'import { isAttachableImageFile, revokeImagePreviewURL } from '@/app/ai/attachment/image/prepare'+import { useChatContext } from '@/app/ai/chat/compaction/limits'+import { compactionOf } from '@/app/ai/chat/compaction/marker'+import { useChatCompaction } from '@/app/ai/chat/compaction/use'import { chatDocumentId } from '@/app/ai/chat/history/document'import {clearQueuedMessages,@@ -14,6 +17,7 @@ import {removeQueuedMessage,takeNextMessage} from '@/app/ai/chat/queue'+import { leadingCommand, type LeadingCommand } from '@/app/ai/chat/references/command'import { useChatRunLocation } from '@/app/ai/chat/run-location'import type { ChatSubmission } from '@/app/ai/chat/submission/types'import { useChatSubmission } from '@/app/ai/chat/submission/use'@@ -27,6 +31,9 @@ import { useDateFormat } from '@/app/i18n/date'import { openSettingsDialog } from '@/app/settings/dialog'import { openExternalLink, toast } from '@/app/shell/ui'import { activeTab } from '@/app/tabs'+import ChatContextMeter from '@/components/chat/ChatContextMeter.vue'+import ChatContextWarning from '@/components/chat/ChatContextWarning.vue'+import ChatCreditBalance from '@/components/chat/ChatCreditBalance.vue'import ChatFollowAgentsToggle from '@/components/chat/ChatFollowAgentsToggle.vue'import ChatHistory from '@/components/chat/ChatHistory.vue'import ChatInput from '@/components/chat/ChatInput.vue'@@ -36,12 +43,21 @@ import ChatRunLocation from '@/components/chat/ChatRunLocation.vue'import ChatTranscript from '@/components/chat/ChatTranscript.vue'import { useImageDrop } from '@/components/ui/drop/useImageDrop'-const { isConfigured, ensureChat, history, chatFailure, clearChatFailure, providerID } = useAIChat()+const {+ isConfigured,+ ensureChat,+ compactAgent,+ history,+ chatFailure,+ clearChatFailure,+ providerID+} = useAIChat()const { ai } = useI18n()const dates = useDateFormat()const runLocation = useChatRunLocation()const chat = shallowRef<Chat<UIMessage> | null>(null)+const compaction = useChatCompaction({ chat, ensureChat, flush: history.flush, compactAgent })const submission = useChatSubmission({chat,ensureChat,@@ -64,7 +80,8 @@ const submission = useChatSubmission({})),reportError: toast.error,openModelSettings: () => openSettingsDialog('ai'),- openSetup: () => openAISetup()+ openSetup: () => openAISetup(),+ prepare: (current, text) => compaction.compactIfFull(current, text)})const chatInput = useTemplateRef<{@@ -80,9 +97,23 @@ const { dragging: draggingImages } = useImageDrop(panel, {})let viewGeneration = 0-/** Puts an unsent message back only in the conversation it was written in. */+/**+ * Puts an unsent message back only in the conversation it was written in. `/compact` compacts+ * instead of sending, whether typed now or waiting in the queue, and what waits behind it goes+ * next.+ */async function submitMessage(message: ChatSubmission) {const generation = viewGeneration+ const command = compactCommand(message)+ if (command) {+ const compacted = await compaction.compact({+ trigger: 'manual',+ instructions: command.rest || undefined+ })+ if (!compacted && generation === viewGeneration) chatInput.value?.restoreDraft(message)+ if (compacted && status.value === 'ready') sendNextQueued()+ return+ }if (await submission.submit(message)) returnif (generation === viewGeneration) chatInput.value?.restoreDraft(message)else for (const image of message.images) revokeImagePreviewURL(image.previewURL)@@ -93,6 +124,40 @@ void history.initialize().catch(() => {})const messages = computed(() => chat.value?.messages ?? history.messages.value)+const context = useChatContext(messages)+/** Past this share of its window, a bar over the message field offers to compact. */+const CONTEXT_WARNING = 0.7+const contextPercent = computed(() =>+ context.ratio.value === null ? null : Math.round(Math.min(1, context.ratio.value) * 100)+)++/**+ * The command when `message` starts with `/compact`, and what to keep after it: the chat+ * summarizes a model it calls itself and asks Pi to compact its own context. An ACP agent's+ * own `/compact` goes to it as written.+ */+function compactCommand(message: ChatSubmission): LeadingCommand | null {+ if (providerID.value.startsWith('acp:') || message.images.length > 0) return null+ const command = leadingCommand(message.displayText)+ return command?.name === 'compact' ? command : null+}++/** Compacts now, from the bar near the limit; a reply in progress finishes first. */+function compactConversation(): void {+ if (status.value === 'streaming' || status.value === 'submitted') return+ void compaction.compact({ trigger: 'manual' })+}++watch(+ () => compaction.failed.value,+ (failed) => {+ if (failed)+ toast.error(ai.value.compactionFailed, {+ label: ai.value.retryRequest,+ run: () => void compaction.retry()+ })+ }+)const historyOptions = computed(() => {const current = history.current.valueconst rows = [...history.conversations.value]@@ -187,6 +252,8 @@ const failureMessage = computed(() => {return ai.value.chatSignInExpiredcase 'plan-forbidden':return ai.value.chatPlanForbidden+ case 'context-limit':+ return ai.value.chatContextLimitdefault:return null}@@ -245,8 +312,23 @@ watch()})+/**+ * Compacts what came before the failed request, which stays after the summary, and asks again;+ * the request itself is what the model is to answer.+ */+async function compactAndRetry(failedId: string | undefined): Promise<void> {+ const request = messages.value.findLast(+ (message) => message.role === 'user' && compactionOf(message) === null+ )+ if (!request) return+ if (await compaction.compact({ trigger: 'manual', before: request.id })) retryFailed(failedId)+}function failureAction(failedId: string | undefined): { label: string; run: () => void } {const billingURL = cloudBillingURL.value+ // A request past the window goes again once the conversation is compacted.+ if (chatFailure.value?.reason === 'context-limit') {+ return { label: ai.value.compactAndRetry, run: () => void compactAndRetry(failedId) }+ }if (chatFailure.value?.reason === 'cloud-credits-exhausted' && billingURL) {return { label: ai.value.manageCloudPlanAction, run: () => void openExternalLink(billingURL) }}@@ -306,7 +388,18 @@ function handleStop() {@save-trace="saveTrace"@delete="historyAction(() => history.remove($event))">- <template #actions><ChatFollowAgentsToggle /></template>+ <template #actions>+ <ChatContextMeter+ v-if="context.limits.value && context.used.value !== null && context.compactsAt.value"+ :used="context.used.value"+ :context-window="context.limits.value.contextWindow"+ :compacts-at="context.compactsAt.value"+ :replying="status === 'streaming' || status === 'submitted'"+ />+ <!-- Without a known window there is no meter, and Cloud credits show on their own. -->+ <ChatCreditBalance v-else :replying="status === 'streaming' || status === 'submitted'" />+ <ChatFollowAgentsToggle />+ </template></ChatHistory><p v-if="history.storageError.value" role="alert" class="px-3 py-2 text-xs text-error">{{ ai.chatStorageFailed }}@@ -327,9 +420,11 @@ function handleStop() {:show-continue="showContinue":queued="queuedMessages":steers="!providerID.startsWith('acp:') && providerID !== 'harness:pi'"+ :sending="submission.sending.value?.displayText ?? null"+ :compacting="compaction.compacting.value"@remove-queued="removeQueuedMessage":nodes-live="!history.readOnly.value"- :interactive="chat !== null && !submission.busy.value"+ :interactive="chat !== null && !submission.busy.value && !compaction.compacting.value"@regenerate="submission.regenerate()"@revert="(messageId) => submission.revert(messageId)"@restore="(messageId) => submission.restore(messageId)"@@ -356,6 +451,17 @@ function handleStop() {:page="runLocation.page"@open="runLocation.open"/>+ <ChatContextWarning+ v-if="+ isConfigured &&+ contextPercent !== null &&+ contextPercent >= CONTEXT_WARNING * 100 &&+ !history.readOnly.value+ "+ :percent="contextPercent"+ :compacting="compaction.compacting.value"+ @compact="compactConversation()"+ /><ChatInputv-if="isConfigured && !agentHistoryReadOnly && !history.readOnly.value"ref="chatInput"diff --git a/src/components/chat/ChatPlayground.stories.ts b/src/components/chat/ChatPlayground.stories.tsindex 59e2cde9f..d13faf435 100644--- a/src/components/chat/ChatPlayground.stories.ts+++ b/src/components/chat/ChatPlayground.stories.ts@@ -80,7 +80,6 @@ const meta = {:status="selected?.status ?? 'ready'"@submit="submit"@stop="stop"- @settings="showProfileNotice"><template #model><div class="@container flex min-w-0 items-center">diff --git a/src/components/chat/ChatTranscript.vue b/src/components/chat/ChatTranscript.vueindex ef1faf342..985eb1fde 100644--- a/src/components/chat/ChatTranscript.vue+++ b/src/components/chat/ChatTranscript.vue@@ -7,8 +7,11 @@ import { useI18n } from '@open-pencil/vue/i18n'import { attachmentsForMessage } from '@/app/ai/attachment/presentation/store'import type { AttachmentPresentation } from '@/app/ai/attachment/presentation/types'+import { compactionOf } from '@/app/ai/chat/compaction/marker'+import { usageOf } from '@/app/ai/chat/metadata'import type { QueuedMessage } from '@/app/ai/chat/queue'import type { ReasoningDisplay } from '@/app/settings/preferences/store'+import ChatReferenceText from '@/components/chat/reference/ChatReferenceText.vue'import { CHAT_NODES_LIVE } from '@/components/chat/tool/context'import AppButton from '@/components/ui/button/AppButton.vue'import IconButton from '@/components/ui/button/IconButton.vue'@@ -16,6 +19,7 @@ import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'import ChatMessage from './ChatMessage.vue'import { useScrollFollowing } from './transcript/useScrollFollowing'+import ChatCompactionDivider from './turn/ChatCompactionDivider.vue'import ChatMessageQueued from './turn/ChatMessageQueued.vue'const {@@ -27,7 +31,9 @@ const {nodesLive = true,reasoningDisplay,queued = [],- steers = false+ steers = false,+ sending = null,+ compacting = false} = defineProps<{messages: UIMessage[]status: ChatStatus@@ -43,6 +49,10 @@ const {queued?: readonly QueuedMessage[]/** Whether the agent takes a waiting message mid-turn. */steers?: boolean+ /** The text of a message sent but not in the chat yet, shown at once while the chat connects. */+ sending?: string | null+ /** The conversation is being compacted, from a `/compact` or before a message goes. */+ compacting?: boolean}>()const emit = defineEmits<{continue: []@@ -59,6 +69,7 @@ provide()const running = computed(() => status === 'submitted' || status === 'streaming')const isThinking = computed(() => {+ if (sending !== null && !compacting) return trueif (!running.value) return falseconst last = messages.at(-1)if (!last || last.role !== 'assistant') return true@@ -71,7 +82,34 @@ const isThinking = computed(() => {const idle = computed(() => interactive && (status === 'ready' || status === 'error'))// A request that failed before any reply is the last message; it is retried, not an older reply.const lastMessage = computed(() => messages.at(-1))-const lastRequest = computed(() => messages.findLast((m) => m.role === 'user'))+/**+ * Each message with the compaction it marks, which the transcript draws as a divider, and what+ * the first reply after that compaction reported its request held.+ */+const entries = computed(() =>+ messages.map((message, index) => {+ // A compaction within a reply is drawn by the reply, at the step where it ran.+ const compaction = message.role === 'user' ? compactionOf(message) : null+ return { message, compaction, tokensAfter: compaction ? tokensAfter(index) : null }+ })+)+/** What the first reply after the compaction at `index` reported, before the next one. */+function tokensAfter(index: number): number | null {+ for (const message of messages.slice(index + 1)) {+ if (compactionOf(message)) return null+ const usage = usageOf(message)+ if (usage) return usage.contextTokens+ }+ return null+}+/**+ * The newest message the person wrote. A compaction's summary is not one, and a request before+ * it is no longer the model's to answer, so neither is edited or retried.+ */+const lastRequest = computed(() => {+ const last = messages.findLast((m) => m.role === 'user')+ return last && compactionOf(last) === null ? last : undefined+})/** Messages with attachments carry context a plain text edit would drop. */const editableRequestId = computed(() => {const request = lastRequest.value@@ -95,9 +133,9 @@ const { arrivedState, resumeFollowing } = useScrollFollowing(<template><ScrollAreaRoot class="relative min-h-0 flex-1">- <ScrollAreaViewport ref="viewportComponent" class="h-full px-3 py-3 [&>div]:h-full">+ <ScrollAreaViewport ref="viewportComponent" class="h-full px-3 pt-3 [&>div]:h-full"><AppPlaceholder- v-if="messages.length === 0"+ v-if="messages.length === 0 && sending === null && !compacting"data-test-id="chat-empty-state":label="ai.describeCreateOrChange":ui="{ root: 'h-full' }"@@ -108,22 +146,57 @@ const { arrivedState, resumeFollowing } = useScrollFollowing(</AppPlaceholder><!-- Messages -->- <div v-else ref="transcriptContent" data-test-id="chat-messages" class="flex flex-col gap-3">- <ChatMessage- v-for="(msg, index) in messages"+ <div+ v-else+ ref="transcriptContent"+ data-test-id="chat-messages"+ class="flex flex-col gap-3 pb-5"+ >+ <template+ v-for="({ message: msg, compaction, tokensAfter }, index) in entries":key="msg.id"- :message="msg"- :presentation="presentations?.[msg.id]"- :streaming="running && msg.role === 'assistant' && index === messages.length - 1"- :can-regenerate="idle && msg.id === lastMessage?.id && msg.role === 'assistant'"- :can-retry="idle && msg.id === lastMessage?.id && msg.role === 'user'"- :can-edit="idle && msg.id === editableRequestId"- :reasoning-display="reasoningDisplay"- @regenerate="emit('regenerate')"- @revert="emit('revert', msg.id)"- @restore="emit('restore', msg.id)"- @edit="(text) => emit('edit', msg.id, text)"- />+ >+ <ChatCompactionDivider+ v-if="compaction"+ :compaction="compaction"+ :tokens-after="tokensAfter"+ />+ <ChatMessage+ v-else+ :message="msg"+ :presentation="presentations?.[msg.id]"+ :streaming="running && msg.role === 'assistant' && index === messages.length - 1"+ :can-regenerate="idle && msg.id === lastMessage?.id && msg.role === 'assistant'"+ :can-retry="idle && msg.id === lastMessage?.id && msg.role === 'user'"+ :can-edit="idle && msg.id === editableRequestId"+ :reasoning-display="reasoningDisplay"+ @regenerate="emit('regenerate')"+ @revert="emit('revert', msg.id)"+ @restore="emit('restore', msg.id)"+ @edit="(text) => emit('edit', msg.id, text)"+ />+ </template>++ <div v-if="sending !== null" class="flex justify-end" data-test-id="chat-sending-message">+ <div+ class="max-w-[85%] rounded-xl rounded-br-md bg-accent px-3 py-2 text-xs leading-relaxed whitespace-pre-wrap text-on-accent"+ >+ <ChatReferenceText :text="sending" />+ </div>+ </div>++ <p+ v-if="compacting"+ role="status"+ class="flex items-center justify-center gap-1.5 py-1 text-2xs text-muted"+ data-test-id="chat-compacting"+ >+ <icon-lucide-loader-circle+ class="size-3 animate-spin motion-reduce:animate-none"+ aria-hidden="true"+ />+ {{ ai.compacting }}+ </p><!-- Thinking indicator: shown when AI is working but no visible activity --><div v-if="isThinking" data-test-id="chat-typing-indicator" class="flex gap-2">diff --git a/src/components/chat/composer/complete.ts b/src/components/chat/composer/complete.tsindex 576eaae6e..13a1c0e0f 100644--- a/src/components/chat/composer/complete.ts+++ b/src/components/chat/composer/complete.ts@@ -28,10 +28,11 @@ export interface ComposerSections {const KIND_ICONS: Record<ChatReferenceKind, Component> = {node: IconFile,page: IconFile,- skill: IconBookOpen+ skill: IconBookOpen,+ command: IconSquareSlash}-const SECTION_RANK: Record<ChatReferenceKind, number> = { node: 0, page: 1, skill: 2 }+const SECTION_RANK: Record<ChatReferenceKind, number> = { node: 0, page: 1, skill: 2, command: 3 }/** What may stand before an `@` that starts a reference: nothing, a space, or an opening bracket. */const REFERENCE_START = /^[\s([]?$/@@ -72,8 +73,15 @@ export function commandCompletion(const typed = context.matchBefore(/^\/\S*$/)if (typed?.from !== 0) return nullconst section = sections().command+ // A command chosen with the caret inside one already there replaces that whole command.+ const rest = context.state.doc.sliceString(+ context.pos,+ context.state.doc.lineAt(context.pos).to+ )+ const word = /^\S*\s?/.exec(rest)?.[0] ?? ''return {from: 0,+ to: context.pos + word.length,validFor: /^\/\S*$/,options: candidates().map((command): ComposerCompletion => ({icon: command.kind === 'skill' ? IconBookOpen : IconSquareSlash,diff --git a/src/components/chat/composer/useChatEditor.ts b/src/components/chat/composer/useChatEditor.tsindex 0e633b65d..4fdc2d632 100644--- a/src/components/chat/composer/useChatEditor.ts+++ b/src/components/chat/composer/useChatEditor.ts@@ -3,6 +3,7 @@ import {autocompletion,completionKeymap,completionStatus,+ selectedCompletion,type Completion,type CompletionSource} from '@codemirror/autocomplete'@@ -80,6 +81,9 @@ export function useChatEditor(override: options.completions,icons: false,activateOnTyping: true,+ // The field sits at the panel's bottom: a short list fits under its first line but would+ // cover the field's own buttons, so lists always open above.+ aboveCursor: true,addToOptions: [{ render: renderCompletionIcon, position: 20 }]}),// The list opens above the field and may be wider than the panel, which clips its content.@@ -96,6 +100,17 @@ export function useChatEditor(return true}},+ {+ // Typing a completion's whole label, such as `/compact`, then a space picks it, so a+ // command typed in full becomes the same chip as one chosen from the list.+ key: 'Space',+ run: (editor) => {+ const selected = selectedCompletion(editor.state)+ if (completionStatus(editor.state) !== 'active' || !selected) return false+ const typed = editor.state.sliceDoc(0, editor.state.selection.main.head)+ return typed === selected.label && acceptCompletion(editor)+ }+ },{key: 'Alt-Enter',run: () => {diff --git a/src/components/chat/composer/useComposerCompletions.ts b/src/components/chat/composer/useComposerCompletions.tsindex 0c79d60be..61c708da6 100644--- a/src/components/chat/composer/useComposerCompletions.ts+++ b/src/components/chat/composer/useComposerCompletions.ts@@ -3,46 +3,53 @@ import { onMounted } from 'vue'import { useAIMessages } from '@open-pencil/vue/i18n'import { agentCommands } from '@/app/ai/agents/acp/commands'-import { commandCandidates, referenceCandidates } from '@/app/ai/chat/references/candidates'+import {+ agentCommandCandidates,+ chatCommandCandidates,+ referenceCandidates,+ type CommandCandidate,+ type ReferenceCandidate+} from '@/app/ai/chat/references/candidates'import { useAIChat } from '@/app/ai/chat/use'import { enabledSkills, refreshSkills } from '@/app/ai/skills/library'import { getActiveEditorStoreOrNull } from '@/app/editor/active-store'-import { commandCompletion, referenceCompletion } from './complete'+import { commandCompletion, referenceCompletion, type ComposerSections } from './complete'-/**- * What `/` and `@` offer in a message field. An ACP agent runs its own skills and commands; the- * built-in chat and Pi run the user's skills.- */+/** The ACP agent a provider ID names, or null for the built-in chat and Pi. */+function acpAgentId(providerID: string): string | null {+ return providerID.startsWith('acp:') ? providerID.slice('acp:'.length) : null+}++/** What `/` and `@` offer in a message field. */export function useComposerCompletions() {const ai = useAIMessages()const { providerID } = useAIChat()- function acpAgentId(): string | null {- return providerID.value.startsWith('acp:') ? providerID.value.slice('acp:'.length) : null- }- const sections = () => ({+ // Skills installed since the app started are offered without opening Settings first.+ onMounted(() => void refreshSkills())++ const sections = (): ComposerSections => ({node: ai.value.chatReferenceLayers,page: ai.value.chatReferencePages,skill: ai.value.chatReferenceSkills,command: ai.value.chatReferenceCommands})- // Skills installed since the app started are offered without opening Settings first.- onMounted(() => void refreshSkills())+ /** An ACP agent's own commands, or else the chat's `/compact` and the user's skills. */+ function commands(): CommandCandidate[] {+ const agentId = acpAgentId(providerID.value)+ if (agentId) return agentCommandCandidates(agentCommands.value[agentId] ?? [])+ const compact = { name: 'compact', description: ai.value.compactCommand, hint: null }+ return chatCommandCandidates([compact], enabledSkills.value)+ }++ /** The active document's layers and pages matching `query`, then the user's skills. */+ function references(query: string): ReferenceCandidate[] {+ const store = getActiveEditorStoreOrNull()+ if (!store) return []+ return referenceCandidates(store.graph, store.state.currentPageId, enabledSkills.value, query)+ }- return [- commandCompletion(() => {- const agentId = acpAgentId()- return commandCandidates(- agentId ? (agentCommands.value[agentId] ?? []) : null,- enabledSkills.value- )- }, sections),- referenceCompletion((query) => {- const store = getActiveEditorStoreOrNull()- if (!store) return []- return referenceCandidates(store.graph, store.state.currentPageId, enabledSkills.value, query)- }, sections)- ]+ return [commandCompletion(commands, sections), referenceCompletion(references, sections)]}diff --git a/src/components/chat/input/useAttachments.ts b/src/components/chat/input/useAttachments.tsindex f6508627f..a1626555c 100644--- a/src/components/chat/input/useAttachments.ts+++ b/src/components/chat/input/useAttachments.ts@@ -13,6 +13,7 @@ import {} from '@/app/ai/attachment/image/prepare'import { MAX_IMAGE_ATTACHMENTS, type ImageAttachmentDraft } from '@/app/ai/attachment/image/types'import { resolveReferencedNodes } from '@/app/ai/chat/context'+import { commandsAsText } from '@/app/ai/chat/references/command'import { referenceLink } from '@/app/ai/chat/references/link'import { mentionedNodes } from '@/app/ai/chat/references/nodes'import type { ChatSubmission } from '@/app/ai/chat/submission/types'@@ -104,7 +105,7 @@ export function useAttachmentDrafts(options: AttachmentDraftOptions) {images.value = []resetImageDialog()return {- modelText: text,+ modelText: commandsAsText(text),displayText: text,images: submittedImages,nodes: mentionedNodes(options.editor.graph, text)diff --git a/src/components/chat/reference/ChatReferenceChip.vue b/src/components/chat/reference/ChatReferenceChip.vueindex 119cecaa0..011b13a88 100644--- a/src/components/chat/reference/ChatReferenceChip.vue+++ b/src/components/chat/reference/ChatReferenceChip.vue@@ -14,13 +14,15 @@ import { chatReferenceTheme } from '@/components/chat/ui'import { sceneNodeIcon } from '@/components/icons'/**- * A layer, page, or skill named in chat text. In the transcript it shows its target when- * clicked; in the composer it is part of the text and only shows what it names.+ * A layer, page, skill, or command named in chat text. In the transcript it shows its target+ * when clicked; in the composer it is part of the text and only shows what it names. A command+ * has nothing to show, so it never acts as a button.*/-const { reference, interactive = true } = defineProps<{+const { reference, interactive: clickable = true } = defineProps<{reference: ChatReferenceinteractive?: boolean}>()+const interactive = computed(() => clickable && reference.kind !== 'command')const ai = useAIMessages()const ui = chatReferenceTheme()@@ -94,6 +96,11 @@ async function open() {:class="ui.icon()"aria-hidden="true"/>+ <icon-lucide-square-slash+ v-else-if="reference.kind === 'command'"+ :class="ui.icon()"+ aria-hidden="true"+ /><icon-lucide-crosshair v-else :class="ui.icon()" aria-hidden="true" /><span :class="ui.label()">{{ resolved.name }}</span></component>diff --git a/src/components/chat/turn/ChatCompactionDivider.stories.ts b/src/components/chat/turn/ChatCompactionDivider.stories.tsnew file mode 100644index 000000000..2ad21b388--- /dev/null+++ b/src/components/chat/turn/ChatCompactionDivider.stories.ts@@ -0,0 +1,50 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { expect, userEvent, within } from 'storybook/test'++import type { Compaction } from '@/app/ai/chat/compaction/marker'++import ChatCompactionDivider from './ChatCompactionDivider.vue'++type DividerStoryArgs = {+ compaction: Compaction+ tokensAfter?: number | null+}++const meta = {+ title: 'App/Chat/Compaction Divider',+ component: ChatCompactionDivider,+ parameters: { layout: 'centered' },+ render: (args) => ({+ components: { ChatCompactionDivider },+ setup: () => ({ args }),+ template:+ '<div class="w-96 rounded-xl bg-panel p-4 text-surface"><ChatCompactionDivider v-bind="args" /></div>'+ })+} satisfies Meta<DividerStoryArgs>++export default meta+type Story = StoryObj<DividerStoryArgs>++export const Summary: Story = {+ args: {+ compaction: {+ summary:+ '## State\n- A calendar component with default, today, and selected variants.\n- Colors bound to variables.',+ trigger: 'auto',+ tokensBefore: 45_100+ },+ tokensAfter: 33_900+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await userEvent.click(canvas.getByRole('button', { name: /Conversation compacted/ }))+ await expect(canvas.getByText('45.1K → 33.9K tokens')).toBeVisible()+ }+}++/** An agent such as Pi compacted its own context and reported no summary. */+export const Agent: Story = {+ args: {+ compaction: { summary: '', trigger: 'manual', tokensBefore: null, agent: true }+ }+}diff --git a/src/components/chat/turn/ChatCompactionDivider.vue b/src/components/chat/turn/ChatCompactionDivider.vuenew file mode 100644index 000000000..d39a6cef7--- /dev/null+++ b/src/components/chat/turn/ChatCompactionDivider.vue@@ -0,0 +1,61 @@+<script setup lang="ts">+import { CollapsibleContent, CollapsibleRoot, CollapsibleTrigger } from 'reka-ui'++import { useI18n } from '@open-pencil/vue/i18n'++import type { Compaction } from '@/app/ai/chat/compaction/marker'+import { formatCompactNumber } from '@/app/i18n/number'+import ChatMarkdown from '@/components/chat/ChatMarkdown.vue'++import { chatCompactionTheme } from '../ui'++/**+ * Where a conversation was compacted: a rule across the transcript. The messages above it stay;+ * the model reads the summary in their place, which its label opens. An agent that compacted+ * its own context may have reported no summary to open.+ */+const { compaction, tokensAfter = null } = defineProps<{+ compaction: Compaction+ /** What the first reply after the compaction reported its request held, once there is one. */+ tokensAfter?: number | null+}>()+const { ai } = useI18n()+const ui = chatCompactionTheme()+</script>++<template>+ <!-- A collapsible with its own header shape, so it drives Reka directly and keeps the shared+ content motion, as the reasoning row does. -->+ <CollapsibleRoot+ as="section"+ :class="ui.root()"+ data-test-id="chat-compaction"+ :aria-label="ai.conversationCompacted"+ >+ <div :class="ui.rule()">+ <span :class="ui.line()" aria-hidden="true" />+ <CollapsibleTrigger :class="ui.toggle()">+ <icon-lucide-shrink :class="ui.icon()" aria-hidden="true" />+ <span :class="ui.title()">{{ ai.conversationCompacted }}</span>+ <icon-lucide-chevron-down :class="ui.chevron()" aria-hidden="true" />+ </CollapsibleTrigger>+ <span :class="ui.line()" aria-hidden="true" />+ </div>+ <CollapsibleContent :class="ui.content()">+ <div :class="ui.summary()">+ <p :class="ui.note()">+ {{ compaction.agent ? ai.agentCompactionKeepsMessages : ai.compactionKeepsMessages }}+ </p>+ <p v-if="compaction.tokensBefore !== null && tokensAfter !== null" :class="ui.note()">+ {{+ ai.compactionTokens({+ before: formatCompactNumber(compaction.tokensBefore),+ after: formatCompactNumber(tokensAfter)+ })+ }}+ </p>+ <ChatMarkdown v-if="compaction.summary" :content="compaction.summary" mode="static" />+ </div>+ </CollapsibleContent>+ </CollapsibleRoot>+</template>diff --git a/src/components/chat/turn/ChatTurnActions.vue b/src/components/chat/turn/ChatTurnActions.vueindex a9c7d8124..59dbd5933 100644--- a/src/components/chat/turn/ChatTurnActions.vue+++ b/src/components/chat/turn/ChatTurnActions.vue@@ -3,9 +3,14 @@ import { computed } from 'vue'import { useI18n } from '@open-pencil/vue/i18n'+import type { ReplyUsage } from '@/app/ai/chat/metadata'+import { tokenUsageDisplay } from '@/app/ai/chat/preferences'import { turnEdits } from '@/app/ai/reply/turns'import AppButton from '@/components/ui/button/AppButton.vue'+import { chatReplyTheme } from '../ui'+import { usageParts } from './usage'+const {messageId,canRegenerate = false,@@ -13,7 +18,8 @@ const {reverted = false,stopped = false,undone = 0,- edits = 0+ edits = 0,+ usage = null} = defineProps<{messageId: stringcanRegenerate?: boolean@@ -26,6 +32,8 @@ const {edits?: number/** The user stopped the reply before it finished. */stopped?: boolean+ /** The tokens the reply used, when its backend reported them. */+ usage?: ReplyUsage | null}>()const emit = defineEmits<{ regenerate: []; revert: []; restore: [] }>()const { ai } = useI18n()@@ -34,11 +42,16 @@ const turn = computed(() => turnEdits(messageId))const revertable = computed(() => turn.value?.revertable === true)const restorable = computed(() => turn.value?.restorable === true)const partlyUndone = computed(() => undone > 0 && undone < edits)+const ui = chatReplyTheme()+/** On hover the usage sits beside the copy button, so a reply with nothing else here leaves no row. */+const inlineUsage = computed(() =>+ usage && tokenUsageDisplay.value === 'always' ? usageParts(ai.value, usage) : null+)</script><template><div- v-if="stopped || partlyUndone || revertable || reverted || canRegenerate"+ v-if="stopped || partlyUndone || revertable || reverted || canRegenerate || inlineUsage"class="flex flex-wrap items-center gap-1"data-slot="chat-turn-actions">@@ -97,5 +110,8 @@ const partlyUndone = computed(() => undone > 0 && undone < edits)<template #leading><icon-lucide-refresh-cw aria-hidden="true" /></template>{{ empty ? ai.retryRequest : revertable ? ai.revertAndRegenerate : ai.regenerate }}</AppButton>+ <span v-if="inlineUsage" :class="ui.usage()" data-slot="chat-turn-usage">+ <span v-for="part in inlineUsage" :key="part">{{ part }}</span>+ </span></div></template>diff --git a/src/components/chat/turn/usage.ts b/src/components/chat/turn/usage.tsnew file mode 100644index 000000000..e6995e221--- /dev/null+++ b/src/components/chat/turn/usage.ts@@ -0,0 +1,17 @@+import type { useAIMessages } from '@open-pencil/vue/i18n'++import type { ReplyUsage } from '@/app/ai/chat/metadata'+import { formatCompactNumber } from '@/app/i18n/number'++/** A reply's tokens in and out, then the cached ones when there were any. */+export function usageParts(+ ai: ReturnType<typeof useAIMessages>['value'],+ usage: ReplyUsage+): string[] {+ const tokens = ai.replyTokens({+ input: formatCompactNumber(usage.inputTokens),+ output: formatCompactNumber(usage.outputTokens)+ })+ if (!usage.cacheReadTokens) return [tokens]+ return [tokens, ai.replyCachedTokens({ cached: formatCompactNumber(usage.cacheReadTokens) })]+}diff --git a/src/components/chat/ui.ts b/src/components/chat/ui.tsindex e44e6dd86..89b1d7fb6 100644--- a/src/components/chat/ui.ts+++ b/src/components/chat/ui.ts@@ -1,9 +1,15 @@import { tv } from 'tailwind-variants'+import compactionTheme from '@/theme/chat/compaction'+import contextTheme from '@/theme/chat/context'import profileTheme from '@/theme/chat/profile'import referenceTheme from '@/theme/chat/reference'+import replyTheme from '@/theme/chat/reply'import thinkingTheme from '@/theme/chat/thinking'+export const chatCompactionTheme = tv(compactionTheme)+export const chatContextTheme = tv(contextTheme)export const chatProfileTheme = tv(profileTheme)export const chatReferenceTheme = tv(referenceTheme)+export const chatReplyTheme = tv(replyTheme)export const chatThinkingTheme = tv(thinkingTheme)diff --git a/src/components/settings/chat/ChatSettingsSection.vue b/src/components/settings/chat/ChatSettingsSection.vueindex 9b738d6e8..f3b6e711e 100644--- a/src/components/settings/chat/ChatSettingsSection.vue+++ b/src/components/settings/chat/ChatSettingsSection.vue@@ -3,7 +3,13 @@ import { computed } from 'vue'import { useI18n } from '@open-pencil/vue/i18n'-import { changePreviewSize, maxAgentSteps, reasoningDisplay } from '@/app/ai/chat/preferences'+import {+ changePreviewSize,+ compactAutomatically,+ maxAgentSteps,+ reasoningDisplay,+ tokenUsageDisplay+} from '@/app/ai/chat/preferences'import { AGENT_STEP_LIMIT_MIN, AGENT_STEP_LIMIT_MAX } from '@/app/ai/reply/schema'import { resolveAgentStepLimit } from '@/app/ai/reply/step-limit'import { openToolAccessSettings } from '@/app/automation/tool-access/settings/use'@@ -14,6 +20,7 @@ import SettingsSection from '@/components/settings/layout/SettingsSection.vue'import AppButton from '@/components/ui/button/AppButton.vue'import PresetNumberField from '@/components/ui/input/PresetNumberField.vue'import AppSelect from '@/components/ui/select/AppSelect.vue'+import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'const { ai, automation, settings } = useI18n()const stepPresets = [25, 50, 100, 200]@@ -27,6 +34,11 @@ const options = computed(() => [{ value: 'while-thinking' as const, label: ai.value.reasoningWhileThinking },{ value: 'expanded' as const, label: ai.value.reasoningExpanded }])+const usageOptions = computed(() => [+ { value: 'hover' as const, label: ai.value.tokenUsageHover },+ { value: 'always' as const, label: ai.value.tokenUsageAlways },+ { value: 'hidden' as const, label: ai.value.tokenUsageHidden }+])const previewOptions = computed(() => [{ value: 'off' as const, label: ai.value.changePreviewOff },{ value: 'small' as const, label: ai.value.changePreviewSmall },@@ -66,6 +78,21 @@ const previewOptions = computed(() => [:ui="{ trigger: 'w-full sm:w-52' }"/></SettingsRow>+ <SettingsRow :label="ai.compactAutomatically" :description="ai.compactAutomaticallyHint">+ <AppSwitch v-model="compactAutomatically" :label="ai.compactAutomatically" />+ </SettingsRow>+ <SettingsRow+ :label="ai.tokenUsage"+ :description="ai.tokenUsageHint"+ class="max-sm:flex-col max-sm:items-stretch"+ >+ <AppSelect+ v-model="tokenUsageDisplay"+ :label="ai.tokenUsage"+ :options="usageOptions"+ :ui="{ trigger: 'w-full sm:w-52' }"+ />+ </SettingsRow><SettingsRow:label="ai.maxAgentSteps":description="ai.maxAgentStepsHint"diff --git a/src/theme/chat/compaction.ts b/src/theme/chat/compaction.tsnew file mode 100644index 000000000..804f7692f--- /dev/null+++ b/src/theme/chat/compaction.ts@@ -0,0 +1,23 @@+import { collapsibleContentMotion } from '../collapsible/collapsible'++/**+ * The divider a compaction leaves in the transcript: a rule with its label in the middle,+ * which opens the summary. Its spacing sits inside the content, which cannot snap while its+ * height animates.+ */+export default {+ slots: {+ root: 'flex flex-col py-1',+ rule: 'flex items-center gap-2 text-2xs text-muted',+ line: 'h-px min-w-3 flex-1 bg-border',+ toggle:+ 'inline-flex min-w-0 items-center gap-1.5 rounded px-1.5 py-0.5 outline-none hover:bg-hover hover:text-surface focus-visible:ring-2 focus-visible:ring-accent',+ icon: 'size-3 shrink-0',+ title: 'truncate',+ chevron:+ 'size-3 shrink-0 transition-transform motion-reduce:transition-none [[data-state=open]>&]:rotate-180',+ content: collapsibleContentMotion,+ summary: 'mt-2 flex flex-col gap-1.5 rounded-md bg-hover px-2.5 py-2 text-xs leading-relaxed',+ note: 'text-2xs leading-snug text-muted'+ }+} as constdiff --git a/src/theme/chat/context.ts b/src/theme/chat/context.tsnew file mode 100644index 000000000..7bc9b355e--- /dev/null+++ b/src/theme/chat/context.ts@@ -0,0 +1,24 @@+import { motionStyles } from '../motion/styles'++/**+ * How full the conversation's context is: a ring in the chat's header with its popover, and+ * the bar over the message field when it fills up.+ */+export default {+ slots: {+ meter:+ 'flex h-6 shrink-0 cursor-pointer items-center gap-1 rounded px-1.5 text-3xs text-muted outline-none hover:bg-hover hover:text-surface focus-visible:ring-2 focus-visible:ring-accent data-[state=open]:bg-hover data-[state=open]:text-surface',+ miniBar: 'flex h-1.5 w-5 shrink-0 overflow-hidden rounded-full bg-border',+ popover: ['z-50 flex w-64 flex-col gap-2.5 p-3 text-2xs text-surface', motionStyles.floating],+ popoverHeader: 'flex items-baseline justify-between gap-2',+ popoverTitle: 'font-medium',+ popoverValue: 'text-muted',+ bar: 'h-1.5 overflow-hidden rounded-full bg-border',+ barValue: 'h-full rounded-full bg-accent data-[full=true]:bg-warning',+ note: 'leading-snug text-muted',+ credits: 'flex items-center justify-between gap-2 text-muted',+ warning:+ 'mx-2.5 mb-1 flex items-center gap-2 rounded-md border border-warning-border bg-warning-bg px-2.5 py-1.5 text-2xs text-warning',+ warningLabel: 'min-w-0 flex-1 truncate'+ }+} as constdiff --git a/src/theme/chat/history.ts b/src/theme/chat/history.tsindex ed94190cb..fff86e423 100644--- a/src/theme/chat/history.ts+++ b/src/theme/chat/history.ts@@ -5,8 +5,7 @@ export default {slots: {root: 'shrink-0 border-b border-border',header: 'flex min-w-0 items-center gap-1 px-2 py-1.5',- trigger:- 'flex min-w-0 flex-1 items-center gap-1 rounded px-1.5 py-1 text-left text-xs text-surface hover:bg-hover disabled:opacity-50',+ heading: 'min-w-0 flex-1 truncate px-1 text-xs text-surface',title: 'min-w-0 flex-1 truncate',icon: 'size-3.5 shrink-0',content: ['z-50 w-80 max-w-[calc(100vw-1rem)] p-2', floatingSurface, motionStyles.floating],diff --git a/src/theme/chat/reply.ts b/src/theme/chat/reply.tsnew file mode 100644index 000000000..87e2fba86--- /dev/null+++ b/src/theme/chat/reply.ts@@ -0,0 +1,24 @@+import { motionStyles } from '../motion/styles'++/** A reply's own details: the tokens it used, and its text's corner. */+export default {+ slots: {+ // Under the reply when the setting shows usage always.+ usage: 'inline-flex items-center gap-2 px-2 text-2xs text-muted',+ // The copy button, and with usage on hover the usage too, shown when the text is hovered or+ // focused.+ corner: [+ 'absolute right-1 bottom-1 text-2xs text-muted opacity-0 group-focus-within/response:opacity-100 group-hover/response:opacity-100',+ motionStyles.reveal+ ]+ },+ variants: {+ // Over the bubble's own colour, fading out the end of a full last line beneath it.+ usage: {+ true: {+ corner:+ 'flex h-6 items-center gap-1 rounded-br-xl bg-[linear-gradient(to_right,transparent,var(--color-hover)_2rem)] pl-8'+ }+ }+ }+} as constdiff --git a/src/theme/code/completion.ts b/src/theme/code/completion.tsindex 616bef54b..bb865d4a7 100644--- a/src/theme/code/completion.ts+++ b/src/theme/code/completion.ts@@ -58,14 +58,22 @@ export const completionListStyles = {color: 'var(--color-muted)',opacity: '1'},+ // The label keeps its width; a long detail, such as a command's description, gives way first.'.cm-completionLabel': {- flex: '1',+ flex: 'none',+ maxWidth: '75%',minWidth: '0',overflow: 'hidden',textOverflow: 'ellipsis'},'.cm-completionMatchedText': { textDecoration: 'none', fontWeight: '600' },'.cm-completionDetail': {+ flex: '0 1 auto',+ minWidth: '0',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ paddingLeft: '12px',marginLeft: 'auto',fontStyle: 'normal',fontVariantNumeric: 'tabular-nums',diff --git a/src/theme/motion/styles.ts b/src/theme/motion/styles.tsindex 1c8435e25..ee681134a 100644--- a/src/theme/motion/styles.ts+++ b/src/theme/motion/styles.ts@@ -8,6 +8,8 @@ export const motionStyles = {*/floating:'animate-in fade-in-0 zoom-in-95 duration-150 ease-out data-[side=bottom]:slide-in-from-top-1 data-[side=top]:slide-in-from-bottom-1 data-[side=left]:slide-in-from-right-1 data-[side=right]:slide-in-from-left-1 motion-reduce:animate-none',+ /** Controls a hover or focus reveals fade in and out; the trigger sets the end state. */+ reveal: 'transition-opacity duration-150 ease-out motion-reduce:transition-none',spinner: 'animate-spin motion-reduce:animate-none',pulse: 'animate-pulse motion-reduce:animate-none'} as constdiff --git a/tests/app/ai/chat/compaction/compaction.test.ts b/tests/app/ai/chat/compaction/compaction.test.tsnew file mode 100644index 000000000..2196e4492--- /dev/null+++ b/tests/app/ai/chat/compaction/compaction.test.ts@@ -0,0 +1,233 @@+import { describe, expect, test } from 'bun:test'++import type { ModelMessage, UIMessage } from 'ai'+import { MockLanguageModelV4 } from 'ai/test'++import { autoCompactAt, contextTokensSinceCompaction } from '@/app/ai/chat/compaction/limits'+import {+ agentCompactionMessage,+ compactionMessage,+ compactionOf,+ messagesSinceCompaction+} from '@/app/ai/chat/compaction/marker'+import { summarizeConversation, summarySource } from '@/app/ai/chat/compaction/summarize'+import { withMetadata } from '@/app/ai/chat/metadata'++import { MOCK_USAGE } from '#tests/helpers/chat/usage'++function text(id: string, role: UIMessage['role'], value: string): UIMessage {+ return { id, role, parts: [{ type: 'text', text: value }] }+}++function reply(id: string, contextTokens: number): UIMessage {+ return withMetadata(text(id, 'assistant', 'Done'), {+ usage: { contextTokens, inputTokens: contextTokens, outputTokens: 10, cacheReadTokens: null }+ })+}++describe('compaction', () => {+ test('the model reads the latest summary and what followed it', () => {+ const marker = compactionMessage({+ summary: 'Built the hero.',+ trigger: 'manual',+ tokensBefore: 9000+ })+ const messages = [+ text('a', 'user', 'Make a hero'),+ reply('b', 9000),+ marker,+ text('c', 'user', 'Now a footer')+ ]+ expect(messagesSinceCompaction(messages).map((message) => message.id)).toEqual([marker.id, 'c'])+ expect(compactionOf(marker)).toEqual({+ summary: 'Built the hero.',+ trigger: 'manual',+ tokensBefore: 9000+ })+ expect(marker.role).toBe('user')+ expect(marker.parts).toEqual([+ {+ type: 'text',+ text: 'The conversation so far, summarized when it was compacted:\n\nBuilt the hero.'+ }+ ])+ expect(messagesSinceCompaction([text('a', 'user', 'Hi')]).map((message) => message.id)).toEqual(+ ['a']+ )+ // An agent's own compaction is drawn, but holds nothing the chat's model reads.+ const agent = agentCompactionMessage('manual')+ expect(compactionOf(agent)).toMatchObject({ agent: true, summary: '' })+ expect(+ messagesSinceCompaction([...messages, agent, text('d', 'user', 'And a nav')]).map(+ (message) => message.id+ )+ ).toEqual([marker.id, 'c', 'd'])+ })++ test('the next request starts from the last reply since the summary, or the summary itself', () => {+ const marker = compactionMessage({+ summary: 'x'.repeat(400),+ trigger: 'auto',+ tokensBefore: 9000+ })+ expect(contextTokensSinceCompaction([reply('a', 9000)])).toBe(9000)+ expect(contextTokensSinceCompaction([reply('a', 9000), marker])).toBe(100)+ expect(contextTokensSinceCompaction([reply('a', 9000), marker, reply('b', 1200)])).toBe(1200)+ expect(contextTokensSinceCompaction([text('a', 'user', 'Hi')])).toBeNull()+ // Right after a compaction, every request carries its instructions and tools with the+ // summary: what the reply that opened the conversation sent, less its request.+ const opened = withMetadata(text('f', 'assistant', 'Done'), {+ usage: {+ contextTokens: 21_000,+ firstRequestTokens: 20_010,+ inputTokens: 30_000,+ outputTokens: 10,+ cacheReadTokens: null+ }+ })+ const later = withMetadata(text('g', 'assistant', 'Done'), {+ usage: {+ contextTokens: 40_000,+ firstRequestTokens: 39_000,+ inputTokens: 39_000,+ outputTokens: 10,+ cacheReadTokens: null+ }+ })+ const ask = text('q', 'user', 'x'.repeat(40))+ expect(+ contextTokensSinceCompaction([ask, opened, text('r', 'user', 'More'), later, marker])+ ).toBe(20_100)+ })++ test('compacts automatically before the window, keeping the whole reply allowance and some room', () => {+ expect(autoCompactAt({ contextWindow: 200_000, maxOutputTokens: 16_000 })).toBe(165_600)+ // Providers reserve the reply allowance, so a prompt at the threshold still fits with it.+ expect(autoCompactAt({ contextWindow: 32_000, maxOutputTokens: 16_000 })).toBe(14_400)+ // An allowance past half the window counts as half, so some conversation still fits.+ expect(autoCompactAt({ contextWindow: 32_000, maxOutputTokens: 30_000 })).toBe(14_400)+ })++ test('the summary request leaves out images and cuts long text, tool inputs, and results', () => {+ const messages: ModelMessage[] = [+ {+ role: 'user',+ content: [+ { type: 'text', text: 'Match this' },+ { type: 'image', image: 'AAAA', mediaType: 'image/png' }+ ]+ },+ {+ role: 'assistant',+ content: [+ {+ type: 'tool-call',+ toolCallId: 'call-1',+ toolName: 'render',+ input: { jsx: 'x'.repeat(5000) }+ }+ ]+ },+ {+ role: 'tool',+ content: [+ {+ type: 'tool-result',+ toolCallId: 'call-1',+ toolName: 'render',+ output: {+ type: 'content',+ value: [+ { type: 'text', text: 'y'.repeat(5000) },+ { type: 'file-data', data: 'AAAA', mediaType: 'image/png' }+ ]+ }+ }+ ]+ },+ { role: 'user', content: 'z'.repeat(20_000) }+ ]+ const [request, call, result, pasted] = summarySource(messages)+ expect(request?.content).toEqual([{ type: 'text', text: 'Match this' }])+ const input = Array.isArray(call?.content) ? call.content[0] : null+ expect(input && 'input' in input && String(input.input)).toEndWith('more characters left out)')+ const output = Array.isArray(result?.content) ? result.content[0] : null+ expect(output && 'output' in output && output.output.type).toBe('text')+ expect(JSON.stringify(output)).not.toContain('AAAA')+ expect(pasted?.content).toBe(`${'z'.repeat(16_000)}… (4000 more characters left out)`)+ })++ test('past its budget the summary reads the latest summary and the newest messages', () => {+ const say = (role: 'user' | 'assistant', label: string): ModelMessage => ({+ role,+ content: `${label}${'w'.repeat(1000)}`+ })+ const labels = (messages: ModelMessage[]) =>+ messages.map((message) => String(message.content).at(0))+ const turns = [say('user', 'a'), say('assistant', 'b'), say('user', 'c'), say('assistant', 'd')]+ const summary = say('user', 's')+ expect(+ labels(summarySource([summary, ...turns], { summaryFirst: true, budget: 3200 }))+ ).toEqual(['s', 'c', 'd'])+ // Without a summary first, what is kept starts with a request.+ expect(labels(summarySource(turns, { budget: 3300 }))).toEqual(['c', 'd'])+ // The newest message stays past the budget, cut shorter to fit.+ const [newest] = summarySource([say('user', 'n'.repeat(20_000))], { budget: 2000 })+ expect(JSON.stringify(newest).length).toBeLessThanOrEqual(2000)+ expect(String(newest?.content)).toEndWith('more characters left out)')+ })++ test('a summary request too long for its model is tried again with a quarter of the budget', async () => {+ const sizes: number[] = []+ const model = new MockLanguageModelV4({+ doGenerate: async (options) => {+ sizes.push(JSON.stringify(options.prompt).length)+ if (sizes.length === 1) throw new Error('context_length_exceeded')+ return {+ content: [{ type: 'text', text: 'Summary' }],+ finishReason: { unified: 'stop', raw: undefined },+ usage: MOCK_USAGE,+ warnings: []+ }+ }+ })+ const turns = Array.from({ length: 8 }, (_, index) =>+ text(`${index}`, index % 2 ? 'assistant' : 'user', 'w'.repeat(1000))+ )+ expect(await summarizeConversation(turns, { model, budget: 8000 })).toBe('Summary')+ expect(sizes).toHaveLength(2)+ expect(sizes[1]).toBeLessThan(sizes[0] / 2)+ })++ test('the conversation’s model writes the summary, following the instructions it is given', async () => {+ let prompt: unknown+ const model = new MockLanguageModelV4({+ doGenerate: async (options) => {+ prompt = options.prompt+ return {+ content: [{ type: 'text', text: ' ## State\n- Hero built ' }],+ finishReason: { unified: 'stop', raw: undefined },+ usage: MOCK_USAGE,+ warnings: []+ }+ }+ })+ const summary = await summarizeConversation(+ [+ text('a', 'user', 'Make a hero'),+ {+ id: 'p',+ role: 'user',+ parts: [{ type: 'file', mediaType: 'image/png', url: 'data:image/png;base64,QUFBQQ==' }]+ },+ reply('b', 100)+ ],+ { model, instructions: 'keep the colors' }+ )+ expect(summary).toBe('## State\n- Hero built')+ expect(JSON.stringify(prompt)).not.toContain('QUFBQQ')+ expect(JSON.stringify(prompt)).toContain(+ 'Summarize the conversation above. Also follow these instructions for the summary: keep the colors'+ )+ })+})diff --git a/tests/app/ai/chat/compaction/use.test.ts b/tests/app/ai/chat/compaction/use.test.tsnew file mode 100644index 000000000..fcdac54b6--- /dev/null+++ b/tests/app/ai/chat/compaction/use.test.ts@@ -0,0 +1,60 @@+import { describe, expect, spyOn, test } from 'bun:test'++import type { UIMessage } from 'ai'+import { shallowRef } from 'vue'++import { compactionOf, messagesSinceCompaction } from '@/app/ai/chat/compaction/marker'+import { useChatCompaction } from '@/app/ai/chat/compaction/use'+import type { ChatInstance } from '@/app/ai/chat/submission/types'+import * as runtime from '@/app/ai/models/runtime'+import type { ResolvedAIModelRole } from '@/app/ai/models/types'++describe('useChatCompaction', () => {+ test('shows as compacting from the moment it is asked, while the chat is still reached', async () => {+ const connected = Promise.withResolvers<ChatInstance | null>()+ const compaction = useChatCompaction({+ chat: shallowRef<ChatInstance | null>(null),+ ensureChat: () => connected.promise+ })+ const compacted = compaction.compact({ trigger: 'manual' })+ expect(compaction.compacting.value).toBe(true)+ connected.resolve(null)+ expect(await compacted).toBe(false)+ expect(compaction.compacting.value).toBe(false)+ })++ test('an agent that compacts its own context gets a divider once it confirms', async () => {+ const created = spyOn(runtime, 'createAIModelRuntime').mockResolvedValue({+ kind: 'harness',+ role: {} as ResolvedAIModelRole+ })+ try {+ const messages: UIMessage[] = [+ { id: 'hi', role: 'user', parts: [{ type: 'text', text: 'Hi' }] },+ { id: 'hello', role: 'assistant', parts: [{ type: 'text', text: 'Hello' }] }+ ]+ const chat = { messages, status: 'ready' } as ChatInstance+ const asked: (string | undefined)[] = []+ const compaction = useChatCompaction({+ chat: shallowRef<ChatInstance | null>(chat),+ ensureChat: async () => chat,+ compactAgent: async (instructions) => {+ asked.push(instructions)+ return true+ }+ })+ expect(await compaction.compact({ trigger: 'manual', instructions: 'keep colors' })).toBe(+ true+ )+ expect(asked).toEqual(['keep colors'])+ expect(compactionOf(chat.messages[2])).toMatchObject({ trigger: 'manual', agent: true })+ // The chat's own model still reads the whole conversation.+ expect(messagesSinceCompaction(chat.messages).map((message) => message.id)).toEqual([+ 'hi',+ 'hello'+ ])+ } finally {+ created.mockRestore()+ }+ })+})diff --git a/tests/app/ai/chat/references/candidates.test.ts b/tests/app/ai/chat/references/candidates.test.tsindex 8c17a9159..9f31182c3 100644--- a/tests/app/ai/chat/references/candidates.test.ts+++ b/tests/app/ai/chat/references/candidates.test.ts@@ -2,7 +2,12 @@ import { describe, expect, test } from 'bun:test'import { SceneGraph } from '@open-pencil/scene-graph'-import { commandCandidates, referenceCandidates } from '@/app/ai/chat/references/candidates'+import {+ agentCommandCandidates,+ chatCommandCandidates,+ referenceCandidates+} from '@/app/ai/chat/references/candidates'+import { commandLink } from '@/app/ai/chat/references/command'import { resolveReference } from '@/app/ai/chat/references/resolve'import { skillFixture } from '#tests/helpers/chat/skills'@@ -45,16 +50,18 @@ describe('reference candidates', () => {expect(found.map(({ reference }) => reference.id)).toEqual([footer.id])})- test('commands are an ACP agent’s own, or else the skills the user can run', () => {+ test('commands are an ACP agent’s own, or else the chat’s and the skills the user can run', () => {const skills = [skillFixture(), skillFixture({ name: 'auto', userInvocable: false })]- expect(commandCandidates(null, skills).map((command) => command.insert)).toEqual([- '/skill:grid '+ const compact = { name: 'compact', description: 'Compact', hint: null }+ expect(chatCommandCandidates([compact], skills).map((command) => command.insert)).toEqual([+ `${commandLink('compact')} `,+ `${commandLink('skill:grid')} `])expect(- commandCandidates([{ name: 'review', description: 'Review', hint: null }], skills).map(+ agentCommandCandidates([{ name: 'review', description: 'Review', hint: null }]).map((command) => command.insert)- ).toEqual(['/review '])+ ).toEqual([`${commandLink('review')} `])})})diff --git a/tests/app/ai/chat/references/command.test.ts b/tests/app/ai/chat/references/command.test.tsnew file mode 100644index 000000000..f85906c54--- /dev/null+++ b/tests/app/ai/chat/references/command.test.ts@@ -0,0 +1,30 @@+import { describe, expect, test } from 'bun:test'++import { commandLink, commandsAsText, leadingCommand } from '@/app/ai/chat/references/command'+import { findReferences, referenceLink } from '@/app/ai/chat/references/link'++describe('commands chosen from /', () => {+ test('are reference links the chat reads as the command they name', () => {+ expect(findReferences(commandLink('compact')).map(({ reference }) => reference)).toEqual([+ { kind: 'command', id: 'compact', label: '/compact' }+ ])+ expect(leadingCommand(` ${commandLink('compact')} keep the colors `)).toEqual({+ name: 'compact',+ rest: 'keep the colors'+ })+ expect(leadingCommand(commandLink('skill:grid'))).toEqual({ name: 'skill:grid', rest: '' })+ })++ test('only a command the message starts with counts', () => {+ expect(leadingCommand('/compact keep the colors')).toBeNull()+ expect(leadingCommand(`Hi ${commandLink('compact')}`)).toBeNull()+ const hero = referenceLink({ kind: 'node', id: '1:2', label: 'Hero' })+ expect(leadingCommand(`${hero} ${commandLink('compact')}`)).toBeNull()+ })++ test('reach agents and models written out, while other references stay links', () => {+ const hero = referenceLink({ kind: 'node', id: '1:2', label: 'Hero' })+ expect(commandsAsText(`${commandLink('review')} the ${hero}`)).toBe(`/review the ${hero}`)+ expect(commandsAsText('plain text')).toBe('plain text')+ })+})diff --git a/tests/app/ai/chat/submission/use.test.ts b/tests/app/ai/chat/submission/use.test.tsindex 6604e090e..2e12652e9 100644--- a/tests/app/ai/chat/submission/use.test.ts+++ b/tests/app/ai/chat/submission/use.test.ts@@ -94,6 +94,24 @@ describe('useChatSubmission', () => {revoke.mockRestore()}})++ test('shows a message as sending until the chat it waits for takes it in', async () => {+ const connected = Promise.withResolvers<Chat<UIMessage> | null>()+ const { chat } = submission(() => connected.promise)+ const submitted = chat.submit(message)+ expect(chat.sending.value).toEqual(message)+ connected.resolve(fakeChat())+ expect(await submitted).toBe(true)+ expect(chat.sending.value).toBeNull()+ })++ test('stops showing a message that never reached the chat', async () => {+ const { chat } = submission(async () => null)+ const submitted = chat.submit(message)+ expect(chat.sending.value).toEqual(message)+ expect(await submitted).toBe(false)+ expect(chat.sending.value).toBeNull()+ })})function fakeChat(sendMessage: () => Promise<void> = async () => undefined): Chat<UIMessage> {diff --git a/tests/app/ai/chat/tool-calls/display.test.ts b/tests/app/ai/chat/tool-calls/display.test.tsindex d03bb4cdd..c857b6ee8 100644--- a/tests/app/ai/chat/tool-calls/display.test.ts+++ b/tests/app/ai/chat/tool-calls/display.test.ts@@ -145,6 +145,22 @@ describe('tool call display', () => {)).toEqual([[0, 2], 4])})++ test('puts each compaction within the reply before the step it kept', () => {+ const parts: ChatMessagePart[] = [+ { type: 'step-start' },+ call({ type: 'tool-render' }),+ { type: 'step-start' },+ call({ type: 'tool-render' }),+ { type: 'step-start' },+ { type: 'text', text: 'Done' }+ ]+ expect(+ groupMessageParts(parts, [1, 2]).map((group) =>+ group.kind === 'compaction' ? `compaction ${group.compaction}` : group.kind+ )+ ).toEqual(['tools', 'compaction 0', 'tools', 'compaction 1', 'part'])+ })})describe('toolHasInput', () => {diff --git a/tests/app/ai/chat/trace/rebuild.test.ts b/tests/app/ai/chat/trace/rebuild.test.tsindex 197d76b97..6f697b685 100644--- a/tests/app/ai/chat/trace/rebuild.test.ts+++ b/tests/app/ai/chat/trace/rebuild.test.ts@@ -7,6 +7,8 @@ import { MockLanguageModelV4 } from 'ai/test'import { FigmaAPI } from '@open-pencil/core/figma-api'+import type { ContextLimits } from '@/app/ai/chat/compaction/limits'+import { messagesSinceCompaction, replyCompactions } from '@/app/ai/chat/compaction/marker'import { matchesRecordedStep, rebuildStepMessages } from '@/app/ai/chat/trace/rebuild'import { createRunRecorder } from '@/app/ai/chat/trace/recorder'import { createAITools } from '@/app/ai/tools'@@ -55,7 +57,12 @@ afterEach(() => {aiToolOverrides.value = previousTools})-test('every recorded step rebuilds from the conversation to the request the model received', async () => {+interface RunOptions {+ steps: StreamChunk[][]+ contextLimits?: () => Promise<ContextLimits | null>+}++async function recordRun({ steps, contextLimits }: RunOptions) {const store = createEditorStore()spyOn(figmaFactory, 'makeFigmaFromStore').mockImplementation((editor, pageId) => {const api = new FigmaAPI(editor.graph)@@ -71,8 +78,14 @@ test('every recorded step rebuilds from the conversation to the request the modestream: simulateReadableStream<StreamChunk>({initialDelayInMs: null,chunkDelayInMs: null,- chunks: STEPS[call++] ?? []+ chunks: steps[call++] ?? []})+ }),+ doGenerate: async () => ({+ content: [{ type: 'text', text: 'Drew one rectangle.' }],+ finishReason: { unified: 'stop', raw: undefined },+ usage: MOCK_USAGE,+ warnings: []})})const traces = memoryTraceStore()@@ -85,7 +98,8 @@ test('every recorded step rebuilds from the conversation to the request the modemaxOutputTokens: 100,thinkingLevel: () => 'default',diagnosticContext: { sessionId: 'conversation', runId: 'run' },- recorder+ recorder,+ contextLimits})const earlier: UIMessage[] = [{ id: 'first', role: 'user', parts: [{ type: 'text', text: 'Hello' }] },@@ -102,8 +116,19 @@ test('every recorded step rebuilds from the conversation to the request the modelet reply: UIMessage | undefinedfor await (const message of readUIMessageStream({ stream })) reply = messageawait recorder.flush()-const run = expectDefined(traces.runs.get('run'))+ return {+ store,+ traces,+ run,+ reply: expectDefined(reply),+ conversation: [...earlier, expectDefined(reply)],+ tools: createAITools(store)+ }+}++test('every recorded step rebuilds from the conversation to the request the model received', async () => {+ const { traces, run, conversation, tools } = await recordRun({ steps: STEPS })expect(run.outcome).toBe('completed')expect(run.input).toEqual({ through: 'request', messages: 3 })expect(run.steps.map((step) => step.response.finishReason)).toEqual([@@ -117,8 +142,6 @@ test('every recorded step rebuilds from the conversation to the request the modetools: expect.arrayContaining([expect.objectContaining({ name: 'create_shape' })])})- const conversation = [...earlier, expectDefined(reply)]- const tools = createAITools(store)for (const step of run.steps) {expect(await matchesRecordedStep(conversation, run, step.index, tools)).toBe(true)}@@ -134,3 +157,34 @@ test('every recorded step rebuilds from the conversation to the request the modeconst last = await rebuildStepMessages(conversation, run, 2, tools)expect(last.filter((message) => message.role === 'tool')).toHaveLength(2)})++test('a reply that fills the context compacts between steps, again when it fills it again', async () => {+ // The first two steps' requests pass the threshold of a 100-token window.+ const full = { ...MOCK_USAGE, inputTokens: { ...MOCK_USAGE.inputTokens, total: 90 } }+ const filled = (step: StreamChunk[]): StreamChunk[] => [+ ...step.slice(0, -1),+ { type: 'finish', finishReason: { unified: 'tool-calls', raw: undefined }, usage: full }+ ]+ const steps = STEPS.with(0, filled(STEPS[0])).with(1, filled(STEPS[1]))+ const { run, reply, conversation, tools } = await recordRun({+ steps,+ contextLimits: async () => ({ contextWindow: 100, maxOutputTokens: 10 })+ })+ expect(run.outcome).toBe('completed')+ expect(replyCompactions(reply)).toEqual([+ { summary: 'Drew one rectangle.', trigger: 'auto', tokensBefore: 91, step: 0 },+ { summary: 'Drew one rectangle.', trigger: 'auto', tokensBefore: 91, step: 1 }+ ])+ // Each later request started from the latest summary and the last step's call and result.+ expect(run.steps.map((step) => step.request.messages)).toEqual([3, 3, 3])+ for (const step of run.steps) {+ expect(await matchesRecordedStep(conversation, run, step.index, tools)).toBe(true)+ }+ // The next request starts from the latest summary too, and keeps the steps after it.+ const next = messagesSinceCompaction(conversation)+ expect(next.map((message) => message.role)).toEqual(['user', 'assistant'])+ expect(JSON.stringify(next[0])).toContain('Drew one rectangle.')+ expect(JSON.stringify(next[1])).toContain('call-b')+ expect(JSON.stringify(next[1])).not.toContain('call-a')+ expect(JSON.stringify(next)).not.toContain('Draw two rectangles')+})diff --git a/tests/app/ai/skills/invoke.test.ts b/tests/app/ai/skills/invoke.test.tsindex af6e2a840..18ce4355b 100644--- a/tests/app/ai/skills/invoke.test.ts+++ b/tests/app/ai/skills/invoke.test.ts@@ -1,6 +1,7 @@import { describe, expect, test } from 'bun:test'import { appendSkillContext, stripModelNotes } from '@/app/ai/chat/context'+import { commandLink } from '@/app/ai/chat/references/command'import { invokedSkill } from '@/app/ai/skills/invoke'import type { SkillLibrary } from '@/app/ai/skills/library'import type { Skill } from '@/app/ai/skills/types'@@ -21,17 +22,22 @@ function library(skills: Skill[]): SkillLibrary & { reads: number } {describe('running a skill by name', () => {test('finds the skill a message starts with, read fresh', async () => {const skills = library([skillFixture()])- expect(await invokedSkill('/skill:grid lay out the hero', skills)).toMatchObject({+ expect(+ await invokedSkill(`${commandLink('skill:grid')} lay out the hero`, skills)+ ).toMatchObject({name: 'grid'})expect(skills.reads).toBe(1)})- test('ignores text without a command, unknown names, and skills not run by name', async () => {+ test('ignores text without a leading command, other commands, unknown names, and skills not run by name', async () => {const skills = library([skillFixture(), skillFixture({ name: 'brand', userInvocable: false })])- expect(await invokedSkill('lay out /skill:grid', skills)).toBeNull()- expect(await invokedSkill('/skill:missing', skills)).toBeNull()- expect(await invokedSkill('/skill:brand', skills)).toBeNull()+ expect(await invokedSkill(`lay out ${commandLink('skill:grid')}`, skills)).toBeNull()+ // Typed text is not a command; one is chosen from `/` or typed in full there.+ expect(await invokedSkill('/skill:grid lay out the hero', skills)).toBeNull()+ expect(await invokedSkill(commandLink('compact'), skills)).toBeNull()+ expect(await invokedSkill(commandLink('skill:missing'), skills)).toBeNull()+ expect(await invokedSkill(commandLink('skill:brand'), skills)).toBeNull()expect(skills.reads).toBe(2)})diff --git a/tests/app/ai/transports/pi.test.ts b/tests/app/ai/transports/pi.test.tsindex 82b7909d6..bc70c1c1f 100644--- a/tests/app/ai/transports/pi.test.ts+++ b/tests/app/ai/transports/pi.test.ts@@ -1,13 +1,23 @@import { expect, test } from 'bun:test'+import { readUIMessageStream, type UIMessage } from 'ai'+import * as v from 'valibot'+import type {HarnessSidecarMessage,HarnessTurnEvent,HarnessTurnUsage} from '@open-pencil/harness'+import {+ agentCompactionMessage,+ messagesSinceCompaction,+ replyCompactions+} from '@/app/ai/chat/compaction/marker'import { HarnessChatTransport } from '@/app/ai/transports/pi'+import { expectDefined } from '#tests/helpers/assert'+test('failed session stop kills the process without deleting resume state', async () => {let output: ReadableStreamDefaultController<HarnessSidecarMessage> | undefinedconst methods: string[] = []@@ -87,10 +97,13 @@ const configuration = {* A companion that answers session requests at once and holds each turn open, so the test* decides when its events and its answer arrive, as Pi's do after a Stop.*/+const promptParams = v.object({ prompt: v.string() })+function fakeCompanion({ turnsFail = false } = {}) {let output: ReadableStreamDefaultController<HarnessSidecarMessage> | undefinedconst methods: string[] = []const turns: string[] = []+ const prompts: unknown[] = []let spawns = 0const spawn = async () => {spawns++@@ -107,8 +120,11 @@ function fakeCompanion({ turnsFail = false } = {}) {if (typeof id !== 'string' || typeof method !== 'string') throw new Error('Invalid request')methods.push(method)if (method === 'session.turn' && turnsFail) throw new Error('Pipe closed')- if (method === 'session.turn') turns.push(id)- else output?.enqueue({ type: 'response', id, result: {} })+ if (method === 'session.turn') {+ turns.push(id)+ if ('params' in request && v.is(promptParams, request.params))+ prompts.push(request.params.prompt)+ } else output?.enqueue({ type: 'response', id, result: {} })}}}@@ -131,7 +147,8 @@ function fakeCompanion({ turnsFail = false } = {}) {id: turn,event: { type: 'finish', finishReason: 'stop', ...(usage ? { usage } : {}) }}),- turns+ turns,+ prompts}}@@ -273,3 +290,74 @@ test('text after a tool call starts a new part, and a stopped turn closes its teexpect(types.at(-1)).toBe('finish')await transport.destroy()})++test('compacting asks Pi to, and a turn keeps each compaction Pi runs in it', async () => {+ const companion = fakeCompanion()+ const transport = new HarnessChatTransport('compact-session', configuration, {}, companion.spawn)+ // Before any turn there is no context to compact.+ expect(await transport.compact()).toBe(false)++ const first = (await send(transport)).getReader()+ await Promise.resolve()+ const firstTurn = companion.turns.at(-1) ?? ''+ companion.text(firstTurn, 'Hi')+ companion.complete(firstTurn)+ while (!(await first.read()).done);+ expect(await transport.compact('keep the colors')).toBe(true)+ expect(companion.methods).toContain('session.compact')++ // The chat draws its own divider for it, which is not the person's message to send.+ const stream = await transport.sendMessages({+ chatId: 'test',+ trigger: 'submit-message',+ messageId: undefined,+ messages: [+ { id: 'hi', role: 'user', parts: [{ type: 'text', text: 'Hi' }] },+ { id: 'answer', role: 'assistant', parts: [{ type: 'text', text: 'Hello' }] },+ agentCompactionMessage('manual'),+ { id: 'again', role: 'user', parts: [{ type: 'text', text: 'Again' }] }+ ],+ abortSignal: undefined+ })+ await Promise.resolve()+ expect(companion.prompts.at(-1)).toBe('Again')+ const turn = companion.turns.at(-1) ?? ''+ // A manual compaction Pi reports later is the one the chat drew already.+ companion.event(turn, {+ type: 'compaction',+ trigger: 'manual',+ summary: 'Greeted.',+ tokensBefore: 1200+ })+ companion.text(turn, 'Hello again')+ // A long turn can fill the context; the reply keeps every compaction Pi runs in it.+ companion.event(turn, {+ type: 'compaction',+ trigger: 'auto',+ summary: 'Greeted twice.',+ tokensBefore: 3400+ })+ companion.text(turn, 'And again')+ companion.event(turn, {+ type: 'compaction',+ trigger: 'auto',+ summary: 'Greeted thrice.',+ tokensBefore: 3500+ })+ companion.text(turn, 'And once more')+ companion.complete(turn)+ let reply: UIMessage | undefined+ for await (const message of readUIMessageStream({ stream })) reply = message+ const message = expectDefined(reply)+ expect(replyCompactions(message)).toEqual([+ { summary: 'Greeted twice.', trigger: 'auto', tokensBefore: 3400, step: 1 },+ { summary: 'Greeted thrice.', trigger: 'auto', tokensBefore: 3500, step: 2 }+ ])+ // The latest summary stands before the step that followed it.+ const next = messagesSinceCompaction([message])+ expect(next.map((entry) => entry.role)).toEqual(['user', 'assistant'])+ expect(JSON.stringify(next[0])).toContain('Greeted thrice.')+ expect(JSON.stringify(next[1])).toContain('And once more')+ expect(JSON.stringify(next[1])).not.toContain('And again')+ await transport.destroy()+})diff --git a/tests/app/ai/transports/tool-loop.test.ts b/tests/app/ai/transports/tool-loop.test.tsindex 98161f5ac..d4828f4d0 100644--- a/tests/app/ai/transports/tool-loop.test.ts+++ b/tests/app/ai/transports/tool-loop.test.ts@@ -8,14 +8,17 @@ import * as v from 'valibot'import type { AIProviderID } from '@open-pencil/core/constants'import { FigmaAPI } from '@open-pencil/core/figma-api'+import { compactionMessage } from '@/app/ai/chat/compaction/marker'import { createRunRecorder } from '@/app/ai/chat/trace/recorder'import type { ThinkingLevel } from '@/app/ai/models/types'import { modelProviderAdapter } from '@/app/ai/providers/registry'+import { currentRun } from '@/app/ai/reply/run'import type { Skill } from '@/app/ai/skills/types'import { aiToolOverrides } from '@/app/ai/tools/preferences'import { createToolLoopTransport } from '@/app/ai/transports/tool-loop'import * as figmaFactory from '@/app/automation/bridge/figma-factory'import { createEditorStore } from '@/app/editor/session/create'+import { createDeferred } from '@/app/runtime/deferred'import { expectDefined } from '#tests/helpers/assert'import { skillFixture } from '#tests/helpers/chat/skills'@@ -331,3 +334,98 @@ test('a waiting message ends the run once the current tool calls finish', asyncstore.dispose()}})++test('a compacted conversation reaches the model as its summary and what followed it', async () => {+ const store = createEditorStore()+ let prompt: unknown+ const model = new MockLanguageModelV4({+ doStream: async (options) => {+ prompt = options.prompt+ return replyModel().doStream(options)+ }+ })+ try {+ const transport = createToolLoopTransport({+ store,+ providerID: 'anthropic',+ model,+ effectiveModelID: 'claude-test',+ maxOutputTokens: 100,+ thinkingLevel: () => 'default'+ })+ const marker = compactionMessage({+ summary: 'Built the hero.',+ trigger: 'manual',+ tokensBefore: 5000+ })+ const stream = await transport.sendMessages({+ trigger: 'submit-message',+ chatId: 'compacted',+ messageId: undefined,+ abortSignal: undefined,+ messages: [+ { id: 'old', role: 'user', parts: [{ type: 'text', text: 'Make a hero section' }] },+ { id: 'reply', role: 'assistant', parts: [{ type: 'text', text: 'Hero is done' }] },+ marker,+ { id: 'new', role: 'user', parts: [{ type: 'text', text: 'Now a footer' }] }+ ]+ })+ const chunks: unknown[] = []+ const reader = stream.getReader()+ for (let read = await reader.read(); !read.done; read = await reader.read())+ chunks.push(read.value)+ const sent = JSON.stringify(prompt)+ expect(sent).toContain('Built the hero.')+ expect(sent).toContain('Now a footer')+ expect(sent).not.toContain('Make a hero section')+ expect(sent).not.toContain('Hero is done')+ // The reply keeps what its last request held, for the context meter.+ expect(chunks).toContainEqual(+ expect.objectContaining({+ type: 'finish',+ messageMetadata: {+ usage: {+ contextTokens: 2,+ firstRequestTokens: 1,+ inputTokens: 1,+ outputTokens: 1,+ cacheReadTokens: null+ }+ }+ })+ )+ } finally {+ store.dispose()+ }+})++test('Stop ends a reply whose context-limit lookup has not answered', async () => {+ const store = createEditorStore()+ try {+ const transport = createToolLoopTransport({+ store,+ providerID: 'openai',+ model: replyModel(),+ effectiveModelID: 'test',+ maxOutputTokens: 100,+ thinkingLevel: () => 'default',+ // The model catalog never answers.+ contextLimits: () => createDeferred<null>().promise+ })+ const controller = new AbortController()+ const sent = transport.sendMessages({+ trigger: 'submit-message',+ chatId: 'stalled',+ messageId: undefined,+ abortSignal: controller.signal,+ messages: [{ id: 'user', role: 'user', parts: [{ type: 'text', text: 'Hello' }] }]+ })+ await Promise.resolve()+ expect(currentRun(store).active).toBe(true)+ controller.abort()+ await sent+ expect(currentRun(store).active).toBe(false)+ } finally {+ store.dispose()+ }+})diff --git a/tests/e2e/chat/history.spec.ts b/tests/e2e/chat/history.spec.tsindex 9d0b0e80a..f3a550023 100644--- a/tests/e2e/chat/history.spec.ts+++ b/tests/e2e/chat/history.spec.ts@@ -37,9 +37,7 @@ test('multiple conversations preserve messages and manual titles', async ({await page.getByRole('menuitem', { name: 'Rename', exact: true }).click()await page.getByRole('textbox', { name: 'Conversation title' }).fill('First design')await page.getByRole('button', { name: 'Save', exact: true }).click()- await expect(- page.getByRole('button', { name: 'Conversation history', exact: true })- ).toContainText('First design')+ await expect(page.getByTestId('chat-title')).toHaveText('First design')})test('saved transcripts remain readable after reload without provider setup', async ({diff --git a/tests/e2e/chat/profiles.spec.ts b/tests/e2e/chat/profiles.spec.tsindex 5e1f4b976..aa277882e 100644--- a/tests/e2e/chat/profiles.spec.ts+++ b/tests/e2e/chat/profiles.spec.ts@@ -18,7 +18,7 @@ test('Design profile selector exposes provider and capabilities', async ({test('OpenRouter accepts a custom model ID from Settings', async ({ configuredChat: chat }) => {const customModel = 'meta-llama/llama-3.3-70b-instruct'- await chat.page.getByTestId('provider-settings-trigger').click()+ await chat.openModelSettings()await chat.page.locator('[data-model-id]').first().click()await chat.page.getByLabel('Model ID').click()// The catalog replaces the fallback list once it loads; pick only after it has settled.@@ -33,7 +33,7 @@ test('OpenRouter accepts a custom model ID from Settings', async ({ configuredCh})test('Get API key links to the provider key page', async ({ configuredChat: chat }) => {- await chat.page.getByTestId('provider-settings-trigger').click()+ await chat.openModelSettings()await chat.page.locator('[data-model-id]').first().click()await expect(chat.page.getByRole('link', { name: 'Get API key' })).toHaveAttribute(diff --git a/tests/e2e/chat/reasoning.spec.ts b/tests/e2e/chat/reasoning.spec.tsindex 8693043ae..82442f2cd 100644--- a/tests/e2e/chat/reasoning.spec.ts+++ b/tests/e2e/chat/reasoning.spec.ts@@ -5,7 +5,7 @@ test('expand while thinking auto-collapses but preserves manual opening', asyncconfiguredChat: chat,page}) => {- await page.getByTestId('provider-settings-trigger').click()+ await chat.openModelSettings()await page.getByRole('combobox', { name: 'Reasoning display' }).click()await page.getByRole('option', { name: 'Expand while thinking', exact: true }).click()await page.getByTestId('app-settings-done').click()@@ -67,7 +67,7 @@ test('reasoning preferences use AI settings and persist across reload', async ({configuredChat: chat,page}) => {- await page.getByTestId('provider-settings-trigger').click()+ await chat.openModelSettings()const display = page.getByRole('combobox', { name: 'Reasoning display' })await expect(display).toContainText('Collapsed by default')await display.click()@@ -88,6 +88,6 @@ test('reasoning preferences use AI settings and persist across reload', async ({await expect(page.locator('[data-slot="chat-reasoning-content"]')).toBeHidden()await page.reload()await chat.chatTab.click()- await page.getByTestId('provider-settings-trigger').click()+ await chat.openModelSettings()await expect(display).toContainText('Expanded by default')})diff --git a/tests/e2e/chat/recovery.spec.ts b/tests/e2e/chat/recovery.spec.tsindex a0b095736..c78931eff 100644--- a/tests/e2e/chat/recovery.spec.ts+++ b/tests/e2e/chat/recovery.spec.ts@@ -24,7 +24,7 @@ test('recovering an unsaved document restores its selected conversation automatiawait chat.chatTab.click()await expect(chat.userMessage()).toContainText('Conversation belonging to recovered document')await expect(chat.assistantMessage()).toBeVisible()- await expect(- page.getByRole('button', { name: 'Conversation history', exact: true })- ).toContainText('Conversation belonging to recovered document')+ await expect(page.getByTestId('chat-title')).toHaveText(+ 'Conversation belonging to recovered document'+ )})diff --git a/tests/e2e/chat/references.spec.ts b/tests/e2e/chat/references.spec.tsindex 3a0674300..9f99dcac5 100644--- a/tests/e2e/chat/references.spec.ts+++ b/tests/e2e/chat/references.spec.ts@@ -49,7 +49,7 @@ test('@ inserts a layer as a chip that the reply shows and that selects the layetest('/ starts a message with a skill', async ({ configuredChat: chat }) => {const { page } = chat- await page.getByTestId('provider-settings-trigger').click()+ await chat.openModelSettings()await page.getByRole('tab', { name: 'Skills', exact: true }).click()const chooser = page.waitForEvent('filechooser')await page.getByRole('button', { name: 'Upload skill' }).click()@@ -68,6 +68,20 @@ test('/ starts a message with a skill', async ({ configuredChat: chat }) => {await page.getByRole('option', { name: /skill:grid/ }).click()await page.keyboard.type('lay out the hero')await expect(chat.input).toHaveText('/skill:grid lay out the hero')+ // The command is a chip, as a reference is, so the chat reads it from the link.+ await expect(chat.input.locator('[data-reference-kind="command"]')).toHaveText('/skill:grid')+})++test('a command typed in full becomes a chip once a space follows it', async ({+ configuredChat: chat+}) => {+ const { page } = chat+ await chat.input.click()+ await page.keyboard.type('/compact')+ await expect(page.getByRole('option', { name: /\/compact/ })).toBeVisible()+ await page.keyboard.type(' keep the colors')+ await expect(chat.input.locator('[data-reference-kind="command"]')).toHaveText('/compact')+ await expect(chat.input).toHaveText('/compact keep the colors')})test('editing a sent message keeps its chips and Escape cancels', async ({diff --git a/tests/e2e/ui/tooltips.webkit.spec.ts b/tests/e2e/ui/tooltips.webkit.spec.tsindex 981bde338..659b8230c 100644--- a/tests/e2e/ui/tooltips.webkit.spec.ts+++ b/tests/e2e/ui/tooltips.webkit.spec.ts@@ -37,11 +37,12 @@ test('tooltips stay hoverable and clickable in WebKit', async () => {await editor.page.getByTestId('api-key-save').click()await expect(editor.page.getByTestId('chat-input')).toBeVisible()- const settings = editor.page.getByTestId('provider-settings-trigger')- await settings.hover()+ const attach = editor.page.getByRole('button', { name: 'Attach images' })+ await attach.hover()await expect(- editor.page.locator('[role=tooltip]').filter({ hasText: 'Provider settings' })+ editor.page.locator('[role=tooltip]').filter({ hasText: 'Attach images' })).toBeVisible()- await settings.click()- await expect(editor.page.getByTestId('provider-settings-provider')).toBeVisible()+ const chooser = editor.page.waitForEvent('filechooser')+ await attach.click()+ await chooser})diff --git a/tests/engine/app/ai/failure.test.ts b/tests/engine/app/ai/failure.test.tsindex 0cc224b1d..8eba85a02 100644--- a/tests/engine/app/ai/failure.test.ts+++ b/tests/engine/app/ai/failure.test.ts@@ -5,10 +5,29 @@ import { APICallError, StreamProviderError } from 'ai'import {classifyAIChatError,classifyAIChatFinish,+ isContextLimitError,isInsufficientCreditError} from '@/app/ai/chat/failure'describe('AI chat failures', () => {+ test('a request past the context window is its own failure, which compaction can fix', () => {+ const openAI = new APICallError({+ message: 'Bad Request',+ url: 'https://api.openai.com/v1/responses',+ requestBodyValues: {},+ statusCode: 400,+ responseBody:+ '{"error":{"code":"context_length_exceeded","message":"Your input exceeds the context window"}}'+ })+ expect(isContextLimitError(openAI)).toBe(true)+ expect(classifyAIChatError(openAI).reason).toBe('context-limit')+ expect(+ isContextLimitError(new Error('prompt is too long: 210000 tokens > 200000 maximum'))+ ).toBe(true)+ expect(isContextLimitError({ statusCode: 413 })).toBe(true)+ expect(isContextLimitError(new Error('Rate limit exceeded'))).toBe(false)+ })+test('recognizes provider credit and quota failures', () => {expect(isInsufficientCreditError({ statusCode: 402 })).toBe(true)expect(isInsufficientCreditError(new Error('Insufficient balance. Please top up.'))).toBe(true)diff --git a/tests/engine/tauri/harness-process.test.ts b/tests/engine/tauri/harness-process.test.tsindex 518700868..08da8c4ab 100644--- a/tests/engine/tauri/harness-process.test.ts+++ b/tests/engine/tauri/harness-process.test.ts@@ -1,5 +1,7 @@import { afterEach, describe, expect, test } from 'bun:test'+import type { HarnessCompactionEvent } from '@open-pencil/harness'+import { spawnHarnessProcess } from '@/app/ai/agents/pi/process'import { clearTauriMocks, mockTauriIPC } from '#tests/helpers/tauri/mocks'@@ -52,6 +54,34 @@ describe('Harness sidecar process', () => {).not.toContain('secret')})+ test('passes on a compaction the agent reports', async () => {+ let onEvent: ((event: unknown) => void) | undefined+ await mockTauriIPC((cmd, args) => {+ if (cmd === 'plugin:shell|spawn') {+ onEvent = (args as { onEvent: { onmessage: (event: unknown) => void } }).onEvent.onmessage+ return 47+ }+ return null+ })+ const process = await spawnHarnessProcess({+ environment: {},+ onUnexpectedClose: () => undefined+ })+ const event: HarnessCompactionEvent = {+ type: 'compaction',+ trigger: 'manual',+ summary: 'Greeted.',+ tokensBefore: 1200+ }+ const line = `${JSON.stringify({ type: 'turn.event', id: 'turn', event })}\n`+ onEvent?.({ event: 'Stdout', payload: Array.from(new TextEncoder().encode(line)) })+ expect((await process.messages.getReader().read()).value).toEqual({+ type: 'turn.event',+ id: 'turn',+ event+ })+ })+test('routes the npm launcher through its cmd scope entry on Windows', async () => {const originalNavigator = Object.getOwnPropertyDescriptor(globalThis, 'navigator')try {diff --git a/tests/helpers/chat/harness.ts b/tests/helpers/chat/harness.tsindex a7451cebf..544e3bd6a 100644--- a/tests/helpers/chat/harness.ts+++ b/tests/helpers/chat/harness.ts@@ -27,6 +27,12 @@ export class ChatHarness {return this.page.getByTestId('chat-profile-selector')}+ /** Model settings open from the model picker's Manage models and roles. */+ async openModelSettings(): Promise<void> {+ await this.profileTrigger.click()+ await this.page.getByRole('button', { name: 'Manage models and roles…' }).click()+ }+userMessage() {return this.page.getByTestId('chat-message-user').last()}