Compare commits

...
31 Commits
Author SHA1 Message Date
David KayaandCopilot 898e27e64d refactor: remove premium request subtitle from ChatPane footer
The Activity Panel already shows premium request counts in the
Session Usage section, so the ChatPane footer only needs the
context-window bar.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 00:47:08 +01:00
David KayaandCopilot 92832c6116 feat: surface Copilot usage and quota data across the UI
Add three layers of usage visibility:

- ChatPane footer: premium request count, AIU consumed, and quota
  remaining below the existing context-window bar
- Settings / CopilotStatusCard: on-demand account quota section with
  progress bars, overage indicators, and reset dates fetched via
  the new get-quota sidecar command
- Activity Panel: per-agent token/cost/duration totals on each agent
  row and a Session Usage summary section between agents and timeline

Backend (sidecar):
- New get-quota command using SDK account.getQuota RPC
- New assistant-usage turn-scoped event from SDK assistant.usage
- QuotaSnapshotMapper for both typed and untyped SDK quota payloads
- DTOs: GetQuotaCommandDto, QuotaSnapshotDto, AccountQuotaResultEventDto,
  AssistantUsageEventDto

Frontend:
- Shared types: AssistantUsageEvent, QuotaSnapshot, GetQuotaCommand
- IPC bridge: getQuota channel, assistant-usage event dispatch
- State: SessionRequestUsageMap accumulator with per-agent breakdown
- 8 new tests for accumulator logic and formatting helpers

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 00:46:09 +01:00
David KayaandCopilot 48efbf36f9 fix: prevent crash when pressing Shift+Enter in empty code block
The CodeHighlightPlugin's selection restoration could create an invalid
Lexical selection targeting a LineBreakNode with type 'element'. Since
LineBreakNode is not an ElementNode, Lexical threw during reconciliation
and the LexicalErrorBoundary replaced the editor with an error state.

The fix ensures findPoint never targets a LineBreakNode directly.
Instead it falls back to an element-level selection on the parent
CodeNode using the child index, which is always a valid target.

Extracted the selection helpers (getCodeNodeAbsoluteOffset,
findCodeNodeSelectionPoint, restoreCodeNodeSelection) into
markdownEditor.ts for testability and added regression tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 00:12:20 +01:00
David KayaandCopilot 21f0ccb184 feat: show sub-agent activity cards in chat stream
Display compact status cards in the chat transcript showing each
sub-agent's name, current activity (Thinking, Using grep, etc.),
and elapsed time. Cards appear while sub-agents are running and
clear when the session goes idle.

- Extend SessionEventRecord with description, error, toolCallId,
  and model fields for subagent events
- Forward additional subagent fields in handleTurnScopedEvent
- Add subagentTracker reducer to derive active subagent state from
  session events, including agent-activity correlation
- Create SubagentActivityCard component with spinner, status icon,
  agent name, activity label, and live elapsed timer
- Wire activeSubagents state in App.tsx and pass to ChatPane
- Add 16 unit tests for the subagent tracker

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 00:04:05 +01:00
David KayaandCopilot 7921b6648f fix: auto-complete previous pending messages when a new assistant message starts
When the agent produces multiple intermediate responses during a turn,
each gets a unique messageId but all stay pending until finalizeTurn().
This caused multiple stacked 'Thinking' bubbles in the chat transcript.

Now, when a new messageId arrives in applyTurnDelta, any previously
pending assistant messages are marked complete and message-complete
events are emitted before the new message-delta. The renderer reducer
mirrors this logic for defensive consistency.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 23:59:06 +01:00
David KayaandCopilot 6d12cce836 fix: prevent composer action bar from overlaying text field
Change the bottom action bar from absolute positioning to normal
document flow so it sits below the editable area instead of floating
on top. Reduce editable bottom padding since buttons no longer overlap.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 23:37:01 +01:00
David KayaandCopilot e4142a6def refactor: move Terminal and Prompts pills into composer
Declutter the pill row above the chat composer by relocating Terminal
and Prompts pills from the session-config rows into the composer's
bottom action bar (left side). The session-config row now only shows
session-scoped controls: Tools, Approval, Model, and Thinking.

The relocated pills use a lighter, borderless style matching the
inner-composer aesthetic alongside the existing Attach, Plan mode,
and Send buttons.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 23:34:58 +01:00
David KayaandCopilot edd4c7381a feat: add integrated terminal frontend
- Add TerminalPanel component with xterm.js, FitAddon, drag-to-resize,
  header bar (status dot, shell label, cwd, restart/minimize/close)
- Modify AppShell to accept terminal panel in vertical flex layout
- Add terminal state management in App.tsx (open/height/running state,
  Ctrl+backtick toggle, height persistence via IPC)
- Add InlineTerminalPill to composer pill row (both single/multi-agent)
- Install @xterm/xterm and @xterm/addon-fit as devDependencies
- Update ARCHITECTURE.md with frontend terminal component details
- Add Integrated Terminal feature card to marketing website

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 23:29:18 +01:00
David KayaandCopilot 251316596c feat: add integrated terminal backend
- add a PTY manager with platform shell resolution and streamed data/exit events
- expose terminal lifecycle and terminal height IPC through preload and app service
- persist terminal panel height in workspace settings and document the backend contract
- add backend tests and validate native packaging with bun run package

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 23:15:16 +01:00
David KayaandCopilot 651a7d27fc feat: show MCP probe progress in approval pill
- Thread mcpProbingServerIds from workspace state through App → ChatPane → InlineApprovalPill
- Show animated spinner and 'probing…' label on pill button while any MCP server is being probed
- Show per-server probing indicator in popover: spinning icon, 'probing…' badge, hidden toggle
- Render approval pill during probing even when no MCP tools are known yet

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 22:08:25 +01:00
David KayaandCopilot cc13ed29f5 feat: stream MCP probe progress
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 21:58:07 +01:00
David KayaandCopilot 9ddd831b34 fix: preserve probed MCP tools across session switches
mergeDiscoveredToolingState now carries over probedTools from existing
servers when the config fingerprint is unchanged. The equality check in
syncProjectDiscoveredTooling also strips probedTools before comparing,
so runtime-only probe data never triggers a spurious state replacement.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 20:09:45 +01:00
David KayaandCopilot 08876f694d fix: handle MCP tools with complex JSON schema \ in outputSchema
The SDK's listTools() calls cacheToolMetadata() which compiles
outputSchema validators. Servers with \ in their schemas (e.g.,
icm-mcp) cause a JSON schema resolution error. Fall back to a raw
JSON-RPC tools/list request that skips schema compilation, since we
only need tool names and descriptions for the approval pill.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 20:00:53 +01:00
David KayaandCopilot 216b17b2ac fix: add origin-only well-known URL fallback for OAuth discovery
Some MCP servers (e.g., eschat.microsoft.com/mcp) serve their
OAuth Protected Resource Metadata at the origin without the path
suffix. Add a third candidate URL that strips the path, matching
VS Code's discovery behavior.

Tried in order:
1. RFC 9728: {origin}/.well-known/{suffix}{path}
2. Appended: {origin}{path}/.well-known/{suffix}
3. Origin-only: {origin}/.well-known/{suffix}

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 19:53:25 +01:00
David KayaandCopilot b985a06df3 fix: re-probe MCP servers after OAuth authentication
Tokens are in-memory and empty at startup, so HTTP servers requiring
OAuth return 401 during initial probing. After the user completes
OAuth (either via session auth prompt or proactive auth), re-probe
the authenticated server so its tools appear in the approval pill
without requiring an app restart.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 19:47:45 +01:00
David KayaandCopilot 169a9617c8 fix: improve MCP probe error reporting and SSE fallback
When SSE fallback gets 405 (confirming a Streamable HTTP server),
surface the original Streamable HTTP error instead of the misleading
SSE 405. Extract HTTP status codes from SDK error objects to produce
clearer log messages like 'HTTP 401: Streamable HTTP error: ...'.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 19:43:53 +01:00
David KayaandCopilot e38a663834 fix: fall back to SSE transport when Streamable HTTP probe fails
Many MCP servers only support legacy SSE despite being configured as
generic HTTP endpoints. Follow the MCP SDK's recommended fallback
pattern: try Streamable HTTP first, then retry with SSE on failure.
This matches VS Code's behavior for these servers.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 19:39:23 +01:00
David KayaandCopilot f0114058ba fix: show MCP tools in all provider groups when shared
When multiple MCP servers expose the same tool names (e.g., several
kusto-mcp instances), each server's group now shows its tools instead
of only the first server getting the tools and others showing 0/0.

Deduplicate the effectiveAutoApprovedCount to avoid double-counting
shared tools in the pill header.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 19:35:56 +01:00
David KayaandCopilot 6505493735 fix: resolve nested button DOM nesting in approval pill
Change the approval group header from <button> to a <div> with
role='button' and keyboard handling to avoid nesting the GroupToggle
<button> inside another <button>, which is invalid HTML.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 19:33:41 +01:00
David KayaandCopilot b4b0bf54d2 fix: improve MCP tool probing reliability
- Increase default probe timeout from 10s to 30s to handle slow
  package managers (uvx, npx) that install on first run
- Add console logging for probe success/failure to aid debugging
- Probe manually configured MCP servers (not just discovered ones)
  so all servers with wildcard tools get their tools discovered

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 19:30:42 +01:00
David KayaandCopilot 8312a47bf1 feat: discover MCP tools via protocol probing for approval pill
When MCP server configs declare wildcard tools (empty tools array),
the Copilot SDK has no API to list individual tool names. Add direct
MCP protocol probing using @modelcontextprotocol/sdk to discover
available tools from each accepted server.

- Add McpToolProber service supporting stdio/SSE/HTTP transports
- Probe accepted MCP servers on project load, acceptance, and rescan
- Store probed tools on DiscoveredMcpServer and McpServerDefinition
- Use probed tools in listApprovalToolDefinitions when declared tools
  are empty, so the approval pill shows individual tool toggles
- Remove unused isMcpServerApprovalKey helper
- Fix effectiveAutoApprovedCount Math.max workaround in ChatPane
- Add comprehensive tests for probed tool behavior
- Update ARCHITECTURE.md tooling integration section

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 19:23:57 +01:00
David KayaandCopilot 3937904548 feat: add server-level MCP auto-approval for wildcard tool servers
MCP servers configured with empty tools arrays (wildcard) now appear in the
auto-approval pill with a server-level toggle. When toggled, a server-level
approval key (mcp_server:<name>) is added to autoApprovedToolNames. The
sidecar matches this key against PermissionRequestMcp.ServerName to auto-
approve all tools from that server without needing individual tool names.

- Add buildMcpServerApprovalKey/isMcpServerApprovalKey helpers
- Create approval groups for all MCP servers including empty-tools ones
- Add serverApprovalKey to ApprovalToolGroup for server-level toggles
- Update sidecar RequiresToolCallApproval to check server-level keys
- Include server-level keys in listApprovalToolNames for pruning safety
- Add tests for both shared domain and sidecar approval matching

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 18:34:19 +01:00
David KayaandCopilot 53a08e0ed4 feat: redesign auto-approval pill with server-level grouping and batch toggle
Group MCP tools by server and LSP tools by profile in the approval popover
instead of showing a flat list. Each server/profile group gets a collapsible
header with a batch toggle to approve/unapprove all tools at once. Add a
search filter (visible when >10 tools) and partial-state indicators for
groups with mixed approval. Add groupApprovalToolsByProvider shared helper
with tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 18:18:17 +01:00
David KayaandCopilot 5ad85db0f5 refactor: redesign project settings with sidebar navigation
Replace flat scrolling layout with sidebar + content panel matching the global
SettingsPanel pattern. Sections: Overview, Instructions (with expandable
previews), Custom Agents (with enable/disable), Prompt Files, MCP Servers,
Danger Zone. Add count badges, pending indicators, project name in header,
section-level rescan buttons, and contextual empty states.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 17:59:31 +01:00
David KayaandCopilot dd203ddde5 feat: add frontend customization UI and prompt picker
Add Copilot Customization section to ProjectSettingsPanel with instruction file
previews, agent profile enable/disable toggles, and prompt file listing. Add
InlinePromptPill to chat input for selecting and sending prompt files with
variable substitution. Wire rescan and agent profile IPC in App.tsx. Update
website with Copilot Customization feature card.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 17:40:21 +01:00
David KayaandCopilot 75b9ff667a feat: support project copilot customization
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 17:29:37 +01:00
David KayaandCopilot f53907755a feat: add dedicated project settings panel accessible from sidebar
Move project-specific settings (discovered MCP servers) out of the
global Settings panel and into a dedicated ProjectSettingsPanel overlay.
Users can now access any project's settings via a gear icon on the
sidebar project header, or by clicking the pending-discovery badge.

- Add ProjectSettingsPanel component with project info, discovered MCP
  server management (accept/dismiss/rescan), and project removal
- Add gear icon and clickable discovery badge to Sidebar ProjectGroup
- Remove project-specific discovery props from SettingsPanel (now
  shows only user-level discovered servers)
- Wire ProjectSettingsPanel overlay in App.tsx with auto-close on
  project removal

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 16:51:57 +01:00
David KayaandCopilot 3c57cb6ded fix: clean up interrupted session state on restart
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 16:22:12 +01:00
David KayaandCopilot b946359c69 fix: stabilize macOS CI validation
Remove the packaging-only create-dmg dependency in favor of native hdiutil, and make the hook runner working-directory test assert behavior without depending on macOS temp-path canonicalization.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 15:43:13 +01:00
David Kaya e4eb221308 fix: new screenshot for website 2026-03-28 15:30:41 +01:00
David KayaandCopilot 036fb4d4fa fix: stabilize cross-platform CI checks
Use the repository's default Electron import pattern in the MCP OAuth service, make the attachment-path test platform-neutral, and ensure the hook runner cwd/env test drains stdin before asserting shell output.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 15:27:48 +01:00
77 changed files with 7842 additions and 432 deletions
+15 -2
View File
@@ -55,7 +55,7 @@ flowchart LR
| --- | --- | --- | --- |
| Renderer | Screens, interaction, local view composition, theme application | Filesystem, process spawning, raw Electron access, Copilot runtime | Typed preload API and pushed events |
| Preload | Narrow bridge between browser context and Electron IPC | Business logic, persistence, orchestration | `ipcRenderer` / `ipcMain` |
| Main process | Workspace mutation, persistence, git inspection, session lifecycle, native window state, sidecar lifecycle | UI rendering, LLM orchestration internals | IPC, filesystem, git CLI, stdio with sidecar |
| Main process | Workspace mutation, persistence, git inspection, session lifecycle, native window state, sidecar lifecycle, PTY-backed terminal lifecycle | UI rendering, LLM orchestration internals | IPC, filesystem, git CLI, stdio with sidecar, native child processes |
| Sidecar | Capability discovery, pattern validation, run execution, streaming deltas and activity | UI, workspace persistence, Electron APIs | Line-delimited JSON over stdio |
| External systems | Git data, Copilot account/model access, OS window chrome | Application state and UI behavior | Controlled adapters owned by main or sidecar |
@@ -124,6 +124,8 @@ Projects are the container for context. There are two kinds:
The scratchpad is modeled inside the same workspace system instead of as a separate subsystem. That keeps the UI and session model consistent while still allowing special rules for scratchpad behavior. Each scratchpad session receives its own working directory under the shared scratchpad root, so session-created files stay isolated from other scratchpad conversations.
Project-backed entries also persist scanned Copilot customization metadata discovered from repository files such as `.github/copilot-instructions.md`, `AGENTS.md`, `.github/agents/*.agent.md`, and `.github/prompts/*.prompt.md`. The main process owns that scan step and stores the normalized results on the project record so repo instructions and enabled custom agent profiles can participate in later run execution without turning the renderer into a filesystem crawler.
### Patterns
Patterns describe how agents collaborate. The architecture supports:
@@ -185,16 +187,20 @@ Typical examples:
- create session
- send message
- update theme
- create or restart the integrated terminal
- toggle session tooling
- update session approval overrides
The renderer does not reach into Electron or the filesystem directly. It talks through a constrained API surface.
The integrated terminal uses the same boundary. The renderer never opens a shell directly; it asks the main process to create or restart a PTY, sends fire-and-forget input and resize messages over IPC, and listens for streamed terminal data and exit events pushed back through preload. The `TerminalPanel` component manages an xterm.js terminal instance with a FitAddon, a drag-to-resize handle, and a header bar showing shell status.
### 2. Main process <-> sidecar
This is a structured stdio protocol used for:
- capability discovery
- on-demand account quota lookup
- pattern validation
- run execution
- streaming partial output
@@ -207,14 +213,19 @@ The protocol also carries **turn-scoped lifecycle events** alongside output delt
- **Sub-agent events**: started, completed, failed, selected, deselected — surfaced when custom agents are defined
- **Skill invocation events**: emitted when an agent-side skill is triggered
- **Hook lifecycle events**: start and end of configured project hook commands discovered from `.github/hooks/*.json`; Aryx suppresses the SDK's built-in no-op hook chatter so the UI only sees meaningful hook activity
- **Assistant usage events**: per-LLM-call tokens, cost, AIU, and quota snapshots from the Copilot SDK's `assistant.usage` stream
- **Session compaction events**: start and complete, with token-reduction metrics when infinite sessions trigger context trimming
- **Session usage events**: current token count and context-window limit for usage-bar rendering
- **Session usage events**: current token count and context-window limit from `session.usage_info` for context-bar rendering
- **Pending-messages-modified events**: emitted when mid-turn steering changes the pending message queue
These events flow through a single `onTurnScopedEvent` callback on the `runTurn` command, avoiding per-event-type callback proliferation. The main process maps each event to a `SessionEventRecord` and pushes it to the renderer, where lightweight state maps (activity, usage, turn-event log) consume them without touching the persisted workspace.
The same boundary also supports server-scoped sidecar commands that do not require a live Copilot session. The new `get-quota` command uses the SDK's `account.getQuota` RPC to fetch account quota snapshots on demand, then returns them as a `quota-result` protocol event followed by the usual `command-complete` sentinel.
For project-backed sessions, the sidecar also discovers GitHub Copilot CLI hook definitions from `.github/hooks/*.json` under the repository root. Those files are parsed and merged once per run bundle, then projected onto the SDK session hook delegates. Hook commands run synchronously in the sidecar through the platform shell, with stdin JSON payloads shaped to match Copilot CLI hook expectations as closely as the SDK allows. Hook failures are logged to stderr and treated as non-fatal diagnostics, while `preToolUse` hook outputs can still deny a tool call before Aryx falls back to its built-in approval policy.
The `run-turn` command now also carries a project-instruction payload derived from scanned repo customization files. The main process composes that payload from repo-level instruction files and merges enabled discovered custom agent profiles into the primary pattern agent's Copilot configuration before sending the command across the stdio boundary. The sidecar then folds those project instructions into the final SDK system message alongside the agent's own instructions and runtime guidance.
## Security model
Security in this system is mostly about **desktop trust boundaries**.
@@ -271,6 +282,8 @@ Tooling is deliberately split into two levels:
- **dynamic runtime tools** reported by the Copilot CLI, with a fallback catalog for startup/offline cases
- **global definitions** for MCP servers and LSP profiles
- **MCP tool discovery** — when MCP server configs declare wildcard tools (empty `tools` array), the main process probes each server directly via the MCP protocol `tools/list` method to discover available tools, using the same auth credentials Aryx manages for OAuth-protected servers
- **incremental probe progress** — MCP probing runs concurrently and publishes per-server progress through the pushed workspace snapshot, using the runtime-only `mcpProbingServerIds` field so the renderer can reflect in-flight discovery without persisting transient UI state
- **pattern defaults** where tool-call approval is enabled by default, plus which known runtime tools can bypass manual approval
- **per-session overrides** for both tool enablement and tool auto-approval
+145 -149
View File
@@ -6,6 +6,7 @@
"name": "kopaya",
"dependencies": {
"keytar": "^7.9.0",
"node-pty": "^1.1.0",
},
"devDependencies": {
"@dagrejs/dagre": "^3.0.0",
@@ -17,14 +18,16 @@
"@lexical/markdown": "0.42.0",
"@lexical/react": "0.42.0",
"@lexical/rich-text": "0.42.0",
"@modelcontextprotocol/sdk": "^1.28.0",
"@tailwindcss/vite": "^4.2.2",
"@types/node": "^25.5.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "5.1.0",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"@xyflow/react": "^12.10.1",
"bun-types": "^1.3.11",
"create-dmg": "^8.1.0",
"electron": "^41.0.3",
"electron-vite": "^5.0.0",
"highlight.js": "^11.11.1",
@@ -39,6 +42,7 @@
"typescript": "^5.9.3",
"typescript-language-server": "^5.1.3",
"vite": "7.1.10",
"yaml": "^2.8.3",
},
},
},
@@ -153,6 +157,8 @@
"@floating-ui/utils": ["@floating-ui/utils@0.2.11", "", {}, "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg=="],
"@hono/node-server": ["@hono/node-server@1.19.11", "", { "peerDependencies": { "hono": "^4" } }, "sha512-dr8/3zEaB+p0D2n/IUrlPF1HZm586qgJNXK1a9fhg/PzdtkK7Ksd5l312tJX2yBuALqDYBlG20QEbayqPyxn+g=="],
"@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],
"@jridgewell/remapping": ["@jridgewell/remapping@2.3.5", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="],
@@ -215,6 +221,8 @@
"@malept/cross-spawn-promise": ["@malept/cross-spawn-promise@1.1.1", "", { "dependencies": { "cross-spawn": "^7.0.1" } }, "sha512-RTBGWL5FWQcg9orDOCcp4LvItNzUPcyEU9bwaeJX0rJ1IQxzucC48Y0/sQLp/g6t99IQgAlGIaesJS+gTn7tVQ=="],
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.28.0", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-gmloF+i+flI8ouQK7MWW4mOwuMh4RePBuPFAEPC6+pdqyWOUMDOixb6qZ69owLJpz6XmyllCouc4t8YWO+E2Nw=="],
"@preact/signals-core": ["@preact/signals-core@1.14.0", "", {}, "sha512-AowtCcCU/33lFlh1zRFf/u+12rfrhtNakj7UpaGEsmMwUKpKWMVvcktOGcwBBNiB4lWrZWc01LhiyyzVklJyaQ=="],
"@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.0-beta.43", "", {}, "sha512-5Uxg7fQUCmfhax7FJke2+8B6cqgeUJUD9o2uXIKXhD+mG0mL6NObmVoi9wXEU1tY89mZKgAYA6fTbftx3q2ZPQ=="],
@@ -269,12 +277,8 @@
"@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.60.0", "", { "os": "win32", "cpu": "x64" }, "sha512-PrsWNQ8BuE00O3Xsx3ALh2Df8fAj9+cvvX9AIA6o4KpATR98c9mud4XtDWVvsEuyia5U4tVSTKygawyJkjm60w=="],
"@sec-ant/readable-stream": ["@sec-ant/readable-stream@0.4.1", "", {}, "sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg=="],
"@sindresorhus/is": ["@sindresorhus/is@4.6.0", "", {}, "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw=="],
"@sindresorhus/merge-streams": ["@sindresorhus/merge-streams@4.0.0", "", {}, "sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ=="],
"@szmarczak/http-timer": ["@szmarczak/http-timer@4.0.6", "", { "dependencies": { "defer-to-connect": "^2.0.0" } }, "sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w=="],
"@tailwindcss/node": ["@tailwindcss/node@4.2.2", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.19.0", "jiti": "^2.6.1", "lightningcss": "1.32.0", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.2.2" } }, "sha512-pXS+wJ2gZpVXqFaUEjojq7jzMpTGf8rU6ipJz5ovJV6PUGmlJ+jvIwGrzdHdQ80Sg+wmQxUFuoW1UAAwHNEdFA=="],
@@ -367,31 +371,33 @@
"@xmldom/xmldom": ["@xmldom/xmldom@0.8.11", "", {}, "sha512-cQzWCtO6C8TQiYl1ruKNn2U6Ao4o4WBBcbL61yJl84x+j5sOWWFU9X7DpND8XZG3daDppSsigMdfAIl2upQBRw=="],
"@xterm/addon-fit": ["@xterm/addon-fit@0.11.0", "", {}, "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g=="],
"@xterm/xterm": ["@xterm/xterm@6.0.0", "", {}, "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg=="],
"@xyflow/react": ["@xyflow/react@12.10.1", "", { "dependencies": { "@xyflow/system": "0.0.75", "classcat": "^5.0.3", "zustand": "^4.4.0" }, "peerDependencies": { "react": ">=17", "react-dom": ">=17" } }, "sha512-5eSWtIK/+rkldOuFbOOz44CRgQRjtS9v5nufk77DV+XBnfCGL9HAQ8PG00o2ZYKqkEU/Ak6wrKC95Tu+2zuK3Q=="],
"@xyflow/system": ["@xyflow/system@0.0.75", "", { "dependencies": { "@types/d3-drag": "^3.0.7", "@types/d3-interpolate": "^3.0.4", "@types/d3-selection": "^3.0.10", "@types/d3-transition": "^3.0.8", "@types/d3-zoom": "^3.0.8", "d3-drag": "^3.0.0", "d3-interpolate": "^3.0.1", "d3-selection": "^3.0.0", "d3-zoom": "^3.0.0" } }, "sha512-iXs+AGFLi8w/VlAoc/iSxk+CxfT6o64Uw/k0CKASOPqjqz6E0rb5jFZgJtXGZCpfQI6OQpu5EnumP5fGxQheaQ=="],
"ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="],
"accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="],
"appdmg": ["appdmg@0.6.6", "", { "dependencies": { "async": "^1.4.2", "ds-store": "^0.1.5", "execa": "^1.0.0", "fs-temp": "^1.0.0", "fs-xattr": "^0.3.0", "image-size": "^0.7.4", "is-my-json-valid": "^2.20.0", "minimist": "^1.1.3", "parse-color": "^1.0.0", "path-exists": "^4.0.0", "repeat-string": "^1.5.4" }, "os": "darwin", "bin": { "appdmg": "bin/appdmg.js" } }, "sha512-GRmFKlCG+PWbcYF4LUNonTYmy0GjguDy6Jh9WP8mpd0T6j80XIJyXBiWlD0U+MLNhqV9Nhx49Gl9GpVToulpLg=="],
"ajv": ["ajv@8.18.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A=="],
"async": ["async@1.5.2", "", {}, "sha512-nSVgobk4rv61R9PUSDtYt7mPVB2olxNR5RWJcAsH676/ef11bUZwvu7+RGYrYauVdDPcO519v68wRhXQtxsV9w=="],
"ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="],
"bail": ["bail@2.0.2", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="],
"balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
"base32-encode": ["base32-encode@1.2.0", "", { "dependencies": { "to-data-view": "^1.1.0" } }, "sha512-cHFU8XeRyx0GgmoWi5qHMCVRiqU6J3MHWxVgun7jggCBUpVzm1Ir7M9dYr2whjSNc3tFeXfQ/oZjQu/4u55h9A=="],
"base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
"baseline-browser-mapping": ["baseline-browser-mapping@2.10.10", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-sUoJ3IMxx4AyRqO4MLeHlnGDkyXRoUG0/AI9fjK+vS72ekpV0yWVY7O0BVjmBcRtkNcsAO2QDZ4tdKKGoI6YaQ=="],
"bl": ["bl@4.1.0", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="],
"boolean": ["boolean@3.2.0", "", {}, "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw=="],
"body-parser": ["body-parser@2.2.2", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^1.0.5", "debug": "^4.4.3", "http-errors": "^2.0.0", "iconv-lite": "^0.7.0", "on-finished": "^2.4.1", "qs": "^6.14.1", "raw-body": "^3.0.1", "type-is": "^2.0.1" } }, "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA=="],
"bplist-creator": ["bplist-creator@0.0.8", "", { "dependencies": { "stream-buffers": "~2.2.0" } }, "sha512-Za9JKzD6fjLC16oX2wsXfc+qBEhJBJB1YPInoAQpMLhDuj5aVOv1baGeIQSq1Fr3OCqzvsoQcSBSwGId/Ja2PA=="],
"boolean": ["boolean@3.2.0", "", {}, "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw=="],
"brace-expansion": ["brace-expansion@5.0.5", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ=="],
@@ -403,18 +409,22 @@
"bun-types": ["bun-types@1.3.11", "", { "dependencies": { "@types/node": "*" } }, "sha512-1KGPpoxQWl9f6wcZh57LvrPIInQMn2TQ7jsgxqpRzg+l0QPOFvJVH7HmvHo/AiPgwXy+/Thf6Ov3EdVn1vOabg=="],
"bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],
"cac": ["cac@6.7.14", "", {}, "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ=="],
"cacheable-lookup": ["cacheable-lookup@5.0.4", "", {}, "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA=="],
"cacheable-request": ["cacheable-request@7.0.4", "", { "dependencies": { "clone-response": "^1.0.2", "get-stream": "^5.1.0", "http-cache-semantics": "^4.0.0", "keyv": "^4.0.0", "lowercase-keys": "^2.0.0", "normalize-url": "^6.0.1", "responselike": "^2.0.0" } }, "sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg=="],
"call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="],
"call-bound": ["call-bound@1.0.4", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="],
"caniuse-lite": ["caniuse-lite@1.0.30001780", "", {}, "sha512-llngX0E7nQci5BPJDqoZSbuZ5Bcs9F5db7EtgfwBerX9XGtkkiO4NwfDDIRzHTTwcYC8vC7bmeUEPGrKlR/TkQ=="],
"ccount": ["ccount@2.0.1", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="],
"chalk": ["chalk@5.6.2", "", {}, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="],
"character-entities": ["character-entities@2.0.2", "", {}, "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ=="],
"character-entities-html4": ["character-entities-html4@2.1.0", "", {}, "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA=="],
@@ -427,28 +437,28 @@
"classcat": ["classcat@5.0.5", "", {}, "sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w=="],
"cli-cursor": ["cli-cursor@5.0.0", "", { "dependencies": { "restore-cursor": "^5.0.0" } }, "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw=="],
"cli-spinners": ["cli-spinners@3.4.0", "", {}, "sha512-bXfOC4QcT1tKXGorxL3wbJm6XJPDqEnij2gQ2m7ESQuE+/z9YFIWnl/5RpTiKWbMq3EVKR4fRLJGn6DVfu0mpw=="],
"clone-response": ["clone-response@1.0.3", "", { "dependencies": { "mimic-response": "^1.0.0" } }, "sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA=="],
"color-convert": ["color-convert@0.5.3", "", {}, "sha512-RwBeO/B/vZR3dfKL1ye/vx8MHZ40ugzpyfeVG5GsiuGnrlMWe2o8wxBbLCpw9CsxV+wHuzYlCiWnybrIA0ling=="],
"comma-separated-tokens": ["comma-separated-tokens@2.0.3", "", {}, "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="],
"commander": ["commander@13.1.0", "", {}, "sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw=="],
"content-disposition": ["content-disposition@1.0.1", "", {}, "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q=="],
"content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="],
"convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="],
"create-dmg": ["create-dmg@8.1.0", "", { "dependencies": { "appdmg": "^0.6.6", "execa": "^9.6.1", "icns-lib": "^1.0.1", "meow": "^14.0.0", "ora": "^9.1.0", "plist": "^3.1.0", "tempy": "^3.1.1" }, "bin": { "create-dmg": "cli.js" } }, "sha512-O/r2pqZE5wgZ/mabUkD+/lt5hQs4VX+YhbFhcIj84ecg8AL+oMAoMjekNJkVVpx5UspTxNDqBxvnWI2VqSW92g=="],
"cookie": ["cookie@0.7.2", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="],
"cookie-signature": ["cookie-signature@1.2.2", "", {}, "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="],
"cors": ["cors@2.8.6", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="],
"cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
"cross-spawn-windows-exe": ["cross-spawn-windows-exe@1.2.0", "", { "dependencies": { "@malept/cross-spawn-promise": "^1.1.0", "is-wsl": "^2.2.0", "which": "^2.0.2" } }, "sha512-mkLtJJcYbDCxEG7Js6eUnUNndWjyUZwJ3H7bErmmtOYU/Zb99DyUkpamuIZE0b3bhmJyZ7D90uS6f+CGxRRjOw=="],
"crypto-random-string": ["crypto-random-string@4.0.0", "", { "dependencies": { "type-fest": "^1.0.1" } }, "sha512-x8dy3RnvYdlUcPOjkEHqozhiwzKNSq7GcPuXFbnyMOCHxX8V3OgIg/pYuabl2sbUPfIJaeAQB7PMOK8DFIdoRA=="],
"csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
"d3-color": ["d3-color@3.1.0", "", {}, "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA=="],
@@ -483,6 +493,8 @@
"define-properties": ["define-properties@1.2.1", "", { "dependencies": { "define-data-property": "^1.0.1", "has-property-descriptors": "^1.0.0", "object-keys": "^1.1.1" } }, "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg=="],
"depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="],
"dequal": ["dequal@2.0.3", "", {}, "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA=="],
"detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
@@ -491,7 +503,9 @@
"devlop": ["devlop@1.1.0", "", { "dependencies": { "dequal": "^2.0.0" } }, "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA=="],
"ds-store": ["ds-store@0.1.6", "", { "dependencies": { "bplist-creator": "~0.0.3", "macos-alias": "~0.2.5", "tn1150": "^0.1.0" } }, "sha512-kY21M6Lz+76OS3bnCzjdsJSF7LBpLYGCVfavW8TgQD2XkcqIZ86W0y9qUDZu6fp7SIZzqosMDW2zi7zVFfv4hw=="],
"dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
"ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],
"electron": ["electron@41.0.3", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-IDjx8liW1q+r7+MOip5W1Eo1eMwJzVObmYrd9yz2dPCkS7XlgLq3qPVMR80TpiROFp73iY30kTzMdpA6fEVs3A=="],
@@ -499,7 +513,7 @@
"electron-vite": ["electron-vite@5.0.0", "", { "dependencies": { "@babel/core": "^7.28.4", "@babel/plugin-transform-arrow-functions": "^7.27.1", "cac": "^6.7.14", "esbuild": "^0.25.11", "magic-string": "^0.30.19", "picocolors": "^1.1.1" }, "peerDependencies": { "@swc/core": "^1.0.0", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0" }, "optionalPeers": ["@swc/core"], "bin": { "electron-vite": "bin/electron-vite.js" } }, "sha512-OHp/vjdlubNlhNkPkL/+3JD34ii5ov7M0GpuXEVdQeqdQ3ulvVR7Dg/rNBLfS5XPIFwgoBLDf9sjjrL+CuDyRQ=="],
"encode-utf8": ["encode-utf8@1.0.3", "", {}, "sha512-ucAnuBEhUK4boH2HjVYG5Q2mQyPorvv0u/ocS+zhdw0S8AlHYY+GOFhP1Gio5z4icpP2ivFSvhtFjQi8+T9ppw=="],
"encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="],
"end-of-stream": ["end-of-stream@1.4.5", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="],
@@ -513,51 +527,65 @@
"es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="],
"es-object-atoms": ["es-object-atoms@1.1.1", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA=="],
"es6-error": ["es6-error@4.1.1", "", {}, "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg=="],
"esbuild": ["esbuild@0.25.12", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.12", "@esbuild/android-arm": "0.25.12", "@esbuild/android-arm64": "0.25.12", "@esbuild/android-x64": "0.25.12", "@esbuild/darwin-arm64": "0.25.12", "@esbuild/darwin-x64": "0.25.12", "@esbuild/freebsd-arm64": "0.25.12", "@esbuild/freebsd-x64": "0.25.12", "@esbuild/linux-arm": "0.25.12", "@esbuild/linux-arm64": "0.25.12", "@esbuild/linux-ia32": "0.25.12", "@esbuild/linux-loong64": "0.25.12", "@esbuild/linux-mips64el": "0.25.12", "@esbuild/linux-ppc64": "0.25.12", "@esbuild/linux-riscv64": "0.25.12", "@esbuild/linux-s390x": "0.25.12", "@esbuild/linux-x64": "0.25.12", "@esbuild/netbsd-arm64": "0.25.12", "@esbuild/netbsd-x64": "0.25.12", "@esbuild/openbsd-arm64": "0.25.12", "@esbuild/openbsd-x64": "0.25.12", "@esbuild/openharmony-arm64": "0.25.12", "@esbuild/sunos-x64": "0.25.12", "@esbuild/win32-arm64": "0.25.12", "@esbuild/win32-ia32": "0.25.12", "@esbuild/win32-x64": "0.25.12" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg=="],
"escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
"escape-html": ["escape-html@1.0.3", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="],
"escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="],
"estree-util-is-identifier-name": ["estree-util-is-identifier-name@3.0.0", "", {}, "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg=="],
"execa": ["execa@9.6.1", "", { "dependencies": { "@sindresorhus/merge-streams": "^4.0.0", "cross-spawn": "^7.0.6", "figures": "^6.1.0", "get-stream": "^9.0.0", "human-signals": "^8.0.1", "is-plain-obj": "^4.1.0", "is-stream": "^4.0.1", "npm-run-path": "^6.0.0", "pretty-ms": "^9.2.0", "signal-exit": "^4.1.0", "strip-final-newline": "^4.0.0", "yoctocolors": "^2.1.1" } }, "sha512-9Be3ZoN4LmYR90tUoVu2te2BsbzHfhJyfEiAVfz7N5/zv+jduIfLrV2xdQXOHbaD6KgpGdO9PRPM1Y4Q9QkPkA=="],
"etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="],
"eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],
"eventsource-parser": ["eventsource-parser@3.0.6", "", {}, "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg=="],
"expand-template": ["expand-template@2.0.3", "", {}, "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg=="],
"express": ["express@5.2.1", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", "content-disposition": "^1.0.0", "content-type": "^1.0.5", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.7", "qs": "^6.14.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.0.1", "vary": "^1.1.2" } }, "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw=="],
"express-rate-limit": ["express-rate-limit@8.3.1", "", { "dependencies": { "ip-address": "10.1.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-D1dKN+cmyPWuvB+G2SREQDzPY1agpBIcTa9sJxOPMCNeH3gwzhqJRDWCXW3gg0y//+LQ/8j52JbMROWyrKdMdw=="],
"extend": ["extend@3.0.2", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="],
"extract-zip": ["extract-zip@2.0.1", "", { "dependencies": { "debug": "^4.1.1", "get-stream": "^5.1.0", "yauzl": "^2.10.0" }, "optionalDependencies": { "@types/yauzl": "^2.9.1" }, "bin": { "extract-zip": "cli.js" } }, "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg=="],
"fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
"fast-uri": ["fast-uri@3.1.0", "", {}, "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA=="],
"fd-slicer": ["fd-slicer@1.1.0", "", { "dependencies": { "pend": "~1.2.0" } }, "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g=="],
"fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
"figures": ["figures@6.1.0", "", { "dependencies": { "is-unicode-supported": "^2.0.0" } }, "sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg=="],
"finalhandler": ["finalhandler@2.1.1", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="],
"fmix": ["fmix@0.1.0", "", { "dependencies": { "imul": "^1.0.0" } }, "sha512-Y6hyofImk9JdzU8k5INtTXX1cu8LDlePWDFU5sftm9H+zKCr5SGrVjdhkvsim646cw5zD0nADj8oHyXMZmCZ9w=="],
"forwarded": ["forwarded@0.2.0", "", {}, "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow=="],
"fresh": ["fresh@2.0.0", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="],
"fs-constants": ["fs-constants@1.0.0", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],
"fs-extra": ["fs-extra@8.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="],
"fs-temp": ["fs-temp@1.2.1", "", { "dependencies": { "random-path": "^0.1.0" } }, "sha512-okTwLB7/Qsq82G6iN5zZJFsOfZtx2/pqrA7Hk/9fvy+c+eJS9CvgGXT2uNxwnI14BDY9L/jQPkaBgSvlKfSW9w=="],
"fs-xattr": ["fs-xattr@0.3.1", "", { "os": "!win32" }, "sha512-UVqkrEW0GfDabw4C3HOrFlxKfx0eeigfRne69FxSBdHIP8Qt5Sq6Pu3RM9KmMlkygtC4pPKkj5CiPO5USnj2GA=="],
"fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"generate-function": ["generate-function@2.3.1", "", { "dependencies": { "is-property": "^1.0.2" } }, "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ=="],
"generate-object-property": ["generate-object-property@1.2.0", "", { "dependencies": { "is-property": "^1.0.0" } }, "sha512-TuOwZWgJ2VAMEGJvAyPWvpqxSANF0LDpmyHauMjFYzaACvn+QTT/AZomvPCzVBV7yDN3OmwHQ5OvHaeLKre3JQ=="],
"function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
"gensync": ["gensync@1.0.0-beta.2", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="],
"get-east-asian-width": ["get-east-asian-width@1.5.0", "", {}, "sha512-CQ+bEO+Tva/qlmw24dCejulK5pMzVnUOFOijVogd3KQs07HnRIgp8TGipvCCRT06xeYEbpbgwaCxglFyiuIcmA=="],
"get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="],
"get-stream": ["get-stream@9.0.1", "", { "dependencies": { "@sec-ant/readable-stream": "^0.4.1", "is-stream": "^4.0.1" } }, "sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA=="],
"get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],
"get-stream": ["get-stream@5.2.0", "", { "dependencies": { "pump": "^3.0.0" } }, "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA=="],
"github-from-package": ["github-from-package@0.0.0", "", {}, "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw=="],
@@ -577,34 +605,40 @@
"has-property-descriptors": ["has-property-descriptors@1.0.2", "", { "dependencies": { "es-define-property": "^1.0.0" } }, "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg=="],
"has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="],
"hasown": ["hasown@2.0.2", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ=="],
"hast-util-to-jsx-runtime": ["hast-util-to-jsx-runtime@2.3.6", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-js": "^1.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" } }, "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg=="],
"hast-util-whitespace": ["hast-util-whitespace@3.0.0", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw=="],
"highlight.js": ["highlight.js@11.11.1", "", {}, "sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w=="],
"hono": ["hono@4.12.9", "", {}, "sha512-wy3T8Zm2bsEvxKZM5w21VdHDDcwVS1yUFFY6i8UobSsKfFceT7TOwhbhfKsDyx7tYQlmRM5FLpIuYvNFyjctiA=="],
"html-url-attributes": ["html-url-attributes@3.0.1", "", {}, "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ=="],
"http-cache-semantics": ["http-cache-semantics@4.2.0", "", {}, "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ=="],
"http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="],
"http2-wrapper": ["http2-wrapper@1.0.3", "", { "dependencies": { "quick-lru": "^5.1.1", "resolve-alpn": "^1.0.0" } }, "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg=="],
"human-signals": ["human-signals@8.0.1", "", {}, "sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ=="],
"icns-lib": ["icns-lib@1.0.1", "", {}, "sha512-J7+RDRQApG/vChY5TP043NitBcNC7QMn1kOgGvlAkyrK65hozAaSwTNsTZ2HJh+br9e1NlzpBreAOpk4YuhOJA=="],
"iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],
"ieee754": ["ieee754@1.2.1", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
"image-size": ["image-size@0.7.5", "", { "bin": { "image-size": "bin/image-size.js" } }, "sha512-Hiyv+mXHfFEP7LzUL/llg9RwFxxY+o9N3JVLIeG5E7iFIFAalxvRU9UZthBdYDEVnzHMgjnKJPPpay5BWf1g9g=="],
"imul": ["imul@1.0.1", "", {}, "sha512-WFAgfwPLAjU66EKt6vRdTlKj4nAgIDQzh29JonLa4Bqtl6D8JrIMvWjCnx7xEjVNmP3U0fM5o8ZObk7d0f62bA=="],
"inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
"ini": ["ini@1.3.8", "", {}, "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="],
"inline-style-parser": ["inline-style-parser@0.2.7", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="],
"ip-address": ["ip-address@10.1.0", "", {}, "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q=="],
"ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="],
"is-alphabetical": ["is-alphabetical@2.0.1", "", {}, "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ=="],
"is-alphanumerical": ["is-alphanumerical@2.0.1", "", { "dependencies": { "is-alphabetical": "^2.0.0", "is-decimal": "^2.0.0" } }, "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw=="],
@@ -615,19 +649,9 @@
"is-hexadecimal": ["is-hexadecimal@2.0.1", "", {}, "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg=="],
"is-interactive": ["is-interactive@2.0.0", "", {}, "sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ=="],
"is-my-ip-valid": ["is-my-ip-valid@1.0.1", "", {}, "sha512-jxc8cBcOWbNK2i2aTkCZP6i7wkHF1bqKFrwEHuN5Jtg5BSaZHUZQ/JTOJwoV41YvHnOaRyWWh72T/KvfNz9DJg=="],
"is-my-json-valid": ["is-my-json-valid@2.20.6", "", { "dependencies": { "generate-function": "^2.0.0", "generate-object-property": "^1.1.0", "is-my-ip-valid": "^1.0.0", "jsonpointer": "^5.0.0", "xtend": "^4.0.0" } }, "sha512-1JQwulVNjx8UqkPE/bqDaxtH4PXCe/2VRh/y3p99heOV87HG4Id5/VfDswd+YiAfHcRTfDlWgISycnHuhZq1aw=="],
"is-plain-obj": ["is-plain-obj@4.1.0", "", {}, "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg=="],
"is-property": ["is-property@1.0.2", "", {}, "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g=="],
"is-stream": ["is-stream@4.0.1", "", {}, "sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A=="],
"is-unicode-supported": ["is-unicode-supported@2.1.0", "", {}, "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ=="],
"is-promise": ["is-promise@4.0.0", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="],
"is-wsl": ["is-wsl@2.2.0", "", { "dependencies": { "is-docker": "^2.0.0" } }, "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww=="],
@@ -637,20 +661,24 @@
"jiti": ["jiti@2.6.1", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ=="],
"jose": ["jose@6.2.2", "", {}, "sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ=="],
"js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
"jsesc": ["jsesc@3.1.0", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="],
"json-buffer": ["json-buffer@3.0.1", "", {}, "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ=="],
"json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
"json-schema-typed": ["json-schema-typed@8.0.2", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="],
"json-stringify-safe": ["json-stringify-safe@5.0.1", "", {}, "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA=="],
"json5": ["json5@2.2.3", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="],
"jsonfile": ["jsonfile@4.0.0", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="],
"jsonpointer": ["jsonpointer@5.0.1", "", {}, "sha512-p/nXbhSEcu3pZRdkW1OfJhpsVtW1gd4Wa1fnQc9YLiTfAjn0312eMKimbdIQzuZl9aa9xUGaRlP9T/CJE/ditQ=="],
"keytar": ["keytar@7.9.0", "", { "dependencies": { "node-addon-api": "^4.3.0", "prebuild-install": "^7.0.1" } }, "sha512-VPD8mtVtm5JNtA2AErl6Chp06JBfy7diFQ7TQQhdpWOl6MrCRB+eRbvAZUsbGQS9kiMq0coJsy0W0vHpDCkWsQ=="],
"keyv": ["keyv@4.5.4", "", { "dependencies": { "json-buffer": "3.0.1" } }, "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw=="],
@@ -683,8 +711,6 @@
"lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.32.0", "", { "os": "win32", "cpu": "x64" }, "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q=="],
"log-symbols": ["log-symbols@7.0.1", "", { "dependencies": { "is-unicode-supported": "^2.0.0", "yoctocolors": "^2.1.1" } }, "sha512-ja1E3yCr9i/0hmBVaM0bfwDjnGy8I/s6PP4DFp+yP+a+mrHO4Rm7DtmnqROTUkHIkqffC84YY7AeqX6oFk0WFg=="],
"longest-streak": ["longest-streak@3.1.0", "", {}, "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g=="],
"lowercase-keys": ["lowercase-keys@2.0.0", "", {}, "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA=="],
@@ -693,14 +719,14 @@
"lucide-react": ["lucide-react@0.577.0", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-4LjoFv2eEPwYDPg/CUdBJQSDfPyzXCRrVW1X7jrx/trgxnxkHFjnVZINbzvzxjN70dxychOfg+FTYwBiS3pQ5A=="],
"macos-alias": ["macos-alias@0.2.12", "", { "dependencies": { "nan": "^2.4.0" }, "os": "darwin" }, "sha512-yiLHa7cfJcGRFq4FrR4tMlpNHb4Vy4mWnpajlSSIFM5k4Lv8/7BbbDLzCAVogWNl0LlLhizRp1drXv0hK9h0Yw=="],
"magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
"markdown-table": ["markdown-table@3.0.4", "", {}, "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw=="],
"matcher": ["matcher@3.0.0", "", { "dependencies": { "escape-string-regexp": "^4.0.0" } }, "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng=="],
"math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],
"mdast-util-find-and-replace": ["mdast-util-find-and-replace@3.0.2", "", { "dependencies": { "@types/mdast": "^4.0.0", "escape-string-regexp": "^5.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.0.0" } }, "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg=="],
"mdast-util-from-markdown": ["mdast-util-from-markdown@2.0.3", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "mdast-util-to-string": "^4.0.0", "micromark": "^4.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q=="],
@@ -731,7 +757,9 @@
"mdast-util-to-string": ["mdast-util-to-string@4.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0" } }, "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg=="],
"meow": ["meow@14.1.0", "", {}, "sha512-EDYo6VlmtnumlcBCbh1gLJ//9jvM/ndXHfVXIFrZVr6fGcwTUyCTFNTLCKuY3ffbK8L/+3Mzqnd58RojiZqHVw=="],
"media-typer": ["media-typer@1.1.0", "", {}, "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw=="],
"merge-descriptors": ["merge-descriptors@2.0.0", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="],
"micromark": ["micromark@4.0.2", "", { "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA=="],
@@ -789,7 +817,9 @@
"micromark-util-types": ["micromark-util-types@2.0.2", "", {}, "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA=="],
"mimic-function": ["mimic-function@5.0.1", "", {}, "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA=="],
"mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],
"mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],
"mimic-response": ["mimic-response@3.1.0", "", {}, "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ=="],
@@ -803,75 +833,75 @@
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"murmur-32": ["murmur-32@0.2.0", "", { "dependencies": { "encode-utf8": "^1.0.3", "fmix": "^0.1.0", "imul": "^1.0.0" } }, "sha512-ZkcWZudylwF+ir3Ld1n7gL6bI2mQAzXvSobPwVtu8aYi2sbXeipeSkdcanRLzIofLcM5F53lGaKm2dk7orBi7Q=="],
"nan": ["nan@2.26.2", "", {}, "sha512-0tTvBTYkt3tdGw22nrAy50x7gpbGCCFH3AFcyS5WiUu7Eu4vWlri1woE6qHBSfy11vksDqkiwjOnlR7WV8G1Hw=="],
"nanoid": ["nanoid@3.3.11", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="],
"napi-build-utils": ["napi-build-utils@2.0.0", "", {}, "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA=="],
"nice-try": ["nice-try@1.0.5", "", {}, "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ=="],
"negotiator": ["negotiator@1.0.0", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="],
"node-abi": ["node-abi@3.89.0", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-6u9UwL0HlAl21+agMN3YAMXcKByMqwGx+pq+P76vii5f7hTPtKDp08/H9py6DY+cfDw7kQNTGEj/rly3IgbNQA=="],
"node-addon-api": ["node-addon-api@4.3.0", "", {}, "sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ=="],
"node-pty": ["node-pty@1.1.0", "", { "dependencies": { "node-addon-api": "^7.1.0" } }, "sha512-20JqtutY6JPXTUnL0ij1uad7Qe1baT46lyolh2sSENDd4sTzKZ4nmAFkeAARDKwmlLjPx6XKRlwRUxwjOy+lUg=="],
"node-releases": ["node-releases@2.0.36", "", {}, "sha512-TdC8FSgHz8Mwtw9g5L4gR/Sh9XhSP/0DEkQxfEFXOpiul5IiHgHan2VhYYb6agDSfp4KuvltmGApc8HMgUrIkA=="],
"normalize-url": ["normalize-url@6.1.0", "", {}, "sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A=="],
"npm-run-path": ["npm-run-path@6.0.0", "", { "dependencies": { "path-key": "^4.0.0", "unicorn-magic": "^0.3.0" } }, "sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA=="],
"object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
"object-inspect": ["object-inspect@1.13.4", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="],
"object-keys": ["object-keys@1.1.1", "", {}, "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA=="],
"on-finished": ["on-finished@2.4.1", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="],
"once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
"onetime": ["onetime@7.0.0", "", { "dependencies": { "mimic-function": "^5.0.0" } }, "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ=="],
"ora": ["ora@9.3.0", "", { "dependencies": { "chalk": "^5.6.2", "cli-cursor": "^5.0.0", "cli-spinners": "^3.2.0", "is-interactive": "^2.0.0", "is-unicode-supported": "^2.1.0", "log-symbols": "^7.0.1", "stdin-discarder": "^0.3.1", "string-width": "^8.1.0" } }, "sha512-lBX72MWFduWEf7v7uWf5DHp9Jn5BI8bNPGuFgtXMmr2uDz2Gz2749y3am3agSDdkhHPHYmmxEGSKH85ZLGzgXw=="],
"p-cancelable": ["p-cancelable@2.1.1", "", {}, "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg=="],
"p-finally": ["p-finally@1.0.0", "", {}, "sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow=="],
"parse-color": ["parse-color@1.0.0", "", { "dependencies": { "color-convert": "~0.5.0" } }, "sha512-fuDHYgFHJGbpGMgw9skY/bj3HL/Jrn4l/5rSspy00DoT4RyLnDcRvPxdZ+r6OFwIsgAuhDh4I09tAId4mI12bw=="],
"parse-entities": ["parse-entities@4.0.2", "", { "dependencies": { "@types/unist": "^2.0.0", "character-entities-legacy": "^3.0.0", "character-reference-invalid": "^2.0.0", "decode-named-character-reference": "^1.0.0", "is-alphanumerical": "^2.0.0", "is-decimal": "^2.0.0", "is-hexadecimal": "^2.0.0" } }, "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw=="],
"parse-ms": ["parse-ms@4.0.0", "", {}, "sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw=="],
"path-exists": ["path-exists@4.0.0", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="],
"parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="],
"path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
"path-scurry": ["path-scurry@2.0.2", "", { "dependencies": { "lru-cache": "^11.0.0", "minipass": "^7.1.2" } }, "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg=="],
"path-to-regexp": ["path-to-regexp@8.4.0", "", {}, "sha512-PuseHIvAnz3bjrM2rGJtSgo1zjgxapTLZ7x2pjhzWwlp4SJQgK3f3iZIQwkpEnBaKz6seKBADpM4B4ySkuYypg=="],
"pend": ["pend@1.2.0", "", {}, "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg=="],
"picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
"picomatch": ["picomatch@4.0.3", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
"plist": ["plist@3.1.0", "", { "dependencies": { "@xmldom/xmldom": "^0.8.8", "base64-js": "^1.5.1", "xmlbuilder": "^15.1.1" } }, "sha512-uysumyrvkUX0rX/dEVqt8gC3sTBzd4zoWfLeS29nb53imdaXVvLINYXTI2GNqzaMuvacNx4uJQ8+b3zXR0pkgQ=="],
"postcss": ["postcss@8.5.8", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg=="],
"prebuild-install": ["prebuild-install@7.1.3", "", { "dependencies": { "detect-libc": "^2.0.0", "expand-template": "^2.0.3", "github-from-package": "0.0.0", "minimist": "^1.2.3", "mkdirp-classic": "^0.5.3", "napi-build-utils": "^2.0.0", "node-abi": "^3.3.0", "pump": "^3.0.0", "rc": "^1.2.7", "simple-get": "^4.0.0", "tar-fs": "^2.0.0", "tunnel-agent": "^0.6.0" }, "bin": { "prebuild-install": "bin.js" } }, "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug=="],
"pretty-ms": ["pretty-ms@9.3.0", "", { "dependencies": { "parse-ms": "^4.0.0" } }, "sha512-gjVS5hOP+M3wMm5nmNOucbIrqudzs9v/57bWRHQWLYklXqoXKrVfYW2W9+glfGsqtPgpiz5WwyEEB+ksXIx3gQ=="],
"prismjs": ["prismjs@1.30.0", "", {}, "sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw=="],
"progress": ["progress@2.0.3", "", {}, "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA=="],
"property-information": ["property-information@7.1.0", "", {}, "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ=="],
"proxy-addr": ["proxy-addr@2.0.7", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="],
"pump": ["pump@3.0.4", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="],
"qs": ["qs@6.15.0", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ=="],
"quick-lru": ["quick-lru@5.1.1", "", {}, "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA=="],
"random-path": ["random-path@0.1.2", "", { "dependencies": { "base32-encode": "^0.1.0 || ^1.0.0", "murmur-32": "^0.1.0 || ^0.2.0" } }, "sha512-4jY0yoEaQ5v9StCl5kZbNIQlg1QheIDBrdkDn53EynpPb9FgO6//p3X/tgMnrC45XN6QZCzU1Xz/+pSSsJBpRw=="],
"range-parser": ["range-parser@1.2.1", "", {}, "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="],
"raw-body": ["raw-body@3.0.2", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="],
"rc": ["rc@1.2.8", "", { "dependencies": { "deep-extend": "^0.6.0", "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" }, "bin": { "rc": "./cli.js" } }, "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw=="],
@@ -897,33 +927,47 @@
"remark-stringify": ["remark-stringify@11.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-to-markdown": "^2.0.0", "unified": "^11.0.0" } }, "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw=="],
"repeat-string": ["repeat-string@1.6.1", "", {}, "sha512-PV0dzCYDNfRi1jCDbJzpW7jNNDRuCOG/jI5ctQcGKt/clZD+YcPS3yIlWuTJMmESC8aevCFmWJy5wjAFgNqN6w=="],
"require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="],
"resolve-alpn": ["resolve-alpn@1.2.1", "", {}, "sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g=="],
"responselike": ["responselike@2.0.1", "", { "dependencies": { "lowercase-keys": "^2.0.0" } }, "sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw=="],
"restore-cursor": ["restore-cursor@5.1.0", "", { "dependencies": { "onetime": "^7.0.0", "signal-exit": "^4.1.0" } }, "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA=="],
"roarr": ["roarr@2.15.4", "", { "dependencies": { "boolean": "^3.0.1", "detect-node": "^2.0.4", "globalthis": "^1.0.1", "json-stringify-safe": "^5.0.1", "semver-compare": "^1.0.0", "sprintf-js": "^1.1.2" } }, "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A=="],
"rollup": ["rollup@4.60.0", "", { "dependencies": { "@types/estree": "1.0.8" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.60.0", "@rollup/rollup-android-arm64": "4.60.0", "@rollup/rollup-darwin-arm64": "4.60.0", "@rollup/rollup-darwin-x64": "4.60.0", "@rollup/rollup-freebsd-arm64": "4.60.0", "@rollup/rollup-freebsd-x64": "4.60.0", "@rollup/rollup-linux-arm-gnueabihf": "4.60.0", "@rollup/rollup-linux-arm-musleabihf": "4.60.0", "@rollup/rollup-linux-arm64-gnu": "4.60.0", "@rollup/rollup-linux-arm64-musl": "4.60.0", "@rollup/rollup-linux-loong64-gnu": "4.60.0", "@rollup/rollup-linux-loong64-musl": "4.60.0", "@rollup/rollup-linux-ppc64-gnu": "4.60.0", "@rollup/rollup-linux-ppc64-musl": "4.60.0", "@rollup/rollup-linux-riscv64-gnu": "4.60.0", "@rollup/rollup-linux-riscv64-musl": "4.60.0", "@rollup/rollup-linux-s390x-gnu": "4.60.0", "@rollup/rollup-linux-x64-gnu": "4.60.0", "@rollup/rollup-linux-x64-musl": "4.60.0", "@rollup/rollup-openbsd-x64": "4.60.0", "@rollup/rollup-openharmony-arm64": "4.60.0", "@rollup/rollup-win32-arm64-msvc": "4.60.0", "@rollup/rollup-win32-ia32-msvc": "4.60.0", "@rollup/rollup-win32-x64-gnu": "4.60.0", "@rollup/rollup-win32-x64-msvc": "4.60.0", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-yqjxruMGBQJ2gG4HtjZtAfXArHomazDHoFwFFmZZl0r7Pdo7qCIXKqKHZc8yeoMgzJJ+pO6pEEHa+V7uzWlrAQ=="],
"router": ["router@2.2.0", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="],
"safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
"safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],
"scheduler": ["scheduler@0.27.0", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
"semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
"semver-compare": ["semver-compare@1.0.0", "", {}, "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow=="],
"send": ["send@1.2.1", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="],
"serialize-error": ["serialize-error@7.0.1", "", { "dependencies": { "type-fest": "^0.13.1" } }, "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw=="],
"serve-static": ["serve-static@2.2.1", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="],
"setprototypeof": ["setprototypeof@1.2.0", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="],
"shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
"shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
"signal-exit": ["signal-exit@4.1.0", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
"side-channel": ["side-channel@1.1.0", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.3", "side-channel-list": "^1.0.0", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw=="],
"side-channel-list": ["side-channel-list@1.0.0", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.3" } }, "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA=="],
"side-channel-map": ["side-channel-map@1.0.1", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3" } }, "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA=="],
"side-channel-weakmap": ["side-channel-weakmap@1.0.2", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="],
"simple-concat": ["simple-concat@1.0.1", "", {}, "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q=="],
@@ -935,22 +979,12 @@
"sprintf-js": ["sprintf-js@1.1.3", "", {}, "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA=="],
"stdin-discarder": ["stdin-discarder@0.3.1", "", {}, "sha512-reExS1kSGoElkextOcPkel4NE99S0BWxjUHQeDFnR8S993JxpPX7KU4MNmO19NXhlJp+8dmdCbKQVNgLJh2teA=="],
"stream-buffers": ["stream-buffers@2.2.0", "", {}, "sha512-uyQK/mx5QjHun80FLJTfaWE7JtwfRMKBLkMne6udYOmvH0CawotVa7TfgYHzAnpphn4+TweIx1QKMnRIbipmUg=="],
"string-width": ["string-width@8.2.0", "", { "dependencies": { "get-east-asian-width": "^1.5.0", "strip-ansi": "^7.1.2" } }, "sha512-6hJPQ8N0V0P3SNmP6h2J99RLuzrWz2gvT7VnK5tKvrNqJoyS9W4/Fb8mo31UiPvy00z7DQXkP2hnKBVav76thw=="],
"statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
"string_decoder": ["string_decoder@1.3.0", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="],
"stringify-entities": ["stringify-entities@4.0.4", "", { "dependencies": { "character-entities-html4": "^2.0.0", "character-entities-legacy": "^3.0.0" } }, "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg=="],
"strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="],
"strip-eof": ["strip-eof@1.0.0", "", {}, "sha512-7FCwGGmx8mD5xQd3RPUvnSpUXHM3BWuzjtpD4TXsfcZ9EL4azvVVUscFYwD9nx8Kh+uCBC00XBtAykoMHwTh8Q=="],
"strip-final-newline": ["strip-final-newline@4.0.0", "", {}, "sha512-aulFJcD6YK8V1G7iRB5tigAP4TsHBZZrOV8pjV++zdUwmeV8uzbY7yn6h9MswN62adStNZFuCIx4haBnRuMDaw=="],
"strip-json-comments": ["strip-json-comments@2.0.1", "", {}, "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ=="],
"style-to-js": ["style-to-js@1.1.21", "", { "dependencies": { "style-to-object": "1.0.14" } }, "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ=="],
@@ -969,15 +1003,9 @@
"tar-stream": ["tar-stream@2.2.0", "", { "dependencies": { "bl": "^4.0.3", "end-of-stream": "^1.4.1", "fs-constants": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.1.1" } }, "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ=="],
"temp-dir": ["temp-dir@3.0.0", "", {}, "sha512-nHc6S/bwIilKHNRgK/3jlhDoIHcp45YgyiwcAk46Tr0LfEqGBVpmiAyuiuxeVE44m3mXnEeVhaipLOEWmH+Njw=="],
"tempy": ["tempy@3.2.0", "", { "dependencies": { "is-stream": "^3.0.0", "temp-dir": "^3.0.0", "type-fest": "^2.12.2", "unique-string": "^3.0.0" } }, "sha512-d79HhZya5Djd7am0q+W4RTsSU+D/aJzM+4Y4AGJGuGlgM2L6sx5ZvOYTmZjqPhrDrV6xJTtRSm1JCLj6V6LHLQ=="],
"tinyglobby": ["tinyglobby@0.2.15", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.3" } }, "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ=="],
"tn1150": ["tn1150@0.1.0", "", { "dependencies": { "unorm": "^1.4.1" } }, "sha512-DbplOfQFkqG5IHcDyyrs/lkvSr3mPUVsFf/RbDppOshs22yTPnSJWEe6FkYd1txAwU/zcnR905ar2fi4kwF29w=="],
"to-data-view": ["to-data-view@1.1.0", "", {}, "sha512-1eAdufMg6mwgmlojAx3QeMnzB/BTVp7Tbndi3U7ftcT2zCZadjxkkmLmd97zmaxWi+sgGcgWrokmpEoy0Dn0vQ=="],
"toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],
"trim-lines": ["trim-lines@3.0.1", "", {}, "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg=="],
@@ -985,7 +1013,9 @@
"tunnel-agent": ["tunnel-agent@0.6.0", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w=="],
"type-fest": ["type-fest@2.19.0", "", {}, "sha512-RAH822pAdBgcNMAfWnCBU3CFZcfZ/i1eZjwFU/dsLKumyuuP3niueg2UAukXYF0E2AAoc82ZSSf9J0WQBinzHA=="],
"type-fest": ["type-fest@0.13.1", "", {}, "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg=="],
"type-is": ["type-is@2.0.1", "", { "dependencies": { "content-type": "^1.0.5", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
@@ -993,12 +1023,8 @@
"undici-types": ["undici-types@7.18.2", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],
"unicorn-magic": ["unicorn-magic@0.3.0", "", {}, "sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA=="],
"unified": ["unified@11.0.5", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="],
"unique-string": ["unique-string@3.0.0", "", { "dependencies": { "crypto-random-string": "^4.0.0" } }, "sha512-VGXBUVwxKMBUznyffQweQABPRRW1vHZAbadFZud4pLFAqRGvv/96vafgjWFqzourzr8YonlQiPgH0YCJfawoGQ=="],
"unist-util-is": ["unist-util-is@6.0.1", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g=="],
"unist-util-position": ["unist-util-position@5.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA=="],
@@ -1011,7 +1037,7 @@
"universalify": ["universalify@0.1.2", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="],
"unorm": ["unorm@1.6.0", "", {}, "sha512-b2/KCUlYZUeA7JFUuRJZPUtr4gZvBh7tavtv4fvk4+KV9pfGiR6CQAQAWl49ZpR3ts2dk4FYkP7EIgDJoiOLDA=="],
"unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="],
"update-browserslist-db": ["update-browserslist-db@1.2.3", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="],
@@ -1019,6 +1045,8 @@
"util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
"vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="],
"vfile": ["vfile@6.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="],
"vfile-message": ["vfile-message@4.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw=="],
@@ -1035,15 +1063,17 @@
"xmlbuilder": ["xmlbuilder@15.1.1", "", {}, "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg=="],
"xtend": ["xtend@4.0.2", "", {}, "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="],
"yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
"yaml": ["yaml@2.8.3", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-AvbaCLOO2Otw/lW5bmh9d/WEdcDFdQp2Z2ZUH3pX9U2ihyUY0nvLv7J6TrWowklRGPYbB/IuIMfYgxaCPg5Bpg=="],
"yauzl": ["yauzl@2.10.0", "", { "dependencies": { "buffer-crc32": "~0.2.3", "fd-slicer": "~1.1.0" } }, "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g=="],
"yjs": ["yjs@13.6.30", "", { "dependencies": { "lib0": "^0.2.99" } }, "sha512-vv/9h42eCMC81ZHDFswuu/MKzkl/vyq1BhaNGfHyOonwlG4CJbQF4oiBBJPvfdeCt/PlVDWh7Nov9D34YY09uQ=="],
"yoctocolors": ["yoctocolors@2.1.2", "", {}, "sha512-CzhO+pFNo8ajLM2d2IW/R93ipy99LWjtwblvC1RsoSUMZgyLbYFr221TnSNT7GjGdYui6P459mw9JH/g/zW2ug=="],
"zod": ["zod@4.3.6", "", {}, "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg=="],
"zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
"zustand": ["zustand@4.5.7", "", { "dependencies": { "use-sync-external-store": "^1.2.2" }, "peerDependencies": { "@types/react": ">=16.8", "immer": ">=9.0.6", "react": ">=16.8" }, "optionalPeers": ["@types/react", "immer", "react"] }, "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw=="],
@@ -1063,54 +1093,20 @@
"@tailwindcss/oxide-wasm32-wasi/tslib": ["tslib@2.8.1", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
"appdmg/execa": ["execa@1.0.0", "", { "dependencies": { "cross-spawn": "^6.0.0", "get-stream": "^4.0.0", "is-stream": "^1.1.0", "npm-run-path": "^2.0.0", "p-finally": "^1.0.0", "signal-exit": "^3.0.0", "strip-eof": "^1.0.0" } }, "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA=="],
"cacheable-request/get-stream": ["get-stream@5.2.0", "", { "dependencies": { "pump": "^3.0.0" } }, "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA=="],
"clone-response/mimic-response": ["mimic-response@1.0.1", "", {}, "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ=="],
"crypto-random-string/type-fest": ["type-fest@1.4.0", "", {}, "sha512-yGSza74xk0UG8k+pLh5oeoYirvIiWo5t0/o3zHHAO2tRDiZcxWP7fywNlXhqb6/r6sWvwi+RsyQMWhVLe4BVuA=="],
"electron/@types/node": ["@types/node@24.12.0", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-GYDxsZi3ChgmckRT9HPU0WEhKLP08ev/Yfcq2AstjrDASOYCSXeyjDsHg4v5t4jOj7cyDX3vmprafKlWIG9MXQ=="],
"extract-zip/get-stream": ["get-stream@5.2.0", "", { "dependencies": { "pump": "^3.0.0" } }, "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA=="],
"global-agent/semver": ["semver@7.7.4", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],
"mdast-util-find-and-replace/escape-string-regexp": ["escape-string-regexp@5.0.0", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="],
"node-abi/semver": ["semver@7.7.4", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],
"npm-run-path/path-key": ["path-key@4.0.0", "", {}, "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ=="],
"node-pty/node-addon-api": ["node-addon-api@7.1.1", "", {}, "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ=="],
"parse-entities/@types/unist": ["@types/unist@2.0.11", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="],
"serialize-error/type-fest": ["type-fest@0.13.1", "", {}, "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg=="],
"tempy/is-stream": ["is-stream@3.0.0", "", {}, "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA=="],
"appdmg/execa/cross-spawn": ["cross-spawn@6.0.6", "", { "dependencies": { "nice-try": "^1.0.4", "path-key": "^2.0.1", "semver": "^5.5.0", "shebang-command": "^1.2.0", "which": "^1.2.9" } }, "sha512-VqCUuhcd1iB+dsv8gxPttb5iZh/D0iubSP21g36KXdEuf6I5JiioesUVjpCdHV9MZRUfVFlvwtIUyPfxo5trtw=="],
"appdmg/execa/get-stream": ["get-stream@4.1.0", "", { "dependencies": { "pump": "^3.0.0" } }, "sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w=="],
"appdmg/execa/is-stream": ["is-stream@1.1.0", "", {}, "sha512-uQPm8kcs47jx38atAcWTVxyltQYoPT68y9aWYdV6yWXSyW8mzSat0TL6CiWdZeCdF3KrAvpVtnHbTv4RN+rqdQ=="],
"appdmg/execa/npm-run-path": ["npm-run-path@2.0.2", "", { "dependencies": { "path-key": "^2.0.0" } }, "sha512-lJxZYlT4DW/bRUtFh1MQIWqmLwQfAxnqWG4HhEdjMlkrJYnJn0Jrr2u3mgxqaWsdiBc76TYkTG/mhrnYTuzfHw=="],
"appdmg/execa/signal-exit": ["signal-exit@3.0.7", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
"electron/@types/node/undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
"appdmg/execa/cross-spawn/path-key": ["path-key@2.0.1", "", {}, "sha512-fEHGKCSmUSDPv4uoj8AlD+joPlq3peND+HRYyxFz4KPw4z926S/b8rIuFs2FYJg3BwsxJf6A9/3eIdLaYC+9Dw=="],
"appdmg/execa/cross-spawn/semver": ["semver@5.7.2", "", { "bin": { "semver": "bin/semver" } }, "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g=="],
"appdmg/execa/cross-spawn/shebang-command": ["shebang-command@1.2.0", "", { "dependencies": { "shebang-regex": "^1.0.0" } }, "sha512-EV3L1+UQWGor21OmnvojK36mhg+TyIKDh3iFBKBohr5xeXIhNBcx8oWdgkTEEQ+BEFFYdLRuqMfd5L84N1V5Vg=="],
"appdmg/execa/cross-spawn/which": ["which@1.3.1", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "which": "./bin/which" } }, "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ=="],
"appdmg/execa/npm-run-path/path-key": ["path-key@2.0.1", "", {}, "sha512-fEHGKCSmUSDPv4uoj8AlD+joPlq3peND+HRYyxFz4KPw4z926S/b8rIuFs2FYJg3BwsxJf6A9/3eIdLaYC+9Dw=="],
"appdmg/execa/cross-spawn/shebang-command/shebang-regex": ["shebang-regex@1.0.0", "", {}, "sha512-wpoSFAxys6b2a2wHZ1XpDSgD7N9iVjg29Ph9uV/uaP9Ex/KXlkTZTeddxDPSYQpgvzKLGJke2UU0AzoGCjNIvQ=="],
}
}
+1 -1
View File
@@ -9,7 +9,7 @@ export default defineConfig({
build: {
outDir: 'dist-electron/main',
},
plugins: [externalizeDepsPlugin()],
plugins: [externalizeDepsPlugin({ exclude: ['@modelcontextprotocol/sdk'] })],
resolve: {
alias: {
'@main': resolve(__dirname, 'src/main'),
+7 -3
View File
@@ -41,14 +41,16 @@
"@lexical/markdown": "0.42.0",
"@lexical/react": "0.42.0",
"@lexical/rich-text": "0.42.0",
"@modelcontextprotocol/sdk": "^1.28.0",
"@tailwindcss/vite": "^4.2.2",
"@types/node": "^25.5.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "5.1.0",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"@xyflow/react": "^12.10.1",
"bun-types": "^1.3.11",
"create-dmg": "^8.1.0",
"electron": "^41.0.3",
"electron-vite": "^5.0.0",
"highlight.js": "^11.11.1",
@@ -62,9 +64,11 @@
"tailwindcss": "^4.2.2",
"typescript": "^5.9.3",
"typescript-language-server": "^5.1.3",
"vite": "7.1.10"
"vite": "7.1.10",
"yaml": "^2.8.3"
},
"dependencies": {
"keytar": "^7.9.0"
"keytar": "^7.9.0",
"node-pty": "^1.1.0"
}
}
+11 -17
View File
@@ -5,7 +5,6 @@ import {
cp,
mkdir,
readFile,
rename,
symlink,
writeFile,
} from 'node:fs/promises';
@@ -104,28 +103,23 @@ async function createMacInstaller(): Promise<void> {
}
const appBundlePath = join(packagedAppDirectory, appBundleName);
const createDmg = join(repositoryRoot, 'node_modules', '.bin', 'create-dmg');
// create-dmg outputs to the destination directory with a generated filename.
// We use --no-version-in-filename so the output is "<AppName>.dmg", then
// rename it to the expected installer asset name.
// Use macOS's native disk image tooling so packaging does not depend on
// create-dmg's native node-gyp install path on CI runners.
await runCommand(
createDmg,
'hdiutil',
[
'--overwrite',
'--no-version-in-filename',
'--no-code-sign',
'create',
'-volname',
productName,
'-srcfolder',
appBundlePath,
releaseRootDirectory,
'-ov',
'-format',
'UDZO',
installerOutputPath,
],
repositoryRoot,
);
// Rename from the generated name ("Aryx.dmg") to the platform-specific asset name
const generatedDmgPath = join(releaseRootDirectory, `${productName}.dmg`);
if (generatedDmgPath !== installerOutputPath) {
await rename(generatedDmgPath, installerOutputPath);
}
}
// --- Linux: .deb package ---
@@ -183,6 +183,7 @@ public sealed class RunTurnCommandDto : SidecarCommandEnvelope
public string WorkspaceKind { get; init; } = "project";
public string Mode { get; init; } = "interactive";
public string MessageMode { get; init; } = "enqueue";
public string? ProjectInstructions { get; init; }
public PatternDefinitionDto Pattern { get; init; } = new();
public IReadOnlyList<ChatMessageDto> Messages { get; init; } = [];
public RunTurnToolingConfigDto? Tooling { get; init; }
@@ -223,6 +224,8 @@ public sealed class DisconnectSessionCommandDto : SidecarCommandEnvelope
public string SessionId { get; init; } = string.Empty;
}
public sealed class GetQuotaCommandDto : SidecarCommandEnvelope;
public sealed class RunTurnToolingConfigDto
{
public IReadOnlyList<RunTurnMcpServerConfigDto> McpServers { get; init; } = [];
@@ -385,6 +388,37 @@ public sealed class HookLifecycleEventDto : SidecarEventDto
public string? Error { get; init; }
}
public sealed class QuotaSnapshotDto
{
public double EntitlementRequests { get; init; }
public double UsedRequests { get; init; }
public double RemainingPercentage { get; init; }
public double Overage { get; init; }
public bool OverageAllowedWithExhaustedQuota { get; init; }
public string? ResetDate { get; init; }
}
public sealed class AccountQuotaResultEventDto : SidecarEventDto
{
public Dictionary<string, QuotaSnapshotDto> QuotaSnapshots { get; init; } = new(StringComparer.Ordinal);
}
public sealed class AssistantUsageEventDto : SidecarEventDto
{
public string SessionId { get; init; } = string.Empty;
public string? AgentId { get; init; }
public string? AgentName { get; init; }
public string Model { get; init; } = string.Empty;
public double? InputTokens { get; init; }
public double? OutputTokens { get; init; }
public double? CacheReadTokens { get; init; }
public double? CacheWriteTokens { get; init; }
public double? Cost { get; init; }
public double? Duration { get; init; }
public double? TotalNanoAiu { get; init; }
public Dictionary<string, QuotaSnapshotDto>? QuotaSnapshots { get; init; }
}
public sealed class SessionUsageEventDto : SidecarEventDto
{
public string SessionId { get; init; } = string.Empty;
@@ -9,9 +9,11 @@ internal static class AgentInstructionComposer
PatternAgentDefinitionDto agent,
int agentIndex,
string workspaceKind = "project",
string interactionMode = "interactive")
string interactionMode = "interactive",
string? projectInstructions = null)
{
string baseInstructions = agent.Instructions.Trim();
string repositoryInstructions = projectInstructions?.Trim() ?? string.Empty;
string workspaceGuidance = string.Equals(workspaceKind, "scratchpad", StringComparison.OrdinalIgnoreCase)
? """
You are operating in scratchpad mode.
@@ -46,12 +48,12 @@ internal static class AgentInstructionComposer
Focus on refining the answer already in progress.
""";
return JoinInstructionBlocks(baseInstructions, workspaceGuidance, planModeGuidance, groupChatGuidance);
return JoinInstructionBlocks(baseInstructions, repositoryInstructions, workspaceGuidance, planModeGuidance, groupChatGuidance);
}
if (!string.Equals(pattern.Mode, "handoff", StringComparison.OrdinalIgnoreCase))
{
return JoinInstructionBlocks(baseInstructions, workspaceGuidance, planModeGuidance);
return JoinInstructionBlocks(baseInstructions, repositoryInstructions, workspaceGuidance, planModeGuidance);
}
string runtimeGuidance = agentIndex == 0
@@ -69,7 +71,7 @@ internal static class AgentInstructionComposer
Do not push the actual work back to triage unless you are blocked or the request is clearly outside your specialty.
""";
return JoinInstructionBlocks(baseInstructions, workspaceGuidance, planModeGuidance, runtimeGuidance);
return JoinInstructionBlocks(baseInstructions, repositoryInstructions, workspaceGuidance, planModeGuidance, runtimeGuidance);
}
private static string JoinInstructionBlocks(params string[] blocks)
@@ -103,7 +103,8 @@ internal sealed class CopilotAgentBundle : IAsyncDisposable
definition,
agentIndex,
command.WorkspaceKind,
command.Mode),
command.Mode,
command.ProjectInstructions),
},
WorkingDirectory = command.ProjectPath,
OnPermissionRequest = onPermissionRequest,
@@ -57,9 +57,10 @@ internal sealed class CopilotApprovalCoordinator
{
string? toolName = ResolveApprovalToolName(request, toolNamesByCallId);
string? autoApprovedToolName = ResolveAutoApprovedToolName(request);
string? mcpServerApprovalKey = ResolveMcpServerApprovalKey(request);
string? approvalCacheKey = ResolveApprovalCacheKey(toolName, autoApprovedToolName);
if (IsToolApprovedForRequest(command.RequestId, approvalCacheKey)
|| !RequiresToolCallApproval(command.Pattern.ApprovalPolicy, agent.Id, toolName, autoApprovedToolName))
|| !RequiresToolCallApproval(command.Pattern.ApprovalPolicy, agent.Id, toolName, autoApprovedToolName, mcpServerApprovalKey))
{
return CreateApprovalResult(PermissionRequestResultKind.Approved);
}
@@ -227,7 +228,8 @@ internal sealed class CopilotApprovalCoordinator
ApprovalPolicyDto? approvalPolicy,
string agentId,
string? toolName,
string? autoApprovedToolName = null)
string? autoApprovedToolName = null,
string? mcpServerApprovalKey = null)
{
if (approvalPolicy?.Rules is null || approvalPolicy.Rules.Count == 0)
{
@@ -245,7 +247,8 @@ internal sealed class CopilotApprovalCoordinator
return true;
}
return !MatchesAutoApprovedTool(autoApprovedToolNames, toolName, autoApprovedToolName);
return !MatchesAutoApprovedTool(autoApprovedToolNames, toolName, autoApprovedToolName)
&& !MatchesAutoApprovedToolName(autoApprovedToolNames, mcpServerApprovalKey);
}
internal static bool TryGetApprovalToolName(
@@ -327,6 +330,19 @@ internal sealed class CopilotApprovalCoordinator
return GetFallbackToolName(request);
}
private const string McpServerApprovalPrefix = "mcp_server:";
private static string? ResolveMcpServerApprovalKey(PermissionRequest request)
{
if (request is not PermissionRequestMcp mcp)
{
return null;
}
string? serverName = NormalizeOptionalString(mcp.ServerName);
return serverName is not null ? $"{McpServerApprovalPrefix}{serverName}" : null;
}
private static string? ResolveApprovalCacheKey(
string? toolName,
string? autoApprovedToolName)
@@ -1,10 +1,19 @@
using Aryx.AgentHost.Contracts;
using GitHub.Copilot.SDK;
using GitHub.Copilot.SDK.Rpc;
namespace Aryx.AgentHost.Services;
internal sealed class CopilotSessionManager : ICopilotSessionManager
{
public async Task<IReadOnlyDictionary<string, QuotaSnapshotDto>> GetQuotaAsync(
CancellationToken cancellationToken)
{
await using CopilotClient client = await CreateStartedClientAsync(cancellationToken).ConfigureAwait(false);
AccountGetQuotaResult result = await client.Rpc.Account.GetQuotaAsync(cancellationToken).ConfigureAwait(false);
return QuotaSnapshotMapper.Map(result.QuotaSnapshots);
}
public async Task<IReadOnlyList<CopilotSessionInfoDto>> ListSessionsAsync(
CopilotSessionListFilterDto? filter,
CancellationToken cancellationToken)
@@ -127,6 +127,10 @@ internal sealed class CopilotTurnExecutionState
_pendingEvents.Enqueue(CreateHookLifecycleEvent(agent, "end", hookEnd.Data));
}
break;
case AssistantUsageEvent assistantUsage:
ActiveAgent = agent;
_pendingEvents.Enqueue(CreateAssistantUsageEvent(agent, assistantUsage.Data));
break;
case SessionUsageInfoEvent usageInfo:
ActiveAgent = agent;
_pendingEvents.Enqueue(CreateUsageEvent(agent, usageInfo.Data));
@@ -410,6 +414,29 @@ internal sealed class CopilotTurnExecutionState
};
}
private AssistantUsageEventDto CreateAssistantUsageEvent(
AgentIdentity agent,
AssistantUsageData? data)
{
return new AssistantUsageEventDto
{
Type = "assistant-usage",
RequestId = _command.RequestId,
SessionId = _command.SessionId,
AgentId = agent.AgentId,
AgentName = agent.AgentName,
Model = data?.Model ?? string.Empty,
InputTokens = data?.InputTokens,
OutputTokens = data?.OutputTokens,
CacheReadTokens = data?.CacheReadTokens,
CacheWriteTokens = data?.CacheWriteTokens,
Cost = data?.Cost,
Duration = data?.Duration,
TotalNanoAiu = data?.CopilotUsage?.TotalNanoAiu,
QuotaSnapshots = QuotaSnapshotMapper.MapOrNull(data?.QuotaSnapshots),
};
}
private SessionUsageEventDto CreateUsageEvent(AgentIdentity agent, SessionUsageInfoData? data)
{
return new SessionUsageEventDto
@@ -12,5 +12,8 @@ public interface ICopilotSessionManager
string? aryxSessionId,
string? copilotSessionId,
CancellationToken cancellationToken);
Task<IReadOnlyDictionary<string, QuotaSnapshotDto>> GetQuotaAsync(
CancellationToken cancellationToken);
}
@@ -0,0 +1,105 @@
using System.Text.Json;
using Aryx.AgentHost.Contracts;
using GitHub.Copilot.SDK.Rpc;
namespace Aryx.AgentHost.Services;
internal static class QuotaSnapshotMapper
{
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
{
PropertyNameCaseInsensitive = true,
};
public static Dictionary<string, QuotaSnapshotDto> Map(
IReadOnlyDictionary<string, AccountGetQuotaResultQuotaSnapshotsValue>? snapshots)
{
Dictionary<string, QuotaSnapshotDto> mapped = new(StringComparer.Ordinal);
if (snapshots is null)
{
return mapped;
}
foreach ((string key, AccountGetQuotaResultQuotaSnapshotsValue snapshot) in snapshots)
{
if (string.IsNullOrWhiteSpace(key))
{
continue;
}
mapped[key.Trim()] = Map(snapshot);
}
return mapped;
}
public static Dictionary<string, QuotaSnapshotDto>? MapOrNull(
IReadOnlyDictionary<string, object>? snapshots)
{
if (snapshots is not { Count: > 0 })
{
return null;
}
Dictionary<string, QuotaSnapshotDto> mapped = new(StringComparer.Ordinal);
foreach ((string key, object snapshot) in snapshots)
{
if (string.IsNullOrWhiteSpace(key))
{
continue;
}
QuotaSnapshotDto? mappedSnapshot = TryMap(snapshot);
if (mappedSnapshot is null)
{
continue;
}
mapped[key.Trim()] = mappedSnapshot;
}
return mapped.Count == 0 ? null : mapped;
}
public static QuotaSnapshotDto Map(AccountGetQuotaResultQuotaSnapshotsValue snapshot)
{
ArgumentNullException.ThrowIfNull(snapshot);
return new QuotaSnapshotDto
{
EntitlementRequests = snapshot.EntitlementRequests,
UsedRequests = snapshot.UsedRequests,
RemainingPercentage = snapshot.RemainingPercentage,
Overage = snapshot.Overage,
OverageAllowedWithExhaustedQuota = snapshot.OverageAllowedWithExhaustedQuota,
ResetDate = snapshot.ResetDate,
};
}
private static QuotaSnapshotDto? TryMap(object? snapshot)
{
if (snapshot is null)
{
return null;
}
if (snapshot is AccountGetQuotaResultQuotaSnapshotsValue typedSnapshot)
{
return Map(typedSnapshot);
}
JsonElement element = snapshot is JsonElement jsonElement
? jsonElement
: JsonSerializer.SerializeToElement(snapshot, JsonOptions);
if (element.ValueKind != JsonValueKind.Object)
{
return null;
}
AccountGetQuotaResultQuotaSnapshotsValue? deserialized =
element.Deserialize<AccountGetQuotaResultQuotaSnapshotsValue>(JsonOptions);
return deserialized is null ? null : Map(deserialized);
}
}
@@ -18,6 +18,7 @@ public sealed class SidecarProtocolHost
private const string ListSessionsCommandType = "list-sessions";
private const string DeleteSessionCommandType = "delete-session";
private const string DisconnectSessionCommandType = "disconnect-session";
private const string GetQuotaCommandType = "get-quota";
private const string AskUserToolName = "ask_user";
private static readonly HashSet<string> ExcludedRuntimeToolNames = new(StringComparer.OrdinalIgnoreCase)
{
@@ -82,6 +83,7 @@ public sealed class SidecarProtocolHost
[ListSessionsCommandType] = HandleListSessionsAsync,
[DeleteSessionCommandType] = HandleDeleteSessionAsync,
[DisconnectSessionCommandType] = HandleDisconnectSessionAsync,
[GetQuotaCommandType] = HandleGetQuotaAsync,
};
}
@@ -313,6 +315,23 @@ public sealed class SidecarProtocolHost
}, context.CancellationToken).ConfigureAwait(false);
}
private async Task HandleGetQuotaAsync(CommandContext context)
{
_ = DeserializeCommand<GetQuotaCommandDto>(context);
IReadOnlyDictionary<string, QuotaSnapshotDto> quotaSnapshots =
await _sessionManager.GetQuotaAsync(context.CancellationToken).ConfigureAwait(false);
await WriteAsync(context.Output, new AccountQuotaResultEventDto
{
Type = "quota-result",
RequestId = context.Envelope.RequestId,
QuotaSnapshots = quotaSnapshots.ToDictionary(
snapshot => snapshot.Key,
snapshot => snapshot.Value,
StringComparer.Ordinal),
}, context.CancellationToken).ConfigureAwait(false);
}
private TCommand DeserializeCommand<TCommand>(CommandContext context)
where TCommand : SidecarCommandEnvelope
{
@@ -151,6 +151,39 @@ public sealed class AgentInstructionComposerTests
Assert.Contains("Do not continue into implementation", instructions, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void Compose_InsertsProjectInstructionsBetweenBaseAndRuntimeGuidance()
{
PatternDefinitionDto pattern = new()
{
Id = "pattern-single",
Name = "Single",
Mode = "single",
Availability = "available",
};
PatternAgentDefinitionDto agent = CreateAgent(
id: "agent-primary",
name: "Primary Agent",
instructions: "You are a helpful assistant.");
string instructions = AgentInstructionComposer.Compose(
pattern,
agent,
agentIndex: 0,
workspaceKind: "scratchpad",
projectInstructions: "Follow the repository guide.");
Assert.Contains("You are a helpful assistant.", instructions, StringComparison.Ordinal);
Assert.Contains("Follow the repository guide.", instructions, StringComparison.Ordinal);
Assert.Contains("scratchpad mode", instructions, StringComparison.OrdinalIgnoreCase);
Assert.True(
instructions.IndexOf("You are a helpful assistant.", StringComparison.Ordinal)
< instructions.IndexOf("Follow the repository guide.", StringComparison.Ordinal));
Assert.True(
instructions.IndexOf("Follow the repository guide.", StringComparison.Ordinal)
< instructions.IndexOf("scratchpad mode", StringComparison.OrdinalIgnoreCase));
}
private static PatternAgentDefinitionDto CreateAgent(string id, string name, string instructions)
{
return new PatternAgentDefinitionDto
@@ -10,13 +10,14 @@ public sealed class AryxCopilotAgentMessageOptionsTests
[Fact]
public async Task ProcessMessageAttachmentsAsync_MapsProtocolAttachmentsAndMessageMode()
{
string attachmentPath = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "aryx-tests", "assets", "diagram.png"));
ChatMessage message = new(ChatRole.User, "Please inspect these images.");
message.Contents.Add(new AIContent
{
RawRepresentation = new ChatMessageAttachmentDto
{
Type = "file",
Path = @"C:\workspace\project\assets\diagram.png",
Path = attachmentPath,
DisplayName = "diagram.png",
},
});
@@ -47,7 +48,7 @@ public sealed class AryxCopilotAgentMessageOptionsTests
first =>
{
UserMessageDataAttachmentsItemFile file = Assert.IsType<UserMessageDataAttachmentsItemFile>(first);
Assert.Equal(@"C:\workspace\project\assets\diagram.png", file.Path);
Assert.Equal(attachmentPath, file.Path);
Assert.Equal("diagram.png", file.DisplayName);
},
second =>
@@ -250,6 +250,43 @@ public sealed class CopilotAgentBundleTests
Assert.NotNull(sessionConfig.Hooks);
}
[Fact]
public void CreateSessionConfig_PassesProjectInstructionsIntoTheSystemMessage()
{
RunTurnCommandDto command = new()
{
SessionId = "session-1",
ProjectPath = @"C:\workspace\project",
WorkspaceKind = "project",
Mode = "interactive",
ProjectInstructions = "Follow repository guidance.",
Pattern = new PatternDefinitionDto
{
Id = "pattern-1",
Name = "Pattern",
Mode = "single",
Availability = "available",
Agents =
[
new PatternAgentDefinitionDto
{
Id = "agent-1",
Name = "Primary",
Model = "gpt-5.4",
Instructions = "Help.",
},
],
},
};
SessionConfig sessionConfig = CopilotAgentBundle.CreateSessionConfig(
command,
command.Pattern.Agents[0],
agentIndex: 0);
Assert.Equal("Help.\n\nFollow repository guidance.", sessionConfig.SystemMessage?.Content);
}
[Fact]
public async Task CopilotSessionHooks_Create_UsesApprovalPolicyForPreToolUse()
{
@@ -251,6 +251,69 @@ public sealed class CopilotTurnExecutionStateTests
Assert.Empty(state.DrainPendingEvents());
}
[Fact]
public void ObserveSessionEvent_AssistantUsage_QueuesAssistantUsageEvent()
{
RunTurnCommandDto command = CreateCommand();
CopilotTurnExecutionState state = new(command);
state.ObserveSessionEvent(
command.Pattern.Agents[0],
SessionEvent.FromJson(
"""
{
"type": "assistant.usage",
"data": {
"model": "gpt-5.4",
"inputTokens": 1200,
"outputTokens": 300,
"cacheReadTokens": 50,
"cacheWriteTokens": 10,
"cost": 0.42,
"duration": 8200,
"quotaSnapshots": {
"premium_interactions": {
"entitlementRequests": 50,
"usedRequests": 12,
"remainingPercentage": 76,
"overage": 0,
"overageAllowedWithExhaustedQuota": true,
"resetDate": "2026-04-01T00:00:00Z"
}
},
"copilotUsage": {
"tokenDetails": [
{
"batchSize": 1,
"costPerBatch": 1,
"tokenCount": 1500,
"tokenType": "input"
}
],
"totalNanoAiu": 1200000000
}
},
"id": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
"timestamp": "2026-03-27T00:00:00Z"
}
"""));
AssistantUsageEventDto evt = Assert.Single(state.DrainPendingEvents().OfType<AssistantUsageEventDto>());
Assert.Equal("session-1", evt.SessionId);
Assert.Equal("agent-1", evt.AgentId);
Assert.Equal("Primary", evt.AgentName);
Assert.Equal("gpt-5.4", evt.Model);
Assert.Equal(1200, evt.InputTokens);
Assert.Equal(300, evt.OutputTokens);
Assert.Equal(0.42, evt.Cost);
Assert.Equal(8200, evt.Duration);
Assert.Equal(1200000000, evt.TotalNanoAiu);
QuotaSnapshotDto snapshot = Assert.Single(evt.QuotaSnapshots!.Values);
Assert.Equal(50, snapshot.EntitlementRequests);
Assert.Equal(12, snapshot.UsedRequests);
Assert.Equal(76, snapshot.RemainingPercentage);
}
[Fact]
public void ObserveSessionEvent_SessionCompactionComplete_QueuesCompactionEvent()
{
@@ -843,6 +843,36 @@ public sealed class CopilotWorkflowRunnerTests
Assert.True(CopilotApprovalCoordinator.RequiresToolCallApproval(policy, "agent-1", "git.status"));
}
[Fact]
public void RequiresToolCallApproval_HonorsMcpServerLevelApprovalKey()
{
ApprovalPolicyDto policy = new()
{
Rules =
[
new ApprovalCheckpointRuleDto
{
Kind = "tool-call",
},
],
AutoApprovedToolNames = ["mcp_server:Git MCP"],
};
// Server-level key approves any tool from that server
Assert.False(CopilotApprovalCoordinator.RequiresToolCallApproval(
policy, "agent-1", "git.status", null, "mcp_server:Git MCP"));
Assert.False(CopilotApprovalCoordinator.RequiresToolCallApproval(
policy, "agent-1", "git.diff", null, "mcp_server:Git MCP"));
// Different server still requires approval
Assert.True(CopilotApprovalCoordinator.RequiresToolCallApproval(
policy, "agent-1", "fs.read", null, "mcp_server:Filesystem"));
// Non-MCP tools unaffected
Assert.True(CopilotApprovalCoordinator.RequiresToolCallApproval(
policy, "agent-1", "unknown_tool"));
}
[Fact]
public void TryGetApprovalToolName_ResolvesDirectNamesAndRuntimeFallbacks()
{
@@ -69,10 +69,11 @@ public sealed class HookCommandRunnerTests
HookCommandRunner runner = new();
using TestDirectory project = new();
string hooksDirectory = Directory.CreateDirectory(Path.Combine(project.Path, "scripts")).FullName;
await File.WriteAllTextAsync(Path.Combine(hooksDirectory, "cwd-marker.txt"), "marker");
HookCommandDefinition hook = CreatePlatformHook(
OperatingSystem.IsWindows()
? "Write-Output ((Get-Location).Path + '|' + $env:HOOK_TEST_ENV)"
: "printf '%s|%s' \"$(pwd)\" \"$HOOK_TEST_ENV\"",
? "$null = [Console]::In.ReadToEnd(); if (Test-Path -LiteralPath './cwd-marker.txt') { $status = 'present' } else { $status = 'missing' }; Write-Output ($status + '|' + $env:HOOK_TEST_ENV)"
: "cat >/dev/null; if [ -f ./cwd-marker.txt ]; then status=present; else status=missing; fi; printf '%s|%s' \"$status\" \"$HOOK_TEST_ENV\"",
cwd: "scripts",
env: new Dictionary<string, string>
{
@@ -81,7 +82,7 @@ public sealed class HookCommandRunnerTests
string? output = await runner.RunAsync(hook, "{}", project.Path, CancellationToken.None);
Assert.Equal($"{hooksDirectory}|configured", output?.Trim());
Assert.Equal("present|configured", output?.Trim());
}
private static HookCommandDefinition CreatePlatformHook(
@@ -850,6 +850,44 @@ public sealed class SidecarProtocolHostTests
Assert.Equal("session-1", sessionManager.DeletedAryxSessionId);
}
[Fact]
public async Task GetQuotaCommand_ReturnsQuotaResultEvent()
{
SidecarProtocolHost host = new(
new PatternValidator(),
sessionManager: new FakeSessionManager
{
QuotaSnapshots = new Dictionary<string, QuotaSnapshotDto>(StringComparer.Ordinal)
{
["premium_interactions"] = new()
{
EntitlementRequests = 50,
UsedRequests = 12,
RemainingPercentage = 76,
Overage = 0,
OverageAllowedWithExhaustedQuota = true,
ResetDate = "2026-04-01T00:00:00Z",
},
},
});
IReadOnlyList<JsonElement> events = await RunHostAsync(
new GetQuotaCommandDto
{
Type = "get-quota",
RequestId = "quota-1",
},
host);
JsonElement quotaEvent = AssertSingleEvent(events, "quota-result", "quota-1");
JsonElement snapshot = quotaEvent.GetProperty("quotaSnapshots").GetProperty("premium_interactions");
Assert.Equal(50, snapshot.GetProperty("entitlementRequests").GetDouble());
Assert.Equal(12, snapshot.GetProperty("usedRequests").GetDouble());
Assert.Equal(76, snapshot.GetProperty("remainingPercentage").GetDouble());
Assert.True(snapshot.GetProperty("overageAllowedWithExhaustedQuota").GetBoolean());
Assert.Equal("2026-04-01T00:00:00Z", snapshot.GetProperty("resetDate").GetString());
}
[Fact]
public async Task DisconnectSessionCommand_CancelsActiveTurnsForSession()
{
@@ -1115,6 +1153,9 @@ public sealed class SidecarProtocolHostTests
public IReadOnlyList<CopilotSessionInfoDto> DeletedSessions { get; init; } = [];
public IReadOnlyDictionary<string, QuotaSnapshotDto> QuotaSnapshots { get; init; }
= new Dictionary<string, QuotaSnapshotDto>(StringComparer.Ordinal);
public string? DeletedAryxSessionId { get; private set; }
public string? DeletedCopilotSessionId { get; private set; }
@@ -1135,5 +1176,11 @@ public sealed class SidecarProtocolHostTests
DeletedCopilotSessionId = copilotSessionId;
return Task.FromResult(DeletedSessions);
}
public Task<IReadOnlyDictionary<string, QuotaSnapshotDto>> GetQuotaAsync(
CancellationToken cancellationToken)
{
return Task.FromResult(QuotaSnapshots);
}
}
}
+604 -24
View File
@@ -9,6 +9,7 @@ import type {
ApprovalRequestedEvent,
ExitPlanModeRequestedEvent,
McpOauthRequiredEvent,
RunTurnCustomAgentConfig,
RunTurnToolingConfig,
SidecarCapabilities,
TurnDeltaEvent,
@@ -30,10 +31,20 @@ import {
} from '@shared/domain/pattern';
import {
applyDiscoveredMcpServerStatus,
listAcceptedDiscoveredMcpServers,
normalizeDiscoveredToolingState,
type DiscoveredMcpServer,
type DiscoveredToolingState,
type DiscoveredToolingStatus,
} from '@shared/domain/discoveredTooling';
import {
listEnabledProjectAgentProfiles,
normalizeProjectCustomizationState,
resolveProjectInstructionsContent,
setProjectAgentProfileEnabled,
type ProjectAgentProfile,
type ProjectCustomizationState,
} from '@shared/domain/projectCustomization';
import {
approvalPolicyRequiresCheckpoint,
dequeuePendingApprovalState,
@@ -58,6 +69,7 @@ import {
type SessionQueryResult,
} from '@shared/domain/sessionLibrary';
import type { SessionEventRecord } from '@shared/domain/event';
import type { TerminalExitInfo, TerminalSnapshot } from '@shared/domain/terminal';
import {
applySessionApprovalSettings,
applySessionModelConfig,
@@ -82,6 +94,7 @@ import {
import {
createSessionToolingSelection,
listApprovalToolNames,
normalizeTerminalHeight,
normalizeTheme,
resolveProjectToolingSettings,
resolveWorkspaceToolingSettings,
@@ -104,6 +117,7 @@ import { WorkspaceRepository } from '@main/persistence/workspaceRepository';
import { getScratchpadSessionPath } from '@main/persistence/appPaths';
import { SecretStore } from '@main/secrets/secretStore';
import { ConfigScannerRegistry } from '@main/services/configScanner';
import { ProjectCustomizationScanner } from '@main/services/customizationScanner';
import {
SIDECAR_STOPPED_BEFORE_COMPLETION_MESSAGE,
SidecarClient,
@@ -116,12 +130,16 @@ import {
} from '@main/sessionToolingConfig';
import { getStoredToken } from '@main/services/mcpTokenStore';
import { performMcpOAuthFlow, requiresOAuth } from '@main/services/mcpOAuthService';
import { probeServers, type McpProbeResult } from '@main/services/mcpToolProber';
import { PtyManager } from '@main/services/ptyManager';
const { dialog, shell } = electron;
type AppServiceEvents = {
'workspace-updated': [WorkspaceState];
'session-event': [SessionEventRecord];
'terminal-data': [string];
'terminal-exit': [TerminalExitInfo];
};
type PendingApprovalHandle = {
@@ -156,18 +174,38 @@ function isSidecarStoppedBeforeCompletionError(error: unknown): error is Error {
return error instanceof Error && error.message === SIDECAR_STOPPED_BEFORE_COMPLETION_MESSAGE;
}
const INTERRUPTED_RUN_ERROR =
'This session was interrupted because Aryx restarted while a run was in progress.';
const INTERRUPTED_APPROVAL_ERROR =
'Pending approval was interrupted because Aryx restarted before a decision was recorded.';
export class AryxAppService extends EventEmitter<AppServiceEvents> {
private readonly workspaceRepository = new WorkspaceRepository();
private readonly sidecar = new SidecarClient();
private readonly secretStore = new SecretStore();
private readonly gitService = new GitService();
private readonly configScanner = new ConfigScannerRegistry();
private readonly customizationScanner = new ProjectCustomizationScanner();
private readonly probeMcpServers = probeServers;
private readonly ptyManager = new PtyManager();
private readonly pendingApprovalHandles = new Map<string, PendingApprovalHandle>();
private readonly pendingUserInputHandles = new Map<string, PendingUserInputHandle>();
private workspace?: WorkspaceState;
private sidecarCapabilities?: SidecarCapabilities;
private sidecarCapabilitiesPromise?: Promise<SidecarCapabilities>;
private didScheduleInitialProjectGitRefresh = false;
private mcpProbeUpdateQueue = Promise.resolve();
constructor() {
super();
this.ptyManager.on('data', (data) => {
this.emit('terminal-data', data);
});
this.ptyManager.on('exit', (info) => {
this.emit('terminal-exit', info);
});
}
async describeSidecarCapabilities(): Promise<SidecarCapabilities> {
return this.loadSidecarCapabilities();
@@ -188,14 +226,18 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
const didSyncProjectTooling = selectedProject
? await this.syncProjectDiscoveredTooling(this.workspace, selectedProject)
: false;
const didSyncProjectCustomization = selectedProject
? await this.syncProjectCustomization(selectedProject)
: false;
const didPruneSelections = this.pruneUnavailableSessionToolingSelections(this.workspace);
const didPruneApprovalTools = await this.pruneUnavailableApprovalTools(this.workspace);
if (
didSyncUserTooling
|| didSyncProjectTooling
|| didSyncProjectCustomization
|| didPruneSelections
|| didPruneApprovalTools
|| this.failInterruptedPendingApprovals(this.workspace)
|| this.cleanupInterruptedSessions(this.workspace)
) {
await this.workspaceRepository.save(this.workspace);
}
@@ -206,12 +248,17 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
void this.refreshProjectGitContext().catch((error) => {
console.error('[aryx git]', error);
});
void this.probeAllAcceptedMcpServers(this.workspace).catch((error) => {
console.error('[aryx mcp-probe]', error);
});
}
return this.workspace;
}
async dispose(): Promise<void> {
this.ptyManager.dispose();
await this.sidecar.dispose();
void this.secretStore;
}
@@ -257,6 +304,7 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
if (existing) {
workspace.selectedProjectId = existing.id;
const didSyncProjectTooling = await this.syncProjectDiscoveredTooling(workspace, existing);
await this.syncProjectCustomization(existing);
if (didSyncProjectTooling) {
this.pruneUnavailableSessionToolingSelections(workspace);
await this.pruneUnavailableApprovalTools(workspace);
@@ -275,6 +323,7 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
workspace.projects.push(project);
workspace.selectedProjectId = project.id;
await this.syncProjectDiscoveredTooling(workspace, project);
await this.syncProjectCustomization(project);
return this.persistAndBroadcast(workspace);
}
@@ -314,7 +363,15 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
this.pruneUnavailableSessionToolingSelections(workspace);
await this.pruneUnavailableApprovalTools(workspace);
return this.persistAndBroadcast(workspace);
const result = await this.persistAndBroadcast(workspace);
if (resolution === 'accept') {
void this.probeDiscoveredMcpServers(workspace, workspace.settings.discoveredUserTooling, serverIds).catch((error) => {
console.error('[aryx mcp-probe]', error);
});
}
return result;
}
async rescanProjectConfigs(projectId: string): Promise<WorkspaceState> {
@@ -323,6 +380,34 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
await this.syncProjectDiscoveredTooling(workspace, project);
this.pruneUnavailableSessionToolingSelections(workspace);
await this.pruneUnavailableApprovalTools(workspace);
const result = await this.persistAndBroadcast(workspace);
void this.probeDiscoveredMcpServersFromState(workspace, project.discoveredTooling).catch((error) => {
console.error('[aryx mcp-probe]', error);
});
return result;
}
async rescanProjectCustomization(projectId: string): Promise<WorkspaceState> {
const workspace = await this.loadWorkspace();
const project = this.requireProject(workspace, projectId);
await this.syncProjectCustomization(project);
return this.persistAndBroadcast(workspace);
}
async setProjectAgentProfileEnabled(
projectId: string,
agentProfileId: string,
enabled: boolean,
): Promise<WorkspaceState> {
const workspace = await this.loadWorkspace();
const project = this.requireProject(workspace, projectId);
project.customization = setProjectAgentProfileEnabled(
project.customization,
agentProfileId,
enabled,
);
return this.persistAndBroadcast(workspace);
}
@@ -341,7 +426,15 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
this.pruneUnavailableSessionToolingSelections(workspace);
await this.pruneUnavailableApprovalTools(workspace);
return this.persistAndBroadcast(workspace);
const result = await this.persistAndBroadcast(workspace);
if (resolution === 'accept') {
void this.probeDiscoveredMcpServers(workspace, project.discoveredTooling, serverIds).catch((error) => {
console.error('[aryx mcp-probe]', error);
});
}
return result;
}
async savePattern(pattern: PatternDefinition): Promise<WorkspaceState> {
@@ -389,6 +482,53 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
return this.persistAndBroadcast(workspace);
}
async setTerminalHeight(height?: number): Promise<WorkspaceState> {
const workspace = await this.loadWorkspace();
const normalizedHeight = normalizeTerminalHeight(height);
if (normalizedHeight === undefined) {
if (workspace.settings.terminalHeight === undefined) {
return workspace;
}
delete workspace.settings.terminalHeight;
return this.persistAndBroadcast(workspace);
}
if (workspace.settings.terminalHeight === normalizedHeight) {
return workspace;
}
workspace.settings.terminalHeight = normalizedHeight;
return this.persistAndBroadcast(workspace);
}
async describeTerminal(): Promise<TerminalSnapshot | undefined> {
return this.ptyManager.getSnapshot();
}
async createTerminal(): Promise<TerminalSnapshot> {
const workspace = await this.loadWorkspace();
return this.ptyManager.create(this.resolveTerminalWorkingDirectory(workspace));
}
async restartTerminal(): Promise<TerminalSnapshot> {
const workspace = await this.loadWorkspace();
return this.ptyManager.restart(this.resolveTerminalWorkingDirectory(workspace));
}
async killTerminal(): Promise<void> {
this.ptyManager.kill();
}
writeTerminal(data: string): void {
this.ptyManager.write(data);
}
resizeTerminal(cols: number, rows: number): void {
this.ptyManager.resize(cols, rows);
}
async deletePattern(patternId: string): Promise<WorkspaceState> {
if (isBuiltinPattern(patternId)) {
throw new Error('Built-in patterns cannot be deleted.');
@@ -619,7 +759,11 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
}
const project = this.requireProject(workspace, session.projectId);
const pattern = this.requirePattern(workspace, session.patternId);
const effectivePattern = await this.buildEffectivePattern(pattern, session);
const effectivePattern = this.applyProjectCustomizationToPattern(
await this.buildEffectivePattern(pattern, session),
project,
);
const projectInstructions = resolveProjectInstructionsContent(project.customization);
const preparedContent = prepareChatMessageContent(content);
if (!preparedContent) {
@@ -674,6 +818,7 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
workspaceKind,
mode: session.interactionMode ?? 'interactive',
messageMode,
projectInstructions,
pattern: effectivePattern,
messages: session.messages,
attachments: attachments?.length ? attachments : undefined,
@@ -1009,6 +1154,11 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
if (result.success) {
sessionAfter.pendingMcpAuth.status = 'authenticated';
sessionAfter.pendingMcpAuth.completedAt = nowIso();
// Re-probe the server now that we have a token
void this.reprobeServerByUrl(session.pendingMcpAuth.serverUrl).catch((error) => {
console.error('[aryx mcp-probe] re-probe after auth failed:', error);
});
} else {
sessionAfter.pendingMcpAuth.status = 'failed';
sessionAfter.pendingMcpAuth.errorMessage = result.error ?? 'Authentication failed';
@@ -1059,6 +1209,9 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
if (result.success) {
console.log(`[aryx oauth] ${server.name} authenticated successfully`);
void this.reprobeServerByUrl(server.url).catch((error) => {
console.error('[aryx mcp-probe] re-probe after auth failed:', error);
});
} else {
console.warn(`[aryx oauth] Proactive auth failed for ${server.name}: ${result.error}`);
}
@@ -1144,19 +1297,41 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
return queryWorkspaceSessions(workspace, input);
}
async getQuota(): Promise<Record<string, import('@shared/contracts/sidecar').QuotaSnapshot>> {
return this.sidecar.getQuota();
}
async refreshProjectGitContext(projectId?: string): Promise<WorkspaceState> {
const workspace = await this.loadWorkspace();
const projects = projectId
? [this.requireProject(workspace, projectId)]
: workspace.projects;
let changed = false;
let didRefreshGit = false;
let didSyncProjectTooling = false;
let didSyncProjectCustomization = false;
for (const project of projects) {
const projectChanged = await this.refreshGitContextForProject(project);
changed = projectChanged || changed;
didRefreshGit = await this.refreshGitContextForProject(project) || didRefreshGit;
didSyncProjectTooling = await this.syncProjectDiscoveredTooling(workspace, project) || didSyncProjectTooling;
didSyncProjectCustomization = await this.syncProjectCustomization(project) || didSyncProjectCustomization;
}
return changed ? this.persistAndBroadcast(workspace) : workspace;
const didPruneSelections = didSyncProjectTooling
? this.pruneUnavailableSessionToolingSelections(workspace)
: false;
const didPruneApprovalTools = didSyncProjectTooling
? await this.pruneUnavailableApprovalTools(workspace)
: false;
return (
didRefreshGit
|| didSyncProjectTooling
|| didSyncProjectCustomization
|| didPruneSelections
|| didPruneApprovalTools
)
? this.persistAndBroadcast(workspace)
: workspace;
}
async selectProject(projectId?: string): Promise<WorkspaceState> {
@@ -1164,6 +1339,7 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
if (projectId) {
const project = this.requireProject(workspace, projectId);
const didSyncProjectTooling = await this.syncProjectDiscoveredTooling(workspace, project);
await this.syncProjectCustomization(project);
if (didSyncProjectTooling) {
this.pruneUnavailableSessionToolingSelections(workspace);
await this.pruneUnavailableApprovalTools(workspace);
@@ -1188,6 +1364,7 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
const session = this.requireSession(workspace, sessionId);
const project = this.requireProject(workspace, session.projectId);
const didSyncProjectTooling = await this.syncProjectDiscoveredTooling(workspace, project);
await this.syncProjectCustomization(project);
if (didSyncProjectTooling) {
this.pruneUnavailableSessionToolingSelections(workspace);
await this.pruneUnavailableApprovalTools(workspace);
@@ -1209,6 +1386,25 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
return project;
}
private resolveTerminalWorkingDirectory(workspace: WorkspaceState): string {
const selectedSession = workspace.selectedSessionId
? workspace.sessions.find((session) => session.id === workspace.selectedSessionId)
: undefined;
if (selectedSession) {
const project = this.requireProject(workspace, selectedSession.projectId);
return selectedSession.cwd ?? project.path;
}
const selectedProject = workspace.selectedProjectId
? workspace.projects.find((project) => project.id === workspace.selectedProjectId)
: workspace.projects[0];
if (!selectedProject) {
throw new Error('Open a project or session before starting the integrated terminal.');
}
return selectedProject.path;
}
private async refreshGitContextForProject(project: ProjectRecord): Promise<boolean> {
if (isScratchpadProject(project)) {
if (!project.git) {
@@ -1279,11 +1475,20 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
? mergeStreamingText(existing.content, event.contentDelta)
: (event.content ?? event.contentDelta);
// When a new assistant message begins, auto-complete any previously pending
// assistant messages so only the latest one shows the "Thinking" indicator.
const completedMessages: ChatMessageRecord[] = [];
if (existing) {
existing.content = content;
existing.pending = true;
existing.authorName = event.authorName;
} else {
for (const message of session.messages) {
if (message.pending && message.role === 'assistant') {
message.pending = false;
completedMessages.push(message);
}
}
session.messages.push({
id: event.messageId,
role: 'assistant',
@@ -1306,6 +1511,16 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
session.updatedAt = occurredAt;
await this.workspaceRepository.save(workspace);
for (const completed of completedMessages) {
this.emitSessionEvent({
sessionId,
kind: 'message-complete',
occurredAt,
messageId: completed.id,
authorName: completed.authorName,
content: completed.content,
});
}
this.emitSessionEvent({
sessionId,
kind: 'message-delta',
@@ -1616,6 +1831,10 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
subagentEventKind: event.eventKind,
customAgentName: event.customAgentName,
customAgentDisplayName: event.customAgentDisplayName,
customAgentDescription: event.customAgentDescription,
subagentError: event.error,
subagentToolCallId: event.toolCallId,
subagentModel: event.model,
});
return;
case 'skill-invoked':
@@ -1678,6 +1897,24 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
agentName: event.agentName,
});
return;
case 'assistant-usage':
this.emitSessionEvent({
sessionId,
kind: 'assistant-usage',
occurredAt,
agentId: event.agentId,
agentName: event.agentName,
usageModel: event.model,
usageInputTokens: event.inputTokens,
usageOutputTokens: event.outputTokens,
usageCacheReadTokens: event.cacheReadTokens,
usageCacheWriteTokens: event.cacheWriteTokens,
usageCost: event.cost,
usageDuration: event.duration,
usageTotalNanoAiu: event.totalNanoAiu,
usageQuotaSnapshots: event.quotaSnapshots,
});
return;
}
}
@@ -1837,6 +2074,77 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
return normalizePatternModels(patternWithApprovalSettings, modelCatalog);
}
private applyProjectCustomizationToPattern(
pattern: PatternDefinition,
project: ProjectRecord,
): PatternDefinition {
if (isScratchpadProject(project)) {
return pattern;
}
const projectCustomAgents = this.buildProjectCustomAgents(project.customization);
if (projectCustomAgents.length === 0) {
return pattern;
}
const [primaryAgent, ...remainingAgents] = pattern.agents;
if (!primaryAgent) {
return pattern;
}
const existingCustomAgents = primaryAgent.copilot?.customAgents ?? [];
const existingAgentNames = new Set(existingCustomAgents.map((agent) => agent.name.toLowerCase()));
const mergedCustomAgents = [
...existingCustomAgents,
...projectCustomAgents.filter((agent) => !existingAgentNames.has(agent.name.toLowerCase())),
];
return {
...pattern,
agents: [
{
...primaryAgent,
copilot: {
...primaryAgent.copilot,
customAgents: mergedCustomAgents,
},
},
...remainingAgents,
],
};
}
private buildProjectCustomAgents(
customization?: ProjectCustomizationState,
): RunTurnCustomAgentConfig[] {
return listEnabledProjectAgentProfiles(customization).map((profile) => this.mapProjectAgentProfile(profile));
}
private mapProjectAgentProfile(profile: ProjectAgentProfile): RunTurnCustomAgentConfig {
const customAgent: RunTurnCustomAgentConfig = {
name: profile.name,
prompt: profile.prompt,
};
if (profile.displayName) {
customAgent.displayName = profile.displayName;
}
if (profile.description) {
customAgent.description = profile.description;
}
if (profile.tools) {
customAgent.tools = profile.tools;
}
if (profile.infer !== undefined) {
customAgent.infer = profile.infer;
}
return customAgent;
}
private async listKnownApprovalToolNames(
workspace: WorkspaceState,
project?: ProjectRecord,
@@ -1915,6 +2223,25 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
return true;
}
private async syncProjectCustomization(project: ProjectRecord): Promise<boolean> {
if (isScratchpadProject(project)) {
if (!project.customization || this.equalProjectCustomizationState(project.customization, undefined)) {
return false;
}
project.customization = undefined;
return true;
}
const nextState = await this.customizationScanner.scanProject(project.path, project.customization);
if (this.equalProjectCustomizationState(project.customization, nextState)) {
return false;
}
project.customization = nextState;
return true;
}
private async syncProjectDiscoveredTooling(
workspace: WorkspaceState,
project: ProjectRecord,
@@ -1941,6 +2268,232 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
return true;
}
private async probeAllAcceptedMcpServers(workspace: WorkspaceState): Promise<void> {
const targets = [
...this.listAcceptedDiscoveredServerDefinitions(
workspace,
(server) => !server.probedTools || server.probedTools.length === 0,
),
...workspace.settings.tooling.mcpServers.filter(
(server) => server.tools.length === 0 && (!server.probedTools || server.probedTools.length === 0),
),
];
await this.probeWorkspaceMcpServers(workspace, targets);
}
private async probeDiscoveredMcpServersFromState(
workspace: WorkspaceState,
state?: DiscoveredToolingState,
): Promise<void> {
const targets = listAcceptedDiscoveredMcpServers(state)
.filter((server) => !server.probedTools || server.probedTools.length === 0)
.map((server) => this.discoveredServerToDefinition(server));
await this.probeWorkspaceMcpServers(workspace, targets);
}
private async probeDiscoveredMcpServers(
workspace: WorkspaceState,
state: DiscoveredToolingState | undefined,
serverIds: ReadonlyArray<string>,
): Promise<void> {
const targets = listAcceptedDiscoveredMcpServers(state)
.filter((server) => serverIds.includes(server.id))
.map((server) => this.discoveredServerToDefinition(server));
await this.probeWorkspaceMcpServers(workspace, targets);
}
private async probeWorkspaceMcpServers(
workspace: WorkspaceState,
targets: ReadonlyArray<McpServerDefinition>,
): Promise<void> {
const uniqueTargets = [...new Map(targets.map((server) => [server.id, server])).values()];
if (uniqueTargets.length === 0) {
return;
}
const targetIds = uniqueTargets.map((server) => server.id);
const tokenLookup = (url: string) => getStoredToken(url)?.accessToken;
await this.enqueueMcpProbeUpdate(async () => {
if (this.addMcpProbingServerIds(workspace, targetIds)) {
await this.persistAndBroadcast(workspace);
}
});
try {
await this.probeMcpServers(uniqueTargets, tokenLookup, (result) =>
this.enqueueMcpProbeUpdate(async () => {
const didUpdateProbing = this.removeMcpProbingServerIds(workspace, [result.serverId]);
const didApplyResult = this.applyMcpProbeResult(workspace, result);
if (didUpdateProbing || didApplyResult) {
await this.persistAndBroadcast(workspace);
}
}),
);
} finally {
await this.enqueueMcpProbeUpdate(async () => {
if (this.removeMcpProbingServerIds(workspace, targetIds)) {
await this.persistAndBroadcast(workspace);
}
});
}
}
/**
* Re-probes all MCP servers matching a given URL after OAuth authentication
* succeeds, so their tools appear in the approval pill without restart.
*/
private async reprobeServerByUrl(serverUrl: string): Promise<void> {
const workspace = await this.loadWorkspace();
// Collect matching servers from manual config and discovered tooling
const targets: McpServerDefinition[] = [];
for (const server of workspace.settings.tooling.mcpServers) {
if (server.transport !== 'local' && server.url === serverUrl) {
targets.push(server);
}
}
const allDiscovered = [
...(workspace.settings.discoveredUserTooling?.mcpServers ?? []),
...workspace.projects.flatMap((p) => p.discoveredTooling?.mcpServers ?? []),
];
for (const server of allDiscovered) {
if (server.status === 'accepted' && server.transport !== 'local' && server.url === serverUrl) {
targets.push(this.discoveredServerToDefinition(server));
}
}
await this.probeWorkspaceMcpServers(workspace, targets);
}
private listAcceptedDiscoveredServerDefinitions(
workspace: WorkspaceState,
predicate?: (server: DiscoveredMcpServer) => boolean,
): McpServerDefinition[] {
const definitions: McpServerDefinition[] = [];
for (const state of this.listDiscoveredToolingStates(workspace)) {
for (const server of listAcceptedDiscoveredMcpServers(state)) {
if (predicate && !predicate(server)) {
continue;
}
definitions.push(this.discoveredServerToDefinition(server));
}
}
return definitions;
}
private listDiscoveredToolingStates(workspace: WorkspaceState): Array<DiscoveredToolingState | undefined> {
return [
workspace.settings.discoveredUserTooling,
...workspace.projects.map((project) => project.discoveredTooling),
];
}
private addMcpProbingServerIds(workspace: WorkspaceState, serverIds: ReadonlyArray<string>): boolean {
return this.updateMcpProbingServerIds(workspace, serverIds, 'add');
}
private removeMcpProbingServerIds(workspace: WorkspaceState, serverIds: ReadonlyArray<string>): boolean {
return this.updateMcpProbingServerIds(workspace, serverIds, 'remove');
}
private updateMcpProbingServerIds(
workspace: WorkspaceState,
serverIds: ReadonlyArray<string>,
operation: 'add' | 'remove',
): boolean {
const next = new Set(workspace.mcpProbingServerIds ?? []);
const before = next.size;
for (const serverId of serverIds) {
if (operation === 'add') {
next.add(serverId);
} else {
next.delete(serverId);
}
}
if (next.size === before) {
return false;
}
if (next.size === 0) {
delete workspace.mcpProbingServerIds;
} else {
workspace.mcpProbingServerIds = [...next];
}
return true;
}
private applyMcpProbeResult(workspace: WorkspaceState, result: McpProbeResult): boolean {
if (result.status !== 'success' || result.tools.length === 0) {
return false;
}
let changed = false;
for (const server of workspace.settings.tooling.mcpServers) {
if (server.id !== result.serverId) {
continue;
}
server.probedTools = result.tools;
changed = true;
}
for (const state of this.listDiscoveredToolingStates(workspace)) {
for (const server of state?.mcpServers ?? []) {
if (server.id !== result.serverId) {
continue;
}
server.probedTools = result.tools;
changed = true;
}
}
return changed;
}
private async enqueueMcpProbeUpdate(update: () => Promise<void>): Promise<void> {
const next = this.mcpProbeUpdateQueue.then(update, update);
this.mcpProbeUpdateQueue = next.catch(() => undefined);
await next;
}
private discoveredServerToDefinition(server: DiscoveredMcpServer): McpServerDefinition {
if (server.transport === 'local') {
return {
id: server.id,
name: server.name,
transport: 'local',
command: server.command,
args: [...server.args],
cwd: server.cwd,
env: server.env ? { ...server.env } : undefined,
tools: [...server.tools],
timeoutMs: server.timeoutMs,
createdAt: nowIso(),
updatedAt: nowIso(),
};
}
return {
id: server.id,
name: server.name,
transport: server.transport,
url: server.url,
headers: server.headers ? { ...server.headers } : undefined,
tools: [...server.tools],
timeoutMs: server.timeoutMs,
createdAt: nowIso(),
updatedAt: nowIso(),
};
}
private pruneUnavailableSessionToolingSelections(workspace: WorkspaceState): boolean {
let changed = false;
@@ -1979,8 +2532,27 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
left?: DiscoveredToolingState,
right?: DiscoveredToolingState,
): boolean {
return JSON.stringify(normalizeDiscoveredToolingState(left).mcpServers)
=== JSON.stringify(normalizeDiscoveredToolingState(right).mcpServers);
const stripRuntime = (servers: DiscoveredMcpServer[]) =>
servers.map(({ probedTools: _, ...rest }) => rest);
return JSON.stringify(stripRuntime(normalizeDiscoveredToolingState(left).mcpServers))
=== JSON.stringify(stripRuntime(normalizeDiscoveredToolingState(right).mcpServers));
}
private equalProjectCustomizationState(
left?: ProjectCustomizationState,
right?: ProjectCustomizationState,
): boolean {
const normalizedLeft = normalizeProjectCustomizationState(left);
const normalizedRight = normalizeProjectCustomizationState(right);
return JSON.stringify({
instructions: normalizedLeft.instructions,
agentProfiles: normalizedLeft.agentProfiles,
promptFiles: normalizedLeft.promptFiles,
}) === JSON.stringify({
instructions: normalizedRight.instructions,
agentProfiles: normalizedRight.agentProfiles,
promptFiles: normalizedRight.promptFiles,
});
}
private updateSessionRun(
@@ -2015,33 +2587,41 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
this.emit('session-event', event);
}
private failInterruptedPendingApprovals(workspace: WorkspaceState): boolean {
private cleanupInterruptedSessions(workspace: WorkspaceState): boolean {
let changed = false;
for (const session of workspace.sessions) {
const pendingApprovals = listPendingApprovals(session);
if (pendingApprovals.length === 0) {
const hasPendingUserInput = session.pendingUserInput !== undefined;
const failedRequestIds = new Set(
session.runs
.filter((run) => run.status === 'running')
.map((run) => run.requestId),
);
if (pendingApprovals.length === 0 && !hasPendingUserInput && failedRequestIds.size === 0) {
continue;
}
changed = true;
const failedAt = nowIso();
const error = 'Pending approval was interrupted because Aryx restarted before a decision was recorded.';
const requestIds = this.rejectPendingApprovals(session, failedAt, error);
session.status = 'error';
session.lastError = error;
session.updatedAt = failedAt;
if (requestIds.length === 0) {
const fallbackRequestId = session.runs.find((run) => run.status === 'running')?.requestId;
if (fallbackRequestId) {
requestIds.push(fallbackRequestId);
if (pendingApprovals.length > 0) {
for (const requestId of this.rejectPendingApprovals(session, failedAt, INTERRUPTED_APPROVAL_ERROR)) {
failedRequestIds.add(requestId);
}
}
for (const requestId of requestIds) {
if (session.pendingUserInput) {
this.pendingUserInputHandles.delete(session.pendingUserInput.id);
session.pendingUserInput = undefined;
}
session.status = 'error';
session.lastError = INTERRUPTED_RUN_ERROR;
session.updatedAt = failedAt;
for (const requestId of failedRequestIds) {
this.updateSessionRun(session, requestId, (run) =>
failSessionRunRecord(run, failedAt, error));
failSessionRunRecord(run, failedAt, INTERRUPTED_RUN_ERROR));
}
}
+42 -5
View File
@@ -5,28 +5,32 @@ import { ipcChannels } from '@shared/contracts/channels';
import type {
CancelSessionTurnInput,
CreateSessionInput,
ResolveProjectDiscoveredToolingInput,
ResolveWorkspaceDiscoveredToolingInput,
DismissSessionPlanReviewInput,
DismissSessionMcpAuthInput,
DismissSessionPlanReviewInput,
DeleteSessionInput,
StartSessionMcpAuthInput,
DuplicateSessionInput,
RenameSessionInput,
RescanProjectConfigsInput,
RescanProjectCustomizationInput,
ResolveProjectDiscoveredToolingInput,
ResolveSessionApprovalInput,
ResolveSessionUserInputInput,
ResolveWorkspaceDiscoveredToolingInput,
SaveLspProfileInput,
SaveMcpServerInput,
SavePatternInput,
SendSessionMessageInput,
SetPatternFavoriteInput,
SetProjectAgentProfileEnabledInput,
SetSessionArchivedInput,
SetSessionInteractionModeInput,
SetSessionPinnedInput,
SetTerminalHeightInput,
ResizeTerminalInput,
UpdateSessionModelConfigInput,
UpdateSessionApprovalSettingsInput,
UpdateSessionToolingInput,
UpdateSessionModelConfigInput,
DeleteSessionInput,
} from '@shared/contracts/ipc';
import type { QuerySessionsInput } from '@shared/domain/sessionLibrary';
import type { AppearanceTheme } from '@shared/domain/tooling';
@@ -53,11 +57,21 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
ipcMain.handle(ipcChannels.rescanProjectConfigs, (_event, input: RescanProjectConfigsInput) =>
service.rescanProjectConfigs(input.projectId),
);
ipcMain.handle(
ipcChannels.rescanProjectCustomization,
(_event, input: RescanProjectCustomizationInput) =>
service.rescanProjectCustomization(input.projectId),
);
ipcMain.handle(
ipcChannels.resolveProjectDiscoveredTooling,
(_event, input: ResolveProjectDiscoveredToolingInput) =>
service.resolveProjectDiscoveredTooling(input.projectId, input.serverIds, input.resolution),
);
ipcMain.handle(
ipcChannels.setProjectAgentProfileEnabled,
(_event, input: SetProjectAgentProfileEnabledInput) =>
service.setProjectAgentProfileEnabled(input.projectId, input.agentProfileId, input.enabled),
);
ipcMain.handle(ipcChannels.savePattern, (_event, input: SavePatternInput) => service.savePattern(input.pattern));
ipcMain.handle(ipcChannels.deletePattern, (_event, patternId: string) => service.deletePattern(patternId));
ipcMain.handle(ipcChannels.setPatternFavorite, (_event, input: SetPatternFavoriteInput) =>
@@ -68,6 +82,10 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
applyTitleBarTheme(window, theme);
return result;
});
ipcMain.handle(
ipcChannels.setTerminalHeight,
(_event, input: SetTerminalHeightInput) => service.setTerminalHeight(input.height),
);
ipcMain.handle(ipcChannels.saveMcpServer, (_event, input: SaveMcpServerInput) =>
service.saveMcpServer(input.server),
);
@@ -80,6 +98,16 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
ipcMain.handle(ipcChannels.deleteLspProfile, (_event, profileId: string) =>
service.deleteLspProfile(profileId),
);
ipcMain.handle(ipcChannels.describeTerminal, () => service.describeTerminal());
ipcMain.handle(ipcChannels.createTerminal, () => service.createTerminal());
ipcMain.handle(ipcChannels.restartTerminal, () => service.restartTerminal());
ipcMain.handle(ipcChannels.killTerminal, () => service.killTerminal());
ipcMain.on(ipcChannels.writeTerminal, (_event, data: string) => {
service.writeTerminal(data);
});
ipcMain.on(ipcChannels.resizeTerminal, (_event, input: ResizeTerminalInput) => {
service.resizeTerminal(input.cols, input.rows);
});
ipcMain.handle(ipcChannels.updateSessionTooling, (_event, input: UpdateSessionToolingInput) =>
service.updateSessionTooling(
input.sessionId,
@@ -145,6 +173,7 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
ipcMain.handle(ipcChannels.selectSession, (_event, sessionId?: string) => service.selectSession(sessionId));
ipcMain.handle(ipcChannels.openAppDataFolder, () => service.openAppDataFolder());
ipcMain.handle(ipcChannels.resetLocalWorkspace, () => service.resetLocalWorkspace());
ipcMain.handle(ipcChannels.getQuota, () => service.getQuota());
service.on('workspace-updated', (workspace) => {
window.webContents.send(ipcChannels.workspaceUpdated, workspace);
@@ -153,4 +182,12 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
service.on('session-event', (event) => {
window.webContents.send(ipcChannels.sessionEvent, event);
});
service.on('terminal-data', (data) => {
window.webContents.send(ipcChannels.terminalData, data);
});
service.on('terminal-exit', (info) => {
window.webContents.send(ipcChannels.terminalExit, info);
});
}
+4 -1
View File
@@ -4,6 +4,7 @@ import { createBuiltinPatterns, resolvePatternGraph } from '@shared/domain/patte
import type { PatternDefinition } from '@shared/domain/pattern';
import { isScratchpadProject, mergeScratchpadProject } from '@shared/domain/project';
import { normalizeDiscoveredToolingState } from '@shared/domain/discoveredTooling';
import { normalizeProjectCustomizationState } from '@shared/domain/projectCustomization';
import { normalizeSessionRunRecords } from '@shared/domain/runTimeline';
import type { SessionRecord } from '@shared/domain/session';
import {
@@ -73,6 +74,7 @@ export class WorkspaceRepository {
(stored.projects ?? []).map((project) => ({
...project,
discoveredTooling: normalizeDiscoveredToolingState(project.discoveredTooling),
customization: normalizeProjectCustomizationState(project.customization),
})),
this.scratchpadPath,
);
@@ -121,8 +123,9 @@ export class WorkspaceRepository {
}
async save(workspace: WorkspaceState): Promise<void> {
const { mcpProbingServerIds: _mcpProbingServerIds, ...persistedWorkspace } = workspace;
await writeJsonFile(this.filePath, {
...workspace,
...persistedWorkspace,
lastUpdatedAt: nowIso(),
});
}
+370
View File
@@ -0,0 +1,370 @@
import { readdir, readFile } from 'node:fs/promises';
import { basename, join, relative } from 'node:path';
import { parse as parseYaml } from 'yaml';
import {
mergeProjectCustomizationState,
normalizeProjectCustomizationState,
type ProjectAgentProfile,
type ProjectCustomizationState,
type ProjectInstructionFile,
type ProjectPromptFile,
type ProjectPromptVariable,
} from '@shared/domain/projectCustomization';
import { nowIso } from '@shared/utils/ids';
const promptVariablePattern = /\$\{input:([a-zA-Z0-9_-]+):([^}]+)\}/g;
export class ProjectCustomizationScanner {
async scanProject(
projectPath: string,
current?: ProjectCustomizationState,
): Promise<ProjectCustomizationState> {
const previous = normalizeProjectCustomizationState(current);
const instructions = await this.scanInstructionFiles(projectPath, previous);
const agentProfiles = await this.scanAgentProfiles(projectPath, previous);
const promptFiles = await this.scanPromptFiles(projectPath, previous);
return mergeProjectCustomizationState(
previous,
{
instructions,
agentProfiles,
promptFiles,
},
nowIso(),
);
}
private async scanInstructionFiles(
projectPath: string,
previous: ProjectCustomizationState,
): Promise<ProjectInstructionFile[]> {
const previousByPath = new Map(previous.instructions.map((instruction) => [instruction.sourcePath, instruction]));
const sourcePaths = ['.github\\copilot-instructions.md', 'AGENTS.md'] as const;
const instructions: ProjectInstructionFile[] = [];
for (const sourcePath of sourcePaths) {
const filePath = join(projectPath, ...sourcePath.split('\\'));
const contents = await this.readProjectFile(filePath);
if (contents.kind === 'missing') {
continue;
}
if (contents.kind === 'retain-previous') {
const existing = previousByPath.get(sourcePath);
if (existing) {
instructions.push(existing);
}
continue;
}
const content = contents.value.trim();
if (!content) {
continue;
}
instructions.push({
id: buildProjectCustomizationItemId('instruction', sourcePath),
sourcePath,
content,
});
}
return instructions;
}
private async scanAgentProfiles(
projectPath: string,
previous: ProjectCustomizationState,
): Promise<ProjectAgentProfile[]> {
const previousByPath = new Map(previous.agentProfiles.map((profile) => [profile.sourcePath, profile]));
const filePaths = await this.listProjectFiles(join(projectPath, '.github', 'agents'), '.agent.md');
const profiles: ProjectAgentProfile[] = [];
for (const filePath of filePaths) {
const sourcePath = toProjectSourcePath(projectPath, filePath);
const contents = await this.readProjectFile(filePath);
if (contents.kind === 'retain-previous') {
const existing = previousByPath.get(sourcePath);
if (existing) {
profiles.push(existing);
}
continue;
}
if (contents.kind === 'missing') {
continue;
}
const parsedFile = parseProjectFrontmatter(contents.value, sourcePath);
if (!parsedFile) {
const existing = previousByPath.get(sourcePath);
if (existing) {
profiles.push(existing);
}
continue;
}
const name = readOptionalString(parsedFile.attributes, ['name'])
?? basename(filePath, '.agent.md');
const prompt = parsedFile.body.trim();
if (!name || !prompt) {
continue;
}
profiles.push({
id: buildProjectCustomizationItemId('agent', sourcePath),
name,
displayName: readOptionalString(parsedFile.attributes, ['displayName', 'display-name']),
description: readOptionalString(parsedFile.attributes, ['description']),
tools: readOptionalStringArray(parsedFile.attributes.tools),
prompt,
mcpServers: readOptionalNamedObjectMap(parsedFile.attributes['mcp-servers']),
infer: typeof parsedFile.attributes.infer === 'boolean' ? parsedFile.attributes.infer : undefined,
sourcePath,
enabled: previousByPath.get(sourcePath)?.enabled ?? true,
});
}
return profiles;
}
private async scanPromptFiles(
projectPath: string,
previous: ProjectCustomizationState,
): Promise<ProjectPromptFile[]> {
const previousByPath = new Map(previous.promptFiles.map((promptFile) => [promptFile.sourcePath, promptFile]));
const filePaths = await this.listProjectFiles(join(projectPath, '.github', 'prompts'), '.prompt.md');
const promptFiles: ProjectPromptFile[] = [];
for (const filePath of filePaths) {
const sourcePath = toProjectSourcePath(projectPath, filePath);
const contents = await this.readProjectFile(filePath);
if (contents.kind === 'retain-previous') {
const existing = previousByPath.get(sourcePath);
if (existing) {
promptFiles.push(existing);
}
continue;
}
if (contents.kind === 'missing') {
continue;
}
const parsedFile = parseProjectFrontmatter(contents.value, sourcePath);
if (!parsedFile) {
const existing = previousByPath.get(sourcePath);
if (existing) {
promptFiles.push(existing);
}
continue;
}
const template = parsedFile.body.trim();
if (!template) {
continue;
}
promptFiles.push({
id: buildProjectCustomizationItemId('prompt', sourcePath),
name: basename(filePath, '.prompt.md'),
description: readOptionalString(parsedFile.attributes, ['description']),
agent: readOptionalString(parsedFile.attributes, ['agent']),
template,
variables: extractPromptVariables(template),
sourcePath,
});
}
return promptFiles;
}
private async listProjectFiles(directoryPath: string, suffix: string): Promise<string[]> {
try {
const entries = await readdir(directoryPath, { withFileTypes: true });
return entries
.filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith(suffix))
.map((entry) => join(directoryPath, entry.name))
.sort((left, right) => left.localeCompare(right));
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return [];
}
console.warn(`[aryx customization] Failed to read directory ${directoryPath}:`, error);
return [];
}
}
private async readProjectFile(filePath: string): Promise<
| { kind: 'success'; value: string }
| { kind: 'missing' }
| { kind: 'retain-previous' }
> {
try {
return {
kind: 'success',
value: await readFile(filePath, 'utf8'),
};
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return { kind: 'missing' };
}
console.warn(`[aryx customization] Failed to read ${filePath}:`, error);
return { kind: 'retain-previous' };
}
}
}
function parseProjectFrontmatter(
contents: string,
sourcePath: string,
): { attributes: Record<string, unknown>; body: string } | undefined {
const match = /^(?:\uFEFF)?---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/u.exec(contents);
if (!match) {
return {
attributes: {},
body: contents,
};
}
try {
const parsed = parseYaml(match[1]);
if (!isPlainObject(parsed) && parsed !== null && parsed !== undefined) {
console.warn(`[aryx customization] Ignoring non-object frontmatter in ${sourcePath}.`);
return undefined;
}
return {
attributes: isPlainObject(parsed) ? parsed : {},
body: match[2],
};
} catch (error) {
console.warn(`[aryx customization] Failed to parse frontmatter in ${sourcePath}:`, error);
return undefined;
}
}
function extractPromptVariables(template: string): ProjectPromptVariable[] {
const variables: ProjectPromptVariable[] = [];
const seenNames = new Set<string>();
let match: RegExpExecArray | null;
while ((match = promptVariablePattern.exec(template))) {
const name = match[1]?.trim();
if (!name || seenNames.has(name)) {
continue;
}
seenNames.add(name);
variables.push({
name,
placeholder: match[2]?.trim() ?? '',
});
}
promptVariablePattern.lastIndex = 0;
return variables;
}
function buildProjectCustomizationItemId(kind: 'instruction' | 'agent' | 'prompt', sourcePath: string): string {
return `project_customization_${kind}_${normalizeIdentifierSegment(sourcePath)}`;
}
function toProjectSourcePath(projectPath: string, filePath: string): string {
const relativePath = relative(projectPath, filePath).trim();
return relativePath ? relativePath.replaceAll('/', '\\') : basename(filePath);
}
function normalizeIdentifierSegment(value: string): string {
const normalized = value
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, '_')
.replace(/^_+|_+$/g, '');
return normalized.length > 0 ? normalized : 'item';
}
function readOptionalString(
record: Record<string, unknown>,
keys: ReadonlyArray<string>,
): string | undefined {
for (const key of keys) {
const value = record[key];
if (typeof value !== 'string') {
continue;
}
const trimmed = value.trim();
if (trimmed.length > 0) {
return trimmed;
}
}
return undefined;
}
function readOptionalStringArray(value: unknown): string[] | undefined {
if (value === undefined) {
return undefined;
}
if (typeof value === 'string') {
const trimmed = value.trim();
return trimmed.length > 0 ? [trimmed] : [];
}
if (!Array.isArray(value)) {
return undefined;
}
return [...new Set(value
.filter((entry): entry is string => typeof entry === 'string')
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0))];
}
function readOptionalNamedObjectMap(
value: unknown,
): Record<string, Record<string, unknown>> | undefined {
if (!isPlainObject(value)) {
return undefined;
}
const entries = Object.entries(value)
.map(([name, config]) => [name.trim(), normalizeYamlValue(config)] as const)
.filter(([name, config]) => name.length > 0 && isPlainObject(config))
.sort(([leftName], [rightName]) => leftName.localeCompare(rightName));
if (entries.length === 0) {
return undefined;
}
return Object.fromEntries(entries.map(([name, config]) => [name, config as Record<string, unknown>]));
}
function normalizeYamlValue(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map((entry) => normalizeYamlValue(entry));
}
if (!isPlainObject(value)) {
return typeof value === 'string' ? value.trim() : value;
}
return Object.fromEntries(
Object.entries(value)
.map(([key, nestedValue]) => [key.trim(), normalizeYamlValue(nestedValue)] as const)
.filter(([key]) => key.length > 0)
.sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey)),
);
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === 'object' && !Array.isArray(value);
}
+16 -3
View File
@@ -1,11 +1,13 @@
import { randomBytes, createHash } from 'node:crypto';
import { createServer, type Server, type IncomingMessage, type ServerResponse } from 'node:http';
import { shell } from 'electron';
import electron from 'electron';
import type { McpOauthStaticClientConfig } from '@shared/domain/mcpAuth';
import { storeToken, buildWellKnownUrl, buildWellKnownUrlFallback, type McpOAuthToken } from './mcpTokenStore';
import { storeToken, buildWellKnownUrl, buildWellKnownUrlFallback, buildWellKnownUrlOriginOnly, type McpOAuthToken } from './mcpTokenStore';
const { shell } = electron;
/* ── Public API ──────────────────────────────────────────────── */
@@ -226,7 +228,18 @@ interface AuthServerMetadata {
async function fetchWellKnownMetadata(baseUrl: string, suffix: string): Promise<Record<string, unknown> | undefined> {
const rfcUrl = buildWellKnownUrl(baseUrl, suffix);
const fallbackUrl = buildWellKnownUrlFallback(baseUrl, suffix);
const urls = rfcUrl === fallbackUrl ? [rfcUrl] : [rfcUrl, fallbackUrl];
const originOnlyUrl = buildWellKnownUrlOriginOnly(baseUrl, suffix);
// Deduplicate: RFC path, appended fallback, then origin-only (for servers
// that serve metadata at the origin without the resource path suffix).
const seen = new Set<string>();
const urls: string[] = [];
for (const url of [rfcUrl, fallbackUrl, originOnlyUrl]) {
if (!seen.has(url)) {
seen.add(url);
urls.push(url);
}
}
for (const url of urls) {
try {
+5
View File
@@ -66,3 +66,8 @@ export function buildWellKnownUrlFallback(baseUrl: string, wellKnownSuffix: stri
const base = baseUrl.replace(/\/+$/, '');
return `${base}/.well-known/${wellKnownSuffix}`;
}
export function buildWellKnownUrlOriginOnly(baseUrl: string, wellKnownSuffix: string): string {
const parsed = new URL(baseUrl);
return `${parsed.origin}/.well-known/${wellKnownSuffix}`;
}
+237
View File
@@ -0,0 +1,237 @@
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
import type { McpServerDefinition } from '@shared/domain/tooling';
export interface McpProbedTool {
name: string;
description?: string;
}
export interface McpProbeResult {
serverId: string;
serverName: string;
tools: McpProbedTool[];
status: 'success' | 'failed';
error?: string;
}
const CLIENT_INFO = { name: 'aryx', version: '1.0.0' };
const DEFAULT_TIMEOUT_MS = 30_000;
const MAX_CONCURRENCY = 5;
export async function probeServers(
servers: ReadonlyArray<McpServerDefinition>,
tokenLookup?: (serverUrl: string) => string | undefined,
onResult?: (result: McpProbeResult) => void | Promise<void>,
): Promise<McpProbeResult[]> {
if (servers.length === 0) {
return [];
}
const results = new Array<McpProbeResult>(servers.length);
let nextIndex = 0;
const workerCount = Math.min(MAX_CONCURRENCY, servers.length);
async function worker(): Promise<void> {
while (true) {
const index = nextIndex;
nextIndex += 1;
const server = servers[index];
if (!server) {
return;
}
const result = await probeServer(server, tokenLookup);
results[index] = result;
await onResult?.(result);
}
}
await Promise.all(Array.from({ length: workerCount }, () => worker()));
return results;
}
export async function probeServer(
server: McpServerDefinition,
tokenLookup?: (serverUrl: string) => string | undefined,
): Promise<McpProbeResult> {
const timeoutMs = server.timeoutMs ?? DEFAULT_TIMEOUT_MS;
try {
const tools = await withTimeout(
probeServerCore(server, tokenLookup),
timeoutMs,
`Probe timed out after ${timeoutMs}ms`,
);
console.log(`[aryx mcp-probe] ${server.name}: discovered ${tools.length} tool(s)`);
return {
serverId: server.id,
serverName: server.name,
tools,
status: 'success',
};
} catch (error) {
const message = formatProbeError(error);
console.warn(`[aryx mcp-probe] ${server.name}: failed — ${message}`);
return {
serverId: server.id,
serverName: server.name,
tools: [],
status: 'failed',
error: message,
};
}
}
async function probeServerCore(
server: McpServerDefinition,
tokenLookup?: (serverUrl: string) => string | undefined,
): Promise<McpProbedTool[]> {
if (server.transport === 'local' || server.transport === 'sse') {
return probeWithTransport(createTransport(server, tokenLookup));
}
// For HTTP servers, try Streamable HTTP first, then fall back to SSE.
// Many MCP servers only support SSE despite being configured as generic HTTP.
const headers = buildHeaders(server.url, server.headers, tokenLookup);
const headerOpts = headers ? { requestInit: { headers } } : undefined;
try {
return await probeWithTransport(
new StreamableHTTPClientTransport(new URL(server.url), headerOpts),
);
} catch (streamableError) {
try {
return await probeWithTransport(
new SSEClientTransport(new URL(server.url), headerOpts),
);
} catch (sseError) {
// SSE 405 means the server IS Streamable HTTP — surface the original error.
const sseCode = (sseError as { code?: number }).code;
if (sseCode === 405) throw streamableError;
throw sseError;
}
}
}
async function probeWithTransport(
transport: InstanceType<typeof StdioClientTransport> | InstanceType<typeof SSEClientTransport> | InstanceType<typeof StreamableHTTPClientTransport>,
): Promise<McpProbedTool[]> {
const client = new Client(CLIENT_INFO, { capabilities: {} });
try {
await client.connect(transport);
// Use listTools() which validates schemas. If a tool has a complex
// outputSchema with $ref that the SDK can't resolve, fall back to
// a raw JSON-RPC request that skips schema compilation.
let rawTools: Array<{ name?: string; description?: string }>;
try {
const result = await client.listTools();
rawTools = result.tools ?? [];
} catch {
// listTools failed (likely schema validation of outputSchema $ref).
// Send raw JSON-RPC and extract tool names without validation.
const response = await new Promise<{ tools?: Array<{ name?: string; description?: string }> }>((resolve, reject) => {
const id = Math.random().toString(36).slice(2);
const onMessage = (msg: { id?: string; result?: unknown; error?: unknown }) => {
if (msg.id !== id) return;
transport.onmessage = undefined;
if (msg.error) reject(new Error(JSON.stringify(msg.error)));
else resolve((msg.result ?? {}) as { tools?: Array<{ name?: string; description?: string }> });
};
const prevHandler = transport.onmessage;
transport.onmessage = (msg) => {
onMessage(msg as { id?: string; result?: unknown; error?: unknown });
if (prevHandler) (prevHandler as (msg: unknown) => void)(msg);
};
transport.send({ jsonrpc: '2.0', id, method: 'tools/list', params: {} }).catch(reject);
});
rawTools = response.tools ?? [];
}
return rawTools
.filter((tool) => typeof tool.name === 'string' && tool.name.trim().length > 0)
.map((tool) => ({
name: tool.name!.trim(),
description: typeof tool.description === 'string' && tool.description.trim().length > 0
? tool.description.trim()
: undefined,
}));
} finally {
try {
await client.close();
} catch {
// Ignore close errors — connection may already be closed
}
}
}
function createTransport(
server: McpServerDefinition,
tokenLookup?: (serverUrl: string) => string | undefined,
) {
if (server.transport === 'local') {
return new StdioClientTransport({
command: server.command,
args: server.args.length > 0 ? server.args : undefined,
env: server.env
? Object.fromEntries(
Object.entries({ ...process.env, ...server.env })
.filter((entry): entry is [string, string] => entry[1] !== undefined),
)
: undefined,
cwd: server.cwd,
stderr: 'ignore',
});
}
const headers = buildHeaders(server.url, server.headers, tokenLookup);
return new SSEClientTransport(
new URL(server.url),
headers ? { requestInit: { headers } } : undefined,
);
}
function buildHeaders(
serverUrl: string,
configHeaders?: Record<string, string>,
tokenLookup?: (serverUrl: string) => string | undefined,
): Record<string, string> | undefined {
const bearerToken = tokenLookup?.(serverUrl);
if (!bearerToken && !configHeaders) {
return undefined;
}
return {
...(configHeaders ?? {}),
...(bearerToken ? { Authorization: `Bearer ${bearerToken}` } : {}),
};
}
function formatProbeError(error: unknown): string {
if (!(error instanceof Error)) return String(error);
const httpCode = (error as { code?: number }).code;
const base = error.message;
if (typeof httpCode === 'number' && httpCode >= 100) {
return `HTTP ${httpCode}: ${base}`;
}
return base;
}
function withTimeout<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(message)), ms);
promise.then(
(value) => { clearTimeout(timer); resolve(value); },
(error) => { clearTimeout(timer); reject(error); },
);
});
}
+352
View File
@@ -0,0 +1,352 @@
import { EventEmitter } from 'node:events';
import { constants as fsConstants } from 'node:fs';
import { access, stat } from 'node:fs/promises';
import { basename, delimiter, isAbsolute, join } from 'node:path';
import type { TerminalExitInfo, TerminalSnapshot } from '@shared/domain/terminal';
const DEFAULT_COLS = 80;
const DEFAULT_ROWS = 24;
const DEFAULT_TERMINAL_NAME = 'xterm-256color';
const DEFAULT_UNIX_SHELL = '/bin/bash';
const DEFAULT_WINDOWS_FALLBACK_SHELL = 'cmd.exe';
type Disposable = {
dispose(): void;
};
interface ManagedPty {
readonly pid: number;
write(data: string): void;
resize(cols: number, rows: number): void;
kill(signal?: string): void;
onData(listener: (data: string) => void): Disposable;
onExit(listener: (event: TerminalExitInfo) => void): Disposable;
}
type PtySpawnOptions = {
name: string;
cols: number;
rows: number;
cwd: string;
env: Record<string, string>;
};
type PtySpawn = (
file: string,
args: string[],
options: PtySpawnOptions,
) => ManagedPty | Promise<ManagedPty>;
type CommandExists = (
command: string,
env: NodeJS.ProcessEnv,
platform: NodeJS.Platform,
) => Promise<boolean>;
type ActiveTerminal = {
pty: ManagedPty;
snapshot: TerminalSnapshot;
dataSubscription: Disposable;
exitSubscription: Disposable;
};
type PtyManagerEvents = {
data: [string];
exit: [TerminalExitInfo];
};
export interface PtyManagerOptions {
platform?: NodeJS.Platform;
env?: NodeJS.ProcessEnv;
spawnPty?: PtySpawn;
commandExists?: CommandExists;
}
export class PtyManager extends EventEmitter<PtyManagerEvents> {
private readonly platform: NodeJS.Platform;
private readonly env: NodeJS.ProcessEnv;
private readonly spawnPty: PtySpawn;
private readonly commandExists: CommandExists;
private activeTerminal?: ActiveTerminal;
constructor(options: PtyManagerOptions = {}) {
super();
this.platform = options.platform ?? process.platform;
this.env = options.env ?? process.env;
this.spawnPty = options.spawnPty ?? defaultSpawnPty;
this.commandExists = options.commandExists ?? commandExistsOnPath;
}
get isRunning(): boolean {
return this.activeTerminal !== undefined;
}
getSnapshot(): TerminalSnapshot | undefined {
return this.activeTerminal ? { ...this.activeTerminal.snapshot } : undefined;
}
async create(cwd: string, cols = DEFAULT_COLS, rows = DEFAULT_ROWS): Promise<TerminalSnapshot> {
if (this.activeTerminal) {
return { ...this.activeTerminal.snapshot };
}
return this.spawnTerminal(cwd, cols, rows);
}
async restart(
cwd: string,
cols = this.activeTerminal?.snapshot.cols ?? DEFAULT_COLS,
rows = this.activeTerminal?.snapshot.rows ?? DEFAULT_ROWS,
): Promise<TerminalSnapshot> {
this.disposeActiveTerminal();
return this.spawnTerminal(cwd, cols, rows);
}
write(data: string): void {
if (!data) {
return;
}
if (!this.activeTerminal) {
console.warn('[aryx terminal] Ignoring terminal write because no terminal is running.');
return;
}
this.activeTerminal.pty.write(data);
}
resize(cols: number, rows: number): void {
if (!this.activeTerminal) {
console.warn('[aryx terminal] Ignoring terminal resize because no terminal is running.');
return;
}
const nextCols = normalizeDimension(cols, DEFAULT_COLS);
const nextRows = normalizeDimension(rows, DEFAULT_ROWS);
this.activeTerminal.pty.resize(nextCols, nextRows);
this.activeTerminal.snapshot.cols = nextCols;
this.activeTerminal.snapshot.rows = nextRows;
}
kill(): void {
this.activeTerminal?.pty.kill();
}
dispose(): void {
this.disposeActiveTerminal();
}
private async spawnTerminal(cwd: string, cols: number, rows: number): Promise<TerminalSnapshot> {
await assertDirectory(cwd);
const nextCols = normalizeDimension(cols, DEFAULT_COLS);
const nextRows = normalizeDimension(rows, DEFAULT_ROWS);
const shell = await resolveShellCommand(this.platform, this.env, this.commandExists);
const pty = await this.spawnPty(shell.command, shell.args, {
name: DEFAULT_TERMINAL_NAME,
cols: nextCols,
rows: nextRows,
cwd,
env: sanitizeEnvironment(this.env),
});
const snapshot: TerminalSnapshot = {
cwd,
shell: shell.label,
pid: pty.pid,
cols: nextCols,
rows: nextRows,
};
const active: ActiveTerminal = {
pty,
snapshot,
dataSubscription: { dispose() {} },
exitSubscription: { dispose() {} },
};
active.dataSubscription = pty.onData((data) => {
if (this.activeTerminal?.pty !== pty) {
return;
}
this.emit('data', data);
});
active.exitSubscription = pty.onExit((event) => {
if (this.activeTerminal?.pty !== pty) {
return;
}
this.activeTerminal = undefined;
active.dataSubscription.dispose();
active.exitSubscription.dispose();
this.emit('exit', event);
});
this.activeTerminal = active;
return { ...snapshot };
}
private disposeActiveTerminal(): void {
const active = this.activeTerminal;
if (!active) {
return;
}
this.activeTerminal = undefined;
active.dataSubscription.dispose();
active.exitSubscription.dispose();
try {
active.pty.kill();
} catch (error) {
console.warn('[aryx terminal] Failed to stop terminal during cleanup.', error);
}
}
}
async function defaultSpawnPty(
file: string,
args: string[],
options: PtySpawnOptions,
): Promise<ManagedPty> {
const { spawn } = await import('node-pty');
return spawn(file, args, options) as ManagedPty;
}
async function resolveShellCommand(
platform: NodeJS.Platform,
env: NodeJS.ProcessEnv,
commandExists: CommandExists,
): Promise<{ command: string; args: string[]; label: string }> {
if (platform === 'win32') {
const windowsPowerShellPath = resolveWindowsPowerShellPath(env);
const candidates = [
{ command: 'pwsh.exe', args: ['-NoLogo'], label: 'PowerShell' },
{ command: windowsPowerShellPath, args: ['-NoLogo'], label: 'PowerShell' },
...(env.COMSPEC || env.ComSpec
? [{
command: env.COMSPEC ?? env.ComSpec ?? DEFAULT_WINDOWS_FALLBACK_SHELL,
args: [],
label: resolveShellLabel(env.COMSPEC ?? env.ComSpec ?? DEFAULT_WINDOWS_FALLBACK_SHELL),
}]
: []),
{ command: DEFAULT_WINDOWS_FALLBACK_SHELL, args: [], label: 'Command Prompt' },
] satisfies Array<{ command: string; args: string[]; label: string }>;
for (const candidate of candidates) {
if (await commandExists(candidate.command, env, platform)) {
return candidate;
}
}
return candidates[candidates.length - 1]!;
}
const configuredShell = env.SHELL?.trim();
if (configuredShell && await commandExists(configuredShell, env, platform)) {
return { command: configuredShell, args: [], label: resolveShellLabel(configuredShell) };
}
return { command: DEFAULT_UNIX_SHELL, args: [], label: resolveShellLabel(DEFAULT_UNIX_SHELL) };
}
async function commandExistsOnPath(
command: string,
env: NodeJS.ProcessEnv,
platform: NodeJS.Platform,
): Promise<boolean> {
if (isAbsolute(command)) {
return fileExists(command, platform);
}
const searchPath = env.PATH ?? env.Path ?? '';
const pathEntries = searchPath.split(delimiter).filter((entry) => entry.length > 0);
const commandNames = platform === 'win32'
? expandWindowsCommandCandidates(command)
: [command];
for (const entry of pathEntries) {
for (const candidate of commandNames) {
if (await fileExists(join(entry, candidate), platform)) {
return true;
}
}
}
return false;
}
async function fileExists(path: string, platform: NodeJS.Platform): Promise<boolean> {
try {
await access(path, platform === 'win32' ? fsConstants.F_OK : fsConstants.X_OK);
return true;
} catch {
return false;
}
}
function expandWindowsCommandCandidates(command: string): string[] {
if (command.includes('.')) {
return [command];
}
return [
`${command}.exe`,
`${command}.cmd`,
`${command}.bat`,
command,
];
}
function resolveWindowsPowerShellPath(env: NodeJS.ProcessEnv): string {
const systemRoot = env.SystemRoot ?? env.SYSTEMROOT ?? 'C:\\Windows';
return join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
}
function resolveShellLabel(command: string): string {
const baseName = basename(command).replace(/\.(exe|cmd|bat)$/i, '');
if (baseName === 'pwsh' || baseName === 'powershell') {
return 'PowerShell';
}
if (baseName === 'cmd') {
return 'Command Prompt';
}
return baseName;
}
function sanitizeEnvironment(env: NodeJS.ProcessEnv): Record<string, string> {
return Object.fromEntries(
Object.entries({
...env,
TERM: DEFAULT_TERMINAL_NAME,
}).filter((entry): entry is [string, string] => typeof entry[1] === 'string'),
);
}
function normalizeDimension(value: number, fallback: number): number {
if (!Number.isFinite(value)) {
return fallback;
}
const normalized = Math.round(value);
return normalized >= 1 ? normalized : fallback;
}
async function assertDirectory(path: string): Promise<void> {
try {
const entry = await stat(path);
if (!entry.isDirectory()) {
throw new Error(`Terminal working directory "${path}" is not a directory.`);
}
} catch (error) {
if (error instanceof Error) {
throw new Error(`Terminal working directory "${path}" is unavailable.`, { cause: error });
}
throw error;
}
}
+3 -1
View File
@@ -11,6 +11,7 @@ import type {
SessionUsageEvent,
SessionCompactionEvent,
PendingMessagesModifiedEvent,
AssistantUsageEvent,
} from '@shared/contracts/sidecar';
import type { ChatMessageRecord } from '@shared/domain/session';
@@ -20,7 +21,8 @@ export type TurnScopedEvent =
| HookLifecycleEvent
| SessionUsageEvent
| SessionCompactionEvent
| PendingMessagesModifiedEvent;
| PendingMessagesModifiedEvent
| AssistantUsageEvent;
export interface RunTurnPendingCommand {
kind: 'run-turn';
+28
View File
@@ -16,6 +16,7 @@ import type {
RunTurnCommand,
CopilotSessionListFilter,
CopilotSessionInfo,
QuotaSnapshot,
} from '@shared/contracts/sidecar';
import type { ApprovalDecision } from '@shared/domain/approval';
import type { ChatMessageRecord } from '@shared/domain/session';
@@ -80,6 +81,12 @@ type PendingCommand =
resolve: () => void;
reject: (error: Error) => void;
})
| ({
processId: number;
kind: 'get-quota';
resolve: (snapshots: Record<string, QuotaSnapshot>) => void;
reject: (error: Error) => void;
})
| ({
processId: number;
} & RunTurnPendingCommand);
@@ -185,6 +192,13 @@ export class SidecarClient {
});
}
async getQuota(): Promise<Record<string, QuotaSnapshot>> {
return this.dispatch<Record<string, QuotaSnapshot>>({
type: 'get-quota',
requestId: `get-quota-${Date.now()}`,
});
}
async dispose(): Promise<void> {
const state = this.processState;
if (!state) {
@@ -341,6 +355,13 @@ export class SidecarClient {
resolve: resolve as () => void,
reject,
});
} else if (command.type === 'get-quota') {
this.pending.set(command.requestId, {
processId: state.id,
kind: 'get-quota',
resolve: resolve as (snapshots: Record<string, QuotaSnapshot>) => void,
reject,
});
} else {
this.pending.set(command.requestId, {
processId: state.id,
@@ -424,10 +445,17 @@ export class SidecarClient {
case 'session-usage':
case 'session-compaction':
case 'pending-messages-modified':
case 'assistant-usage':
if (pending.kind === 'run-turn' && shouldHandleRunTurnEvent(pending)) {
this.invokeRunTurnHandler(event.requestId, pending, () => pending.onTurnScopedEvent(event));
}
return;
case 'quota-result':
if (pending.kind === 'get-quota') {
pending.resolve(event.quotaSnapshots);
this.pending.delete(event.requestId);
}
return;
case 'sessions-listed':
if (pending.kind === 'list-sessions') {
pending.resolve(event.sessions);
+30
View File
@@ -15,16 +15,31 @@ const api: ElectronApi = {
ipcRenderer.invoke(ipcChannels.resolveWorkspaceDiscoveredTooling, input),
refreshProjectGitContext: (projectId) => ipcRenderer.invoke(ipcChannels.refreshProjectGitContext, projectId),
rescanProjectConfigs: (input) => ipcRenderer.invoke(ipcChannels.rescanProjectConfigs, input),
rescanProjectCustomization: (input) =>
ipcRenderer.invoke(ipcChannels.rescanProjectCustomization, input),
resolveProjectDiscoveredTooling: (input) =>
ipcRenderer.invoke(ipcChannels.resolveProjectDiscoveredTooling, input),
setProjectAgentProfileEnabled: (input) =>
ipcRenderer.invoke(ipcChannels.setProjectAgentProfileEnabled, input),
savePattern: (input) => ipcRenderer.invoke(ipcChannels.savePattern, input),
deletePattern: (patternId) => ipcRenderer.invoke(ipcChannels.deletePattern, patternId),
setPatternFavorite: (input) => ipcRenderer.invoke(ipcChannels.setPatternFavorite, input),
setTheme: (theme) => ipcRenderer.invoke(ipcChannels.setTheme, theme),
setTerminalHeight: (input) => ipcRenderer.invoke(ipcChannels.setTerminalHeight, input),
saveMcpServer: (input) => ipcRenderer.invoke(ipcChannels.saveMcpServer, input),
deleteMcpServer: (serverId) => ipcRenderer.invoke(ipcChannels.deleteMcpServer, serverId),
saveLspProfile: (input) => ipcRenderer.invoke(ipcChannels.saveLspProfile, input),
deleteLspProfile: (profileId) => ipcRenderer.invoke(ipcChannels.deleteLspProfile, profileId),
describeTerminal: () => ipcRenderer.invoke(ipcChannels.describeTerminal),
createTerminal: () => ipcRenderer.invoke(ipcChannels.createTerminal),
restartTerminal: () => ipcRenderer.invoke(ipcChannels.restartTerminal),
killTerminal: () => ipcRenderer.invoke(ipcChannels.killTerminal),
writeTerminal: (data) => {
ipcRenderer.send(ipcChannels.writeTerminal, data);
},
resizeTerminal: (input) => {
ipcRenderer.send(ipcChannels.resizeTerminal, input);
},
updateSessionTooling: (input) => ipcRenderer.invoke(ipcChannels.updateSessionTooling, input),
updateSessionApprovalSettings: (input) =>
ipcRenderer.invoke(ipcChannels.updateSessionApprovalSettings, input),
@@ -50,6 +65,21 @@ const api: ElectronApi = {
selectSession: (sessionId) => ipcRenderer.invoke(ipcChannels.selectSession, sessionId),
openAppDataFolder: () => ipcRenderer.invoke(ipcChannels.openAppDataFolder),
resetLocalWorkspace: () => ipcRenderer.invoke(ipcChannels.resetLocalWorkspace),
getQuota: () => ipcRenderer.invoke(ipcChannels.getQuota),
onTerminalData: (listener) => {
const handler = (_event: Electron.IpcRendererEvent, data: Parameters<typeof listener>[0]) =>
listener(data);
ipcRenderer.on(ipcChannels.terminalData, handler);
return () => ipcRenderer.off(ipcChannels.terminalData, handler);
},
onTerminalExit: (listener) => {
const handler = (_event: Electron.IpcRendererEvent, info: Parameters<typeof listener>[0]) =>
listener(info);
ipcRenderer.on(ipcChannels.terminalExit, handler);
return () => ipcRenderer.off(ipcChannels.terminalExit, handler);
},
onWorkspaceUpdated:(listener) => {
const handler = (_event: Electron.IpcRendererEvent, workspace: Awaited<ReturnType<ElectronApi['loadWorkspace']>>) =>
listener(workspace);
+129 -6
View File
@@ -5,20 +5,26 @@ import { ActivityPanel } from '@renderer/components/ActivityPanel';
import { ChatPane } from '@renderer/components/ChatPane';
import { DiscoveredToolingModal } from '@renderer/components/DiscoveredToolingModal';
import { NewSessionModal } from '@renderer/components/NewSessionModal';
import { ProjectSettingsPanel } from '@renderer/components/ProjectSettingsPanel';
import { SettingsPanel } from '@renderer/components/SettingsPanel';
import { Sidebar } from '@renderer/components/Sidebar';
import { TerminalPanel, DEFAULT_HEIGHT as DEFAULT_TERMINAL_HEIGHT, MIN_HEIGHT as MIN_TERMINAL_HEIGHT } from '@renderer/components/TerminalPanel';
import { resolveChatToolingSettings } from '@renderer/lib/chatTooling';
import {
applySessionEventActivity,
applySessionUsageEvent,
applyAssistantUsageEvent,
applyTurnEventLog,
pruneSessionActivities,
pruneSessionUsage,
pruneSessionRequestUsage,
pruneTurnEventLogs,
type SessionActivityMap,
type SessionUsageMap,
type SessionRequestUsageMap,
type TurnEventLogMap,
} from '@renderer/lib/sessionActivity';
import { applySubagentEvent, pruneSubagentMap, type ActiveSubagentMap } from '@renderer/lib/subagentTracker';
import { applySessionEventWorkspace } from '@renderer/lib/sessionWorkspace';
import { WelcomePane } from '@renderer/components/WelcomePane';
import { getElectronApi } from '@renderer/lib/electronApi';
@@ -98,12 +104,22 @@ export default function App() {
const { capabilities: sidecarCapabilities, isRefreshing: isRefreshingCapabilities, refresh: refreshCapabilities } = useSidecarCapabilities(api);
const [sessionActivities, setSessionActivities] = useState<SessionActivityMap>({});
const [sessionUsage, setSessionUsage] = useState<SessionUsageMap>({});
const [sessionRequestUsage, setSessionRequestUsage] = useState<SessionRequestUsageMap>({});
const [turnEventLogs, setTurnEventLogs] = useState<TurnEventLogMap>({});
const [activeSubagents, setActiveSubagents] = useState<ActiveSubagentMap>({});
const [showSettings, setShowSettings] = useState(false);
const [projectSettingsId, setProjectSettingsId] = useState<string>();
const [newSessionProjectId, setNewSessionProjectId] = useState<string>();
const [showDiscoveryModal, setShowDiscoveryModal] = useState(false);
// Terminal state
const [terminalOpen, setTerminalOpen] = useState(false);
const [terminalHeight, setTerminalHeight] = useState(
() => workspace?.settings.terminalHeight ?? DEFAULT_TERMINAL_HEIGHT,
);
const [terminalRunning, setTerminalRunning] = useState(false);
// Load workspace on mount
useEffect(() => {
let disposed = false;
@@ -128,19 +144,33 @@ export default function App() {
ws.sessions.map((session) => session.id),
),
);
setSessionRequestUsage((current) =>
pruneSessionRequestUsage(
current,
ws.sessions.map((session) => session.id),
),
);
setTurnEventLogs((current) =>
pruneTurnEventLogs(
current,
ws.sessions.map((session) => session.id),
),
);
setActiveSubagents((current) =>
pruneSubagentMap(
current,
ws.sessions.map((session) => session.id),
),
);
});
const offSessionEvent = api.onSessionEvent((event) => {
setWorkspace((current) => applySessionEventWorkspace(current, event));
setSessionActivities((current) => applySessionEventActivity(current, event));
setSessionUsage((current) => applySessionUsageEvent(current, event));
setSessionRequestUsage((current) => applyAssistantUsageEvent(current, event));
setTurnEventLogs((current) => applyTurnEventLog(current, event));
setActiveSubagents((current) => applySubagentEvent(current, event));
});
return () => {
@@ -195,6 +225,14 @@ export default function App() {
() => (selectedSession ? sessionUsage[selectedSession.id] : undefined),
[selectedSession, sessionUsage],
);
const requestUsageForSession = useMemo(
() => (selectedSession ? sessionRequestUsage[selectedSession.id] : undefined),
[selectedSession, sessionRequestUsage],
);
const subagentsForSession = useMemo(
() => (selectedSession ? activeSubagents[selectedSession.id] : undefined),
[selectedSession, activeSubagents],
);
const turnEventsForSession = useMemo(
() => (selectedSession ? turnEventLogs[selectedSession.id] : undefined),
[selectedSession, turnEventLogs],
@@ -226,6 +264,46 @@ export default function App() {
if (hasPendingDiscoveries) setShowDiscoveryModal(true);
}, [hasPendingDiscoveries]);
// Terminal: Ctrl+` toggle + track running state
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.ctrlKey && e.key === '`') {
e.preventDefault();
setTerminalOpen((prev) => !prev);
}
};
window.addEventListener('keydown', handleKeyDown);
// Track terminal running state via exit events
const offExit = api.onTerminalExit(() => setTerminalRunning(false));
return () => {
window.removeEventListener('keydown', handleKeyDown);
offExit();
};
}, [api]);
// Sync terminalHeight from workspace settings when workspace loads
useEffect(() => {
if (workspace?.settings.terminalHeight) {
setTerminalHeight(workspace.settings.terminalHeight);
}
}, [workspace?.settings.terminalHeight]);
const handleTerminalHeightChange = useCallback((newHeight: number) => {
const clamped = Math.max(MIN_TERMINAL_HEIGHT, Math.round(newHeight));
setTerminalHeight(clamped);
void api.setTerminalHeight({ height: clamped });
}, [api]);
const handleTerminalClose = useCallback(() => {
setTerminalOpen(false);
}, []);
const handleTerminalToggle = useCallback(() => {
setTerminalOpen((prev) => !prev);
}, []);
const jumpToMessage = useCallback((messageId: string) => {
const element = document.querySelector(`[data-message-id="${CSS.escape(messageId)}"]`);
if (element) {
@@ -251,6 +329,16 @@ export default function App() {
}
}, [api, workspace]);
const projectForSettings = useMemo(
() => workspace?.projects.find((p) => p.id === projectSettingsId),
[workspace?.projects, projectSettingsId],
);
// Close project settings if the project was removed
useEffect(() => {
if (projectSettingsId && !projectForSettings) setProjectSettingsId(undefined);
}, [projectSettingsId, projectForSettings]);
// Loading state
if (!workspace) {
return (
@@ -321,11 +409,16 @@ export default function App() {
});
}}
availableModels={availableModels}
mcpProbingServerIds={workspace.mcpProbingServerIds}
onTerminalToggle={handleTerminalToggle}
pattern={patternForSession}
project={projectForSession}
runtimeTools={sidecarCapabilities?.runtimeTools}
session={selectedSession}
sessionUsage={usageForSession}
activeSubagents={subagentsForSession}
terminalOpen={terminalOpen}
terminalRunning={terminalRunning}
toolingSettings={chatToolingSettings ?? workspace.settings.tooling}
/>
);
@@ -335,6 +428,7 @@ export default function App() {
onJumpToMessage={jumpToMessage}
pattern={patternForSession}
session={selectedSession}
sessionRequestUsage={requestUsageForSession}
turnEvents={turnEventsForSession}
/>
);
@@ -397,15 +491,10 @@ export default function App() {
theme={workspace.settings.theme}
toolingSettings={workspace.settings.tooling}
discoveredUserTooling={workspace.settings.discoveredUserTooling}
discoveredProjectTooling={selectedProject?.discoveredTooling}
selectedProjectName={selectedProject?.name}
onRescanProjectConfigs={selectedProject ? () => void api.rescanProjectConfigs({ projectId: selectedProject.id }) : undefined}
onResolveUserDiscoveredTooling={(serverIds, resolution) => {
void api.resolveWorkspaceDiscoveredTooling({ serverIds, resolution });
}}
onResolveProjectDiscoveredTooling={selectedProject ? (serverIds, resolution) => {
void api.resolveProjectDiscoveredTooling({ projectId: selectedProject.id, serverIds, resolution });
} : undefined}
onGetQuota={() => api.getQuota()}
/>
) : null;
@@ -415,6 +504,16 @@ export default function App() {
content={content}
detailPanel={detailPanel}
overlay={overlay}
terminalPanel={
terminalOpen ? (
<TerminalPanel
height={terminalHeight}
onHeightChange={handleTerminalHeightChange}
onClose={handleTerminalClose}
onMinimize={handleTerminalClose}
/>
) : undefined
}
sidebar={
<Sidebar
onAddProject={() => void api.addProject()}
@@ -423,6 +522,7 @@ export default function App() {
setNewSessionProjectId(projectId);
}}
onOpenSettings={() => setShowSettings(true)}
onOpenProjectSettings={(projectId) => setProjectSettingsId(projectId)}
onProjectSelect={(projectId) => {
void api.selectProject(projectId);
}}
@@ -484,6 +584,29 @@ export default function App() {
userDiscoveredTooling={workspace.settings.discoveredUserTooling}
/>
)}
{projectForSettings && (
<ProjectSettingsPanel
project={projectForSettings}
onClose={() => setProjectSettingsId(undefined)}
onRescanConfigs={() => {
void api.rescanProjectConfigs({ projectId: projectForSettings.id });
}}
onRescanCustomization={() => {
void api.rescanProjectCustomization({ projectId: projectForSettings.id });
}}
onResolveDiscoveredTooling={(serverIds, resolution) => {
void api.resolveProjectDiscoveredTooling({ projectId: projectForSettings.id, serverIds, resolution });
}}
onSetAgentProfileEnabled={(agentProfileId, enabled) => {
void api.setProjectAgentProfileEnabled({ projectId: projectForSettings.id, agentProfileId, enabled });
}}
onRemoveProject={() => {
void api.removeProject(projectForSettings.id);
setProjectSettingsId(undefined);
}}
/>
)}
</>
);
}
+87 -10
View File
@@ -1,13 +1,18 @@
import { useMemo, type ReactNode } from 'react';
import { Activity, ArrowRight, CheckCircle2, Clock, Cog, ShieldAlert, Sparkles, Users, Zap } from 'lucide-react';
import { Activity, ArrowRight, BarChart3, CheckCircle2, Clock, Cog, ShieldAlert, Sparkles, Users, Zap } from 'lucide-react';
import {
buildAgentActivityRows,
formatAgentActivityLabel,
formatDuration,
formatNanoAiu,
formatTokenCount,
isAgentActivityActive,
isAgentActivityCompleted,
type AgentActivityRow,
type AgentUsageAccumulator,
type SessionActivityState,
type SessionRequestUsageState,
type TurnEventLog,
} from '@renderer/lib/sessionActivity';
import { RunTimeline } from '@renderer/components/RunTimeline';
@@ -70,11 +75,13 @@ function AgentRow({
agent,
accent,
isLast,
agentUsage,
}: {
row: AgentActivityRow;
agent?: PatternAgentDefinition;
accent: (typeof modeAccent)[OrchestrationMode];
isLast: boolean;
agentUsage?: AgentUsageAccumulator;
}) {
const isActive = isAgentActivityActive(row.activity);
const isCompleted = isAgentActivityCompleted(row.activity);
@@ -141,6 +148,27 @@ function AgentRow({
{formatAgentActivityLabel(row.activity)}
</span>
</div>
{/* Per-agent usage summary */}
{agentUsage && agentUsage.requestCount > 0 && (
<div className="mt-0.5 flex items-center gap-1 text-[10px] text-zinc-600">
<span className="tabular-nums">{formatTokenCount(agentUsage.inputTokens)} in</span>
<span className="text-zinc-700">·</span>
<span className="tabular-nums">{formatTokenCount(agentUsage.outputTokens)} out</span>
{agentUsage.cost > 0 && (
<>
<span className="text-zinc-700">·</span>
<span className="tabular-nums">{agentUsage.cost.toFixed(2)} cost</span>
</>
)}
{agentUsage.durationMs > 0 && (
<>
<span className="text-zinc-700">·</span>
<span className="tabular-nums">{formatDuration(agentUsage.durationMs)}</span>
</>
)}
</div>
)}
</div>
</div>
);
@@ -182,6 +210,7 @@ interface ActivityPanelProps {
onJumpToMessage?: (messageId: string) => void;
pattern: PatternDefinition;
session: SessionRecord;
sessionRequestUsage?: SessionRequestUsageState;
turnEvents?: TurnEventLog;
}
@@ -190,6 +219,7 @@ export function ActivityPanel({
onJumpToMessage,
pattern,
session,
sessionRequestUsage,
turnEvents,
}: ActivityPanelProps) {
const activityRows = useMemo(
@@ -241,21 +271,68 @@ export function ActivityPanel({
{activityRows.length > 0 ? (
<div className="rounded-lg border border-zinc-800 bg-zinc-900/40 px-3">
{activityRows.map((row, index) => (
<AgentRow
accent={accent}
agent={pattern.agents[index]}
isLast={index === activityRows.length - 1}
key={row.key}
row={row}
/>
))}
{activityRows.map((row, index) => {
const agentKey = row.activity?.agentId ?? row.key;
const agentUsage = sessionRequestUsage?.perAgent[agentKey]
?? sessionRequestUsage?.perAgent[row.agentName];
return (
<AgentRow
accent={accent}
agent={pattern.agents[index]}
agentUsage={agentUsage}
isLast={index === activityRows.length - 1}
key={row.key}
row={row}
/>
);
})}
</div>
) : (
<p className="py-4 text-center text-[11px] text-zinc-600">No agents configured</p>
)}
</div>
{/* ── Session usage section ──────────────────────────── */}
{sessionRequestUsage && sessionRequestUsage.requestCount > 0 && (
<div className="mb-4">
<SectionHeader>
<BarChart3 className="size-3" />
<span>Session Usage</span>
</SectionHeader>
<div className="rounded-lg border border-zinc-800 bg-zinc-900/40 px-3 py-2.5">
<div className="flex flex-wrap items-center gap-1.5 text-[11px] text-zinc-400">
<span className="font-medium tabular-nums">
{sessionRequestUsage.requestCount} premium request{sessionRequestUsage.requestCount === 1 ? '' : 's'}
</span>
{sessionRequestUsage.totalNanoAiu > 0 && (
<>
<span className="text-zinc-700">·</span>
<span className="tabular-nums">{formatNanoAiu(sessionRequestUsage.totalNanoAiu)} AIU</span>
</>
)}
</div>
<div className="mt-1 flex flex-wrap items-center gap-1.5 text-[10px] text-zinc-500">
<span className="tabular-nums">{formatTokenCount(sessionRequestUsage.totalInputTokens)} in</span>
<span className="text-zinc-700">·</span>
<span className="tabular-nums">{formatTokenCount(sessionRequestUsage.totalOutputTokens)} out</span>
{sessionRequestUsage.totalCost > 0 && (
<>
<span className="text-zinc-700">·</span>
<span className="tabular-nums">{sessionRequestUsage.totalCost.toFixed(2)} cost</span>
</>
)}
{sessionRequestUsage.totalDurationMs > 0 && (
<>
<span className="text-zinc-700">·</span>
<span className="tabular-nums">{formatDuration(sessionRequestUsage.totalDurationMs)} total</span>
</>
)}
</div>
</div>
</div>
)}
{/* ── Run timeline section ─────────────────────────── */}
<div className="mb-4">
<SectionHeader>
+6 -2
View File
@@ -4,10 +4,11 @@ interface AppShellProps {
sidebar: ReactNode;
content: ReactNode;
detailPanel?: ReactNode;
terminalPanel?: ReactNode;
overlay?: ReactNode;
}
export function AppShell({ sidebar, content, detailPanel, overlay }: AppShellProps) {
export function AppShell({ sidebar, content, detailPanel, terminalPanel, overlay }: AppShellProps) {
return (
<div className="relative flex h-screen bg-[var(--color-surface-0)] text-zinc-100">
{/* Full-width drag region matching the title bar overlay height */}
@@ -16,7 +17,10 @@ export function AppShell({ sidebar, content, detailPanel, overlay }: AppShellPro
<aside className="flex w-72 shrink-0 flex-col border-r border-[var(--color-border)] bg-[var(--color-surface-1)]">
{sidebar}
</aside>
<main className="relative min-w-0 flex-1">{content}</main>
<main className="relative flex min-w-0 flex-1 flex-col">
<div className="min-h-0 flex-1">{content}</div>
{terminalPanel}
</main>
{detailPanel && (
<aside className="flex w-64 shrink-0 flex-col border-l border-[var(--color-border)] bg-[var(--color-surface-1)]">
{detailPanel}
+67 -8
View File
@@ -7,14 +7,17 @@ import { ApprovalBanner, QueuedApprovalsList } from '@renderer/components/chat/A
import { PlanReviewBanner } from '@renderer/components/chat/PlanReviewBanner';
import { McpAuthBanner } from '@renderer/components/chat/McpAuthBanner';
import { UserInputBanner } from '@renderer/components/chat/UserInputBanner';
import { InlineApprovalPill, InlineModelPill, InlineThinkingPill, InlineToolsPill } from '@renderer/components/chat/InlinePills';
import { InlineApprovalPill, InlineModelPill, InlineTerminalPill, InlineThinkingPill, InlineToolsPill } from '@renderer/components/chat/InlinePills';
import { InlinePromptPill } from '@renderer/components/chat/InlinePromptPill';
import { ThinkingDots } from '@renderer/components/chat/ThinkingDots';
import { SubagentActivityList } from '@renderer/components/chat/SubagentActivityCard';
import { getAssistantMessagePhase } from '@renderer/lib/messagePhase';
import type { ApprovalDecision } from '@shared/domain/approval';
import type { InteractionMode, MessageMode } from '@shared/contracts/sidecar';
import type { ChatMessageAttachment } from '@shared/domain/attachment';
import { getAttachmentDisplayName, isImageAttachment } from '@shared/domain/attachment';
import type { SessionUsageState } from '@renderer/lib/sessionActivity';
import type { ActiveSubagent } from '@renderer/lib/subagentTracker';
import {
findModel,
getSupportedReasoningEfforts,
@@ -25,6 +28,7 @@ import { type PatternDefinition, type ReasoningEffort } from '@shared/domain/pat
import { isScratchpadProject, type ProjectRecord } from '@shared/domain/project';
import { resolveSessionToolingSelection, type SessionRecord } from '@shared/domain/session';
import {
groupApprovalToolsByProvider,
listApprovalToolDefinitions,
type RuntimeToolDefinition,
type SessionToolingSelection,
@@ -39,8 +43,12 @@ interface ChatPaneProps {
session: SessionRecord;
availableModels: ReadonlyArray<ModelDefinition>;
toolingSettings: WorkspaceToolingSettings;
mcpProbingServerIds?: string[];
runtimeTools?: ReadonlyArray<RuntimeToolDefinition>;
sessionUsage?: SessionUsageState;
activeSubagents?: ReadonlyArray<ActiveSubagent>;
terminalOpen?: boolean;
terminalRunning?: boolean;
onSend: (content: string, attachments?: ChatMessageAttachment[], messageMode?: MessageMode) => Promise<void>;
onCancelTurn?: () => void;
onResolveApproval?: (approvalId: string, decision: ApprovalDecision, alwaysApprove?: boolean) => Promise<unknown>;
@@ -49,6 +57,7 @@ interface ChatPaneProps {
onDismissPlanReview?: () => void;
onDismissMcpAuth?: () => void;
onAuthenticateMcp?: () => void;
onTerminalToggle?: () => void;
onUpdateSessionModelConfig?: (config: {
model: string;
reasoningEffort?: ReasoningEffort;
@@ -63,8 +72,12 @@ export function ChatPane({
session,
availableModels,
toolingSettings,
mcpProbingServerIds,
runtimeTools,
sessionUsage,
activeSubagents,
terminalOpen,
terminalRunning,
onSend,
onCancelTurn,
onResolveApproval,
@@ -73,6 +86,7 @@ export function ChatPane({
onDismissPlanReview,
onDismissMcpAuth,
onAuthenticateMcp,
onTerminalToggle,
onUpdateSessionModelConfig,
onUpdateSessionTooling,
onUpdateSessionApprovalSettings,
@@ -107,6 +121,7 @@ export function ChatPane({
const isComposerDisabled = isUpdatingSessionModelConfig;
const canSubmitInput = hasComposerContent && !isComposerDisabled;
const [pendingAttachments, setPendingAttachments] = useState<ChatMessageAttachment[]>([]);
const promptFiles = useMemo(() => project.customization?.promptFiles ?? [], [project.customization?.promptFiles]);
const toolSelection = useMemo(() => resolveSessionToolingSelection(session), [session]);
const mcpServers = toolingSettings.mcpServers;
@@ -126,10 +141,22 @@ export function ChatPane({
),
[isApprovalOverridden, session.approvalSettings, pattern.approvalPolicy],
);
const effectiveAutoApprovedCount = useMemo(
() => approvalTools.filter((t) => effectiveAutoApproved.has(t.id)).length,
[approvalTools, effectiveAutoApproved],
);
const effectiveAutoApprovedCount = useMemo(() => {
const groups = groupApprovalToolsByProvider(approvalTools, toolingSettings);
const counted = new Set<string>();
for (const group of groups) {
if (group.serverApprovalKey && effectiveAutoApproved.has(group.serverApprovalKey)) {
for (const tool of group.tools) counted.add(tool.id);
} else {
for (const tool of group.tools) {
if (effectiveAutoApproved.has(tool.id)) counted.add(tool.id);
}
}
}
return counted.size;
}, [approvalTools, effectiveAutoApproved, toolingSettings]);
const isProbingMcp = (mcpProbingServerIds?.length ?? 0) > 0;
const hasApprovalContent = approvalTools.length > 0 || isProbingMcp;
useEffect(() => {
transcriptRef.current?.scrollTo({
@@ -386,6 +413,11 @@ export function ChatPane({
);
})}
</div>
{activeSubagents && activeSubagents.length > 0 && (
<div className="px-6 py-1">
<SubagentActivityList subagents={activeSubagents} />
</div>
)}
</div>
)}
</div>
@@ -474,14 +506,16 @@ export function ChatPane({
selection={toolSelection}
/>
)}
{hasToolCallApproval && onUpdateSessionApprovalSettings && approvalTools.length > 0 && (
{hasToolCallApproval && onUpdateSessionApprovalSettings && hasApprovalContent && (
<InlineApprovalPill
approvalTools={approvalTools}
disabled={isComposerDisabled}
effectiveAutoApproved={effectiveAutoApproved}
effectiveAutoApprovedCount={effectiveAutoApprovedCount}
isOverridden={isApprovalOverridden}
mcpProbingServerIds={mcpProbingServerIds}
onUpdate={onUpdateSessionApprovalSettings}
toolingSettings={toolingSettings}
/>
)}
{primaryAgent && (
@@ -529,14 +563,16 @@ export function ChatPane({
selection={toolSelection}
/>
)}
{hasToolCallApproval && onUpdateSessionApprovalSettings && approvalTools.length > 0 && (
{hasToolCallApproval && onUpdateSessionApprovalSettings && hasApprovalContent && (
<InlineApprovalPill
approvalTools={approvalTools}
disabled={isComposerDisabled}
effectiveAutoApproved={effectiveAutoApproved}
effectiveAutoApprovedCount={effectiveAutoApprovedCount}
isOverridden={isApprovalOverridden}
mcpProbingServerIds={mcpProbingServerIds}
onUpdate={onUpdateSessionApprovalSettings}
toolingSettings={toolingSettings}
/>
)}
</div>
@@ -589,7 +625,29 @@ export function ChatPane({
: 'Message...'
}
>
<div className="absolute bottom-2 right-2 flex items-center gap-1">
{/* Bottom action bar: left = shortcuts, right = buttons */}
<div className="flex items-center justify-between px-2 pb-2">
{/* Left: quick actions */}
<div className="flex items-center gap-1.5">
{onTerminalToggle && (
<InlineTerminalPill
disabled={false}
isOpen={!!terminalOpen}
isRunning={!!terminalRunning}
onToggle={onTerminalToggle}
/>
)}
{!isScratchpad && promptFiles.length > 0 && (
<InlinePromptPill
disabled={isComposerDisabled}
onSubmit={(content) => void onSend(content)}
promptFiles={promptFiles}
/>
)}
</div>
{/* Right: attach, plan mode, send */}
<div className="flex items-center gap-1">
{/* Attachment picker */}
<button
aria-label="Attach image"
@@ -678,6 +736,7 @@ export function ChatPane({
<ArrowUp className="size-4" />
)}
</button>
</div>
</div>
</MarkdownComposer>
{isPlanMode && !isSessionBusy && (
+150 -1
View File
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useEffect, useState } from 'react';
import {
CheckCircle2,
XCircle,
@@ -12,12 +12,15 @@ import {
ArrowUpCircle,
User,
Building2,
BarChart3,
Loader2,
} from 'lucide-react';
import type {
SidecarConnectionDiagnostics,
SidecarConnectionStatus,
SidecarCopilotCliVersionStatus,
QuotaSnapshot,
} from '@shared/contracts/sidecar';
interface CopilotStatusCardProps {
@@ -25,6 +28,7 @@ interface CopilotStatusCardProps {
modelCount: number;
isRefreshing: boolean;
onRefresh: () => void;
onGetQuota?: () => Promise<Record<string, QuotaSnapshot>>;
}
interface StatusConfig {
@@ -125,6 +129,137 @@ function VersionBadge({ status, installedVersion }: { status: SidecarCopilotCliV
}
}
const quotaTypeLabels: Record<string, string> = {
premium_interactions: 'Premium Requests',
chat: 'Chat',
completions: 'Completions',
};
function formatQuotaTypeLabel(key: string): string {
return quotaTypeLabels[key] ?? key.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
}
function formatResetDate(iso: string): string {
try {
const date = new Date(iso);
const now = new Date();
const diffMs = date.getTime() - now.getTime();
const diffDays = Math.ceil(diffMs / 86_400_000);
if (diffDays <= 0) return 'Today';
if (diffDays === 1) return 'Tomorrow';
if (diffDays <= 30) return `In ${diffDays} day${diffDays === 1 ? '' : 's'}`;
return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
} catch {
return iso;
}
}
function QuotaSection({
onGetQuota,
}: {
onGetQuota: () => Promise<Record<string, QuotaSnapshot>>;
}) {
const [quotaData, setQuotaData] = useState<Record<string, QuotaSnapshot>>();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>();
useEffect(() => {
let cancelled = false;
setLoading(true);
setError(undefined);
void onGetQuota()
.then((data) => { if (!cancelled) setQuotaData(data); })
.catch((err: unknown) => {
if (!cancelled) setError(err instanceof Error ? err.message : String(err));
})
.finally(() => { if (!cancelled) setLoading(false); });
return () => { cancelled = true; };
}, [onGetQuota]);
if (loading) {
return (
<div className="flex items-center gap-2 py-2">
<Loader2 className="size-3.5 animate-spin text-zinc-500" />
<span className="text-[12px] text-zinc-500">Loading quota</span>
</div>
);
}
if (error) {
return (
<div className="flex items-center gap-2 py-2">
<XCircle className="size-3.5 text-red-400" />
<span className="text-[12px] text-zinc-500">Could not load quota</span>
</div>
);
}
if (!quotaData || Object.keys(quotaData).length === 0) {
return (
<div className="py-2">
<span className="text-[12px] text-zinc-600">No quota data available</span>
</div>
);
}
return (
<div className="space-y-3">
{Object.entries(quotaData).map(([key, snapshot]) => {
const usedPct = snapshot.entitlementRequests > 0
? (snapshot.usedRequests / snapshot.entitlementRequests) * 100
: 0;
const barColor = usedPct > 90
? 'bg-red-500'
: usedPct > 70
? 'bg-amber-500'
: 'bg-indigo-500/60';
return (
<div key={key} className="space-y-1.5">
<div className="flex items-center justify-between">
<span className="text-[12px] font-medium text-zinc-300">
{formatQuotaTypeLabel(key)}
</span>
<span className="text-[11px] tabular-nums text-zinc-500">
{Math.round(snapshot.remainingPercentage)}% remaining
</span>
</div>
<div className="h-1.5 overflow-hidden rounded-full bg-zinc-800">
<div
className={`h-full rounded-full transition-all ${barColor}`}
style={{ width: `${Math.min(100, usedPct)}%` }}
/>
</div>
<div className="flex items-center gap-1.5 text-[10px] text-zinc-500">
<span className="tabular-nums">
{Math.round(snapshot.usedRequests)} of {Math.round(snapshot.entitlementRequests)} used
</span>
{snapshot.overage > 0 && (
<>
<span className="text-zinc-700">·</span>
<span className="tabular-nums text-amber-400">
{Math.round(snapshot.overage)} overage
</span>
</>
)}
{snapshot.resetDate && (
<>
<span className="text-zinc-700">·</span>
<span>Resets {formatResetDate(snapshot.resetDate)}</span>
</>
)}
</div>
</div>
);
})}
</div>
);
}
function AccountSection({ connection }: { connection: SidecarConnectionDiagnostics }) {
const { account } = connection;
if (!account) return null;
@@ -182,6 +317,7 @@ export function CopilotStatusCard({
modelCount,
isRefreshing,
onRefresh,
onGetQuota,
}: CopilotStatusCardProps) {
const [showDetails, setShowDetails] = useState(false);
@@ -242,6 +378,19 @@ export function CopilotStatusCard({
<AccountSection connection={connection} />
)}
{/* Usage & Quota (when healthy and callback provided) */}
{isHealthy && onGetQuota && (
<div className="space-y-2">
<div className="flex items-center gap-1.5 text-[11px] font-medium text-zinc-400">
<BarChart3 className="size-3" />
<span>Usage &amp; Quota</span>
</div>
<div className="rounded-lg border border-zinc-800/60 bg-zinc-900/40 px-3 py-2.5">
<QuotaSection onGetQuota={onGetQuota} />
</div>
</div>
)}
{/* Action hint for non-ready states */}
{!isHealthy && config.actionLabel && (
<div className="flex items-start gap-2 rounded-lg border border-zinc-800 bg-zinc-900/60 px-3 py-2.5">
+5 -55
View File
@@ -24,7 +24,6 @@ import {
$isCodeNode,
$createCodeNode,
$createCodeHighlightNode,
$isCodeHighlightNode,
CodeNode,
CodeHighlightNode,
} from '@lexical/code';
@@ -44,9 +43,7 @@ import {
$getNodeByKey,
$getRoot,
$getSelection,
$isLineBreakNode,
$isRangeSelection,
$isTextNode,
CLEAR_EDITOR_COMMAND,
COMMAND_PRIORITY_HIGH,
FORMAT_TEXT_COMMAND,
@@ -63,6 +60,8 @@ import {
markdownEditorNamespace,
markdownEditorNodes,
markdownEditorTransformers,
getCodeNodeAbsoluteOffset,
restoreCodeNodeSelection,
} from '@renderer/lib/markdownEditor';
import { prepareChatMessageContent } from '@shared/utils/chatMessage';
@@ -295,55 +294,6 @@ function parseHljsHtml(html: string): HljsToken[] {
/* ── Code highlight plugin ────────────────────────────── */
function getAbsoluteOffset(
codeNode: ReturnType<typeof $getNodeByKey>,
point: { key: string; offset: number },
): number {
if (!codeNode || !('getChildren' in codeNode)) return 0;
let offset = 0;
for (const child of (codeNode as CodeNode).getChildren()) {
if (child.getKey() === point.key) return offset + point.offset;
offset += $isLineBreakNode(child) ? 1 : child.getTextContentSize();
}
return offset;
}
function restoreSelectionFromOffsets(codeNode: CodeNode, anchorOff: number, focusOff: number) {
const children = codeNode.getChildren();
function findPoint(target: number) {
let offset = 0;
for (const child of children) {
const size = $isLineBreakNode(child) ? 1 : child.getTextContentSize();
if (offset + size > target || (offset + size === target && $isTextNode(child))) {
return {
key: child.getKey(),
offset: target - offset,
type: ($isTextNode(child) || $isCodeHighlightNode(child) ? 'text' : 'element') as 'text' | 'element',
};
}
offset += size;
}
const last = children[children.length - 1];
if (last) {
return {
key: last.getKey(),
offset: $isLineBreakNode(last) ? 0 : last.getTextContentSize(),
type: ($isTextNode(last) || $isCodeHighlightNode(last) ? 'text' : 'element') as 'text' | 'element',
};
}
return { key: codeNode.getKey(), offset: 0, type: 'element' as const };
}
const anchor = findPoint(anchorOff);
const focus = findPoint(focusOff);
const selection = $getSelection();
if ($isRangeSelection(selection)) {
selection.anchor.set(anchor.key, anchor.offset, anchor.type);
selection.focus.set(focus.key, focus.offset, focus.type);
}
}
/** Enables highlight.js-based syntax highlighting inside CodeNodes. */
function CodeHighlightPlugin() {
const [editor] = useLexicalComposerContext();
@@ -369,8 +319,8 @@ function CodeHighlightPlugin() {
let anchorOff: number | undefined;
let focusOff: number | undefined;
if ($isRangeSelection(sel)) {
anchorOff = getAbsoluteOffset(current, sel.anchor);
focusOff = getAbsoluteOffset(current, sel.focus);
anchorOff = getCodeNodeAbsoluteOffset(current, sel.anchor);
focusOff = getCodeNodeAbsoluteOffset(current, sel.focus);
}
// Build new children from tokens
@@ -392,7 +342,7 @@ function CodeHighlightPlugin() {
// Restore cursor
if (anchorOff !== undefined && focusOff !== undefined) {
restoreSelectionFromOffsets(current, anchorOff, focusOff);
restoreCodeNodeSelection(current, anchorOff, focusOff);
}
});
queueMicrotask(() => highlightingKeys.delete(nodeKey));
@@ -0,0 +1,786 @@
import { useCallback, useMemo, useState, type ReactNode } from 'react';
import { ChevronDown, ChevronLeft, FileCode2, FileText, FolderOpen, GitBranch, RefreshCw, Server, Sparkles, Trash2, AlertTriangle, Circle } from 'lucide-react';
import { ToggleSwitch } from '@renderer/components/ui';
import type { ProjectRecord, ProjectGitContext } from '@shared/domain/project';
import type { DiscoveredMcpServer } from '@shared/domain/discoveredTooling';
import { listAcceptedDiscoveredMcpServers, listPendingDiscoveredMcpServers } from '@shared/domain/discoveredTooling';
import type { ProjectAgentProfile, ProjectInstructionFile, ProjectPromptFile } from '@shared/domain/projectCustomization';
/* ── Types ────────────────────────────────────────────────── */
type ProjectSettingsSection = 'overview' | 'instructions' | 'agents' | 'prompts' | 'mcp-servers' | 'danger-zone';
interface NavItem {
id: ProjectSettingsSection;
label: string;
icon: ReactNode;
}
interface NavGroup {
label: string;
items: NavItem[];
}
interface ProjectSettingsPanelProps {
project: ProjectRecord;
onClose: () => void;
onRescanConfigs: () => void;
onRescanCustomization: () => void;
onResolveDiscoveredTooling: (serverIds: string[], resolution: 'accept' | 'dismiss') => void;
onSetAgentProfileEnabled: (agentProfileId: string, enabled: boolean) => void;
onRemoveProject: () => void;
}
/* ── Main component ───────────────────────────────────────── */
export function ProjectSettingsPanel({
project,
onClose,
onRescanConfigs,
onRescanCustomization,
onResolveDiscoveredTooling,
onSetAgentProfileEnabled,
onRemoveProject,
}: ProjectSettingsPanelProps) {
const [activeSection, setActiveSection] = useState<ProjectSettingsSection>('overview');
const [confirmingRemove, setConfirmingRemove] = useState(false);
const acceptedServers = useMemo(() => listAcceptedDiscoveredMcpServers(project.discoveredTooling), [project.discoveredTooling]);
const pendingServers = useMemo(() => listPendingDiscoveredMcpServers(project.discoveredTooling), [project.discoveredTooling]);
const instructions = project.customization?.instructions ?? [];
const agentProfiles = project.customization?.agentProfiles ?? [];
const promptFiles = project.customization?.promptFiles ?? [];
const enabledAgentCount = agentProfiles.filter((a) => a.enabled).length;
const handleRemove = useCallback(() => {
if (!confirmingRemove) {
setConfirmingRemove(true);
return;
}
onRemoveProject();
}, [confirmingRemove, onRemoveProject]);
const navGroups: NavGroup[] = [
{
label: 'Project',
items: [
{ id: 'overview', label: 'Overview', icon: <FolderOpen className="size-3.5" /> },
],
},
{
label: 'Copilot',
items: [
{ id: 'instructions', label: 'Instructions', icon: <FileCode2 className="size-3.5" /> },
{ id: 'agents', label: 'Custom Agents', icon: <Sparkles className="size-3.5" /> },
{ id: 'prompts', label: 'Prompt Files', icon: <FileText className="size-3.5" /> },
],
},
{
label: 'Tooling',
items: [
{ id: 'mcp-servers', label: 'MCP Servers', icon: <Server className="size-3.5" /> },
],
},
];
function sectionBadge(section: ProjectSettingsSection): ReactNode {
switch (section) {
case 'instructions':
return instructions.length > 0
? <CountBadge count={instructions.length} />
: null;
case 'agents':
return agentProfiles.length > 0
? <CountBadge count={enabledAgentCount} total={agentProfiles.length} />
: null;
case 'prompts':
return promptFiles.length > 0
? <CountBadge count={promptFiles.length} />
: null;
case 'mcp-servers': {
if (pendingServers.length > 0) {
return <PendingBadge count={pendingServers.length} />;
}
const totalServers = acceptedServers.length + pendingServers.length;
return totalServers > 0 ? <CountBadge count={totalServers} /> : null;
}
default:
return null;
}
}
return (
<div className="fixed inset-0 z-50 flex flex-col bg-[var(--color-surface-0)]">
{/* Header */}
<div className="drag-region flex items-center gap-3 border-b border-[var(--color-border)] px-5 pb-3 pt-3">
<button
className="no-drag flex size-8 items-center justify-center rounded-lg text-zinc-400 transition hover:bg-zinc-800 hover:text-zinc-200"
onClick={onClose}
type="button"
>
<ChevronLeft className="size-4" />
</button>
<h2 className="text-[13px] font-semibold text-zinc-100">
Project Settings
<span className="ml-2 font-normal text-zinc-500">·</span>
<span className="ml-2 font-normal text-zinc-400">{project.name}</span>
</h2>
</div>
{/* Sidebar + Content */}
<div className="flex min-h-0 flex-1">
{/* Navigation sidebar */}
<nav className="w-52 shrink-0 border-r border-[var(--color-border)] bg-[var(--color-surface-1)] p-3">
<div className="space-y-4">
{navGroups.map((group) => (
<div key={group.label}>
<span className="mb-1 block px-3 text-[10px] font-semibold uppercase tracking-wider text-zinc-600">
{group.label}
</span>
<div className="space-y-0.5">
{group.items.map((item) => {
const isActive = item.id === activeSection;
const badge = sectionBadge(item.id);
return (
<button
className={`flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-left text-[13px] transition ${
isActive
? 'bg-zinc-800 font-medium text-zinc-100'
: 'text-zinc-400 hover:bg-zinc-800/50 hover:text-zinc-300'
}`}
key={item.id}
onClick={() => {
setActiveSection(item.id);
setConfirmingRemove(false);
}}
type="button"
>
<span className={isActive ? 'text-zinc-300' : 'text-zinc-500'}>{item.icon}</span>
<span className="flex-1 truncate">{item.label}</span>
{badge}
</button>
);
})}
</div>
</div>
))}
{/* Danger zone at the bottom */}
<div className="border-t border-zinc-800 pt-3">
<div className="space-y-0.5">
<button
className={`flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-left text-[13px] transition ${
activeSection === 'danger-zone'
? 'bg-zinc-800 font-medium text-red-400'
: 'text-zinc-500 hover:bg-zinc-800/50 hover:text-red-400'
}`}
onClick={() => {
setActiveSection('danger-zone');
setConfirmingRemove(false);
}}
type="button"
>
<Trash2 className="size-3.5" />
<span className="flex-1 truncate">Danger Zone</span>
</button>
</div>
</div>
</div>
</nav>
{/* Content panel */}
<div className="flex-1 overflow-y-auto">
<div className="mx-auto max-w-2xl px-8 py-6">
{activeSection === 'overview' && (
<OverviewContent project={project} />
)}
{activeSection === 'instructions' && (
<InstructionsContent
instructions={instructions}
onRescan={onRescanCustomization}
/>
)}
{activeSection === 'agents' && (
<AgentsContent
agents={agentProfiles}
onRescan={onRescanCustomization}
onSetEnabled={onSetAgentProfileEnabled}
/>
)}
{activeSection === 'prompts' && (
<PromptsContent
onRescan={onRescanCustomization}
promptFiles={promptFiles}
/>
)}
{activeSection === 'mcp-servers' && (
<McpServersContent
accepted={acceptedServers}
onRescan={onRescanConfigs}
onResolve={onResolveDiscoveredTooling}
pending={pendingServers}
/>
)}
{activeSection === 'danger-zone' && (
<DangerZoneContent
confirmingRemove={confirmingRemove}
onCancelRemove={() => setConfirmingRemove(false)}
onRemove={handleRemove}
/>
)}
</div>
</div>
</div>
</div>
);
}
/* ── Nav badges ───────────────────────────────────────────── */
function CountBadge({ count, total }: { count: number; total?: number }) {
return (
<span className="rounded-full bg-zinc-800 px-1.5 py-0.5 text-[10px] font-medium text-zinc-500">
{total !== undefined ? `${count}/${total}` : count}
</span>
);
}
function PendingBadge({ count }: { count: number }) {
return (
<span className="rounded-full bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-medium text-amber-400">
{count} new
</span>
);
}
/* ── Overview ─────────────────────────────────────────────── */
function OverviewContent({ project }: { project: ProjectRecord }) {
return (
<div>
<SectionHeader
description="Project details and git status."
title="Overview"
/>
<div className="rounded-xl border border-zinc-800 bg-zinc-900/40 px-5 py-4 space-y-3">
<div className="flex items-center gap-3">
<FolderOpen className="size-5 shrink-0 text-indigo-400" />
<div className="min-w-0">
<div className="text-[13px] font-medium text-zinc-200">{project.name}</div>
<div className="mt-0.5 truncate text-[12px] text-zinc-500">{project.path}</div>
</div>
</div>
{project.git && <ProjectGitInfo git={project.git} />}
</div>
</div>
);
}
function ProjectGitInfo({ git }: { git: ProjectGitContext }) {
if (git.status === 'not-repository') {
return (
<div className="flex items-center gap-2 text-[12px] text-zinc-600">
<GitBranch className="size-3.5" />
Not a git repository
</div>
);
}
if (git.status === 'git-missing') {
return (
<div className="flex items-center gap-2 text-[12px] text-amber-500/70">
<AlertTriangle className="size-3.5" />
Git is not installed
</div>
);
}
if (git.status === 'error') {
return (
<div className="flex items-center gap-2 text-[12px] text-red-400/70">
<AlertTriangle className="size-3.5" />
{git.errorMessage ?? 'Git error'}
</div>
);
}
const branchLabel = git.branch ?? git.head?.shortHash ?? 'HEAD';
const parts: string[] = [];
if (git.isDirty && git.changedFileCount) parts.push(`${git.changedFileCount} changed`);
if (git.ahead) parts.push(`${git.ahead} ahead`);
if (git.behind) parts.push(`${git.behind} behind`);
return (
<div className="flex items-center gap-2 text-[12px] text-zinc-400">
<GitBranch className="size-3.5 shrink-0" />
<span>{branchLabel}</span>
{git.isDirty && <Circle className="size-1.5 shrink-0 fill-amber-500 text-amber-500" />}
{parts.length > 0 && (
<span className="text-zinc-600">· {parts.join(' · ')}</span>
)}
</div>
);
}
/* ── Instructions ─────────────────────────────────────────── */
function InstructionsContent({
instructions,
onRescan,
}: {
instructions: ProjectInstructionFile[];
onRescan: () => void;
}) {
return (
<div>
<SectionHeader
description="Repository instructions automatically included in every session. Discovered from .github/copilot-instructions.md and AGENTS.md."
title="Instructions"
>
<RescanButton onClick={onRescan} />
</SectionHeader>
{instructions.length === 0 ? (
<EmptyState>
No instruction files found. Add a <code className="text-zinc-400">.github/copilot-instructions.md</code> or <code className="text-zinc-400">AGENTS.md</code> file to your project root.
</EmptyState>
) : (
<div className="space-y-3">
{instructions.map((instruction) => (
<InstructionCard key={instruction.id} instruction={instruction} />
))}
</div>
)}
</div>
);
}
function InstructionCard({ instruction }: { instruction: ProjectInstructionFile }) {
const [expanded, setExpanded] = useState(false);
const isLong = instruction.content.length > 300;
return (
<div className="rounded-xl border border-zinc-800 bg-zinc-900/40">
<button
className="flex w-full items-center gap-3 px-5 py-3.5 text-left transition hover:bg-zinc-900/60"
onClick={() => setExpanded(!expanded)}
type="button"
>
<FileCode2 className="size-4 shrink-0 text-indigo-400" />
<span className="flex-1 text-[13px] font-medium text-zinc-200">{instruction.sourcePath}</span>
<ChevronDown
className={`size-3.5 shrink-0 text-zinc-500 transition-transform ${expanded ? 'rotate-180' : ''}`}
/>
</button>
{expanded && (
<div className="border-t border-zinc-800 px-5 py-4">
<pre className="whitespace-pre-wrap text-[11px] leading-relaxed text-zinc-400">
{instruction.content}
</pre>
</div>
)}
{!expanded && (
<div className="px-5 pb-3">
<p className={`text-[11px] leading-relaxed text-zinc-500 ${isLong ? 'line-clamp-2' : ''}`}>
{instruction.content}
</p>
</div>
)}
</div>
);
}
/* ── Custom Agents ────────────────────────────────────────── */
function AgentsContent({
agents,
onRescan,
onSetEnabled,
}: {
agents: ProjectAgentProfile[];
onRescan: () => void;
onSetEnabled: (agentProfileId: string, enabled: boolean) => void;
}) {
const enabledCount = agents.filter((a) => a.enabled).length;
return (
<div>
<SectionHeader
description="Custom agent profiles discovered from .github/agents/*.agent.md. Enable or disable individual agents."
title="Custom Agents"
>
<RescanButton onClick={onRescan} />
</SectionHeader>
{agents.length === 0 ? (
<EmptyState>
No custom agents found. Add <code className="text-zinc-400">.agent.md</code> files to <code className="text-zinc-400">.github/agents/</code> in your project.
</EmptyState>
) : (
<>
{agents.length > 1 && (
<div className="mb-3 text-[11px] text-zinc-500">
{enabledCount} of {agents.length} agent{agents.length === 1 ? '' : 's'} enabled
</div>
)}
<div className="space-y-2">
{agents.map((agent) => (
<AgentCard
key={agent.id}
agent={agent}
onToggle={() => onSetEnabled(agent.id, !agent.enabled)}
/>
))}
</div>
</>
)}
</div>
);
}
function AgentCard({
agent,
onToggle,
}: {
agent: ProjectAgentProfile;
onToggle: () => void;
}) {
return (
<div className={`rounded-xl border px-5 py-4 transition ${
agent.enabled
? 'border-zinc-800 bg-zinc-900/40'
: 'border-zinc-800/50 bg-zinc-900/20 opacity-60'
}`}>
<div className="flex items-start gap-3">
<Sparkles className={`mt-0.5 size-4 shrink-0 ${agent.enabled ? 'text-amber-400' : 'text-zinc-600'}`} />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="text-[13px] font-medium text-zinc-200">
{agent.displayName ?? agent.name}
</span>
{agent.tools && agent.tools.length > 0 && (
<span className="rounded-full bg-zinc-800 px-2 py-0.5 text-[10px] font-medium text-zinc-500">
{agent.tools.length} tool{agent.tools.length === 1 ? '' : 's'}
</span>
)}
</div>
{agent.description && (
<p className="mt-1 text-[12px] leading-relaxed text-zinc-500">{agent.description}</p>
)}
<p className="mt-1 text-[11px] text-zinc-600">{agent.sourcePath}</p>
</div>
<button
aria-label={agent.enabled ? `Disable ${agent.name}` : `Enable ${agent.name}`}
aria-pressed={agent.enabled}
className="mt-0.5 shrink-0"
onClick={onToggle}
type="button"
>
<ToggleSwitch enabled={agent.enabled} size="sm" />
</button>
</div>
</div>
);
}
/* ── Prompt Files ─────────────────────────────────────────── */
function PromptsContent({
promptFiles,
onRescan,
}: {
promptFiles: ProjectPromptFile[];
onRescan: () => void;
}) {
return (
<div>
<SectionHeader
description="Reusable prompt templates discovered from .github/prompts/*.prompt.md. Use them from the Prompts pill in the chat input."
title="Prompt Files"
>
<RescanButton onClick={onRescan} />
</SectionHeader>
{promptFiles.length === 0 ? (
<EmptyState>
No prompt files found. Add <code className="text-zinc-400">.prompt.md</code> files to <code className="text-zinc-400">.github/prompts/</code> in your project.
</EmptyState>
) : (
<div className="space-y-2">
{promptFiles.map((prompt) => (
<PromptCard key={prompt.id} prompt={prompt} />
))}
</div>
)}
</div>
);
}
function PromptCard({ prompt }: { prompt: ProjectPromptFile }) {
return (
<div className="rounded-xl border border-zinc-800 bg-zinc-900/40 px-5 py-4">
<div className="flex items-start gap-3">
<FileText className="mt-0.5 size-4 shrink-0 text-emerald-400" />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="text-[13px] font-medium text-zinc-200">{prompt.name}</span>
{prompt.variables.length > 0 && (
<span className="rounded-full bg-zinc-800 px-2 py-0.5 text-[10px] font-medium text-zinc-500">
{prompt.variables.length} variable{prompt.variables.length === 1 ? '' : 's'}
</span>
)}
</div>
{prompt.description && (
<p className="mt-1 text-[12px] leading-relaxed text-zinc-500">{prompt.description}</p>
)}
{prompt.variables.length > 0 && (
<div className="mt-2 flex flex-wrap gap-1.5">
{prompt.variables.map((v) => (
<span
key={v.name}
className="rounded-md bg-zinc-800 px-2 py-0.5 text-[10px] font-medium text-zinc-400"
title={v.placeholder}
>
{v.name}
</span>
))}
</div>
)}
<p className="mt-1.5 text-[11px] text-zinc-600">{prompt.sourcePath}</p>
</div>
</div>
</div>
);
}
/* ── MCP Servers ──────────────────────────────────────────── */
function McpServersContent({
accepted,
pending,
onRescan,
onResolve,
}: {
accepted: DiscoveredMcpServer[];
pending: DiscoveredMcpServer[];
onRescan: () => void;
onResolve: (serverIds: string[], resolution: 'accept' | 'dismiss') => void;
}) {
const hasServers = accepted.length + pending.length > 0;
return (
<div>
<SectionHeader
description="MCP servers discovered from project config files (.vscode/mcp.json, .mcp.json, .copilot/mcp.json)."
title="MCP Servers"
>
<RescanButton label={hasServers ? 'Re-scan' : 'Scan'} onClick={onRescan} />
</SectionHeader>
{!hasServers ? (
<EmptyState>
No MCP servers discovered. Click Scan to check project config files.
</EmptyState>
) : (
<>
<div className="space-y-1">
{accepted.map((server) => (
<DiscoveredServerRow
key={server.id}
onDismiss={() => onResolve([server.id], 'dismiss')}
server={server}
status="accepted"
/>
))}
{pending.map((server) => (
<DiscoveredServerRow
key={server.id}
onAccept={() => onResolve([server.id], 'accept')}
onDismiss={() => onResolve([server.id], 'dismiss')}
server={server}
status="pending"
/>
))}
</div>
{pending.length > 1 && (
<div className="mt-3 flex items-center gap-2">
<button
className="rounded-lg bg-emerald-500/10 px-3 py-1.5 text-[12px] font-medium text-emerald-400 transition hover:bg-emerald-500/20"
onClick={() => onResolve(pending.map((s) => s.id), 'accept')}
type="button"
>
Accept all ({pending.length})
</button>
<button
className="rounded-lg px-3 py-1.5 text-[12px] font-medium text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300"
onClick={() => onResolve(pending.map((s) => s.id), 'dismiss')}
type="button"
>
Dismiss all
</button>
</div>
)}
</>
)}
</div>
);
}
function DiscoveredServerRow({
server,
status,
onAccept,
onDismiss,
}: {
server: DiscoveredMcpServer;
status: 'accepted' | 'pending';
onAccept?: () => void;
onDismiss?: () => void;
}) {
const detail =
server.transport === 'local'
? server.command || 'No command'
: server.url || 'No URL';
const statusBadge = status === 'accepted'
? 'bg-emerald-500/10 text-emerald-400'
: 'bg-amber-500/10 text-amber-400';
return (
<div className="flex items-center gap-3 rounded-xl border border-transparent px-4 py-3 hover:border-zinc-800 hover:bg-zinc-900">
<Server className="size-4 shrink-0 text-zinc-600" />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate text-[13px] font-medium text-zinc-200">{server.name}</span>
<span className="rounded-full bg-zinc-800 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-zinc-400">
{server.transport}
</span>
<span className={`rounded-full px-2 py-0.5 text-[10px] font-medium ${statusBadge}`}>
{status}
</span>
</div>
<p className="mt-0.5 truncate text-[12px] text-zinc-500">
{detail}
<span className="ml-2 text-zinc-700">· {server.sourceLabel}</span>
</p>
</div>
<div className="flex items-center gap-1">
{onAccept && (
<button
className="rounded-lg px-2.5 py-1 text-[12px] font-medium text-emerald-400 transition hover:bg-emerald-500/10"
onClick={onAccept}
type="button"
>
Accept
</button>
)}
{onDismiss && (
<button
className="rounded-lg px-2.5 py-1 text-[12px] font-medium text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300"
onClick={onDismiss}
type="button"
>
{status === 'accepted' ? 'Remove' : 'Dismiss'}
</button>
)}
</div>
</div>
);
}
/* ── Danger Zone ──────────────────────────────────────────── */
function DangerZoneContent({
confirmingRemove,
onRemove,
onCancelRemove,
}: {
confirmingRemove: boolean;
onRemove: () => void;
onCancelRemove: () => void;
}) {
return (
<div>
<SectionHeader
description="Irreversible actions for this project."
title="Danger Zone"
/>
<div className="rounded-xl border border-red-500/20 bg-red-500/5 px-5 py-5">
<h4 className="text-[13px] font-semibold text-zinc-200">Remove project</h4>
<p className="mt-1 text-[12px] text-zinc-500">
Removing a project deletes all its sessions and discovered tooling from Aryx.
Your project files on disk are not affected.
</p>
<div className="mt-4 flex items-center gap-3">
<button
className={`flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] font-medium transition ${
confirmingRemove
? 'bg-red-600 text-white hover:bg-red-500'
: 'bg-red-500/10 text-red-400 hover:bg-red-500/20'
}`}
onClick={onRemove}
type="button"
>
<Trash2 className="size-3.5" />
{confirmingRemove ? 'Confirm removal' : 'Remove project'}
</button>
{confirmingRemove && (
<button
className="rounded-lg px-3 py-1.5 text-[13px] font-medium text-zinc-400 transition hover:bg-zinc-800 hover:text-zinc-200"
onClick={onCancelRemove}
type="button"
>
Cancel
</button>
)}
</div>
</div>
</div>
);
}
/* ── Shared helpers ──────────────────────────────────────── */
function SectionHeader({
title,
description,
children,
}: {
title: string;
description: string;
children?: ReactNode;
}) {
return (
<div className="mb-4 flex items-center justify-between gap-3">
<div>
<h3 className="text-[13px] font-semibold text-zinc-200">{title}</h3>
<p className="mt-0.5 text-[12px] text-zinc-500">{description}</p>
</div>
{children}
</div>
);
}
function RescanButton({ onClick, label = 'Re-scan' }: { onClick: () => void; label?: string }) {
return (
<button
className="flex items-center gap-1.5 rounded-lg bg-zinc-800 px-3 py-1.5 text-[13px] font-medium text-zinc-200 transition hover:bg-zinc-700"
onClick={onClick}
title={label === 'Scan' ? 'Scan for files' : 'Re-scan for changes'}
type="button"
>
<RefreshCw className="size-3.5" />
{label}
</button>
);
}
function EmptyState({ children }: { children: ReactNode }) {
return (
<div className="rounded-xl border border-dashed border-zinc-800 bg-zinc-900/20 px-5 py-8 text-center text-[12px] leading-relaxed text-zinc-500">
{children}
</div>
);
}
+19 -61
View File
@@ -1,12 +1,12 @@
import { useState, type ReactNode } from 'react';
import { ChevronLeft, ChevronRight, Code, Cpu, FolderOpen, Palette, Plus, RefreshCw, Server, TriangleAlert, Workflow, Wrench } from 'lucide-react';
import { ChevronLeft, ChevronRight, Code, Cpu, FolderOpen, Palette, Plus, Server, TriangleAlert, Workflow, Wrench } from 'lucide-react';
import { CopilotStatusCard } from '@renderer/components/CopilotStatusCard';
import { PatternEditor } from '@renderer/components/PatternEditor';
import { LspProfileEditor } from '@renderer/components/settings/LspProfileEditor';
import { McpServerEditor } from '@renderer/components/settings/McpServerEditor';
import type { SidecarCapabilities } from '@shared/contracts/sidecar';
import type { DiscoveredMcpServer, DiscoveredToolingState, ProjectDiscoveredTooling } from '@shared/domain/discoveredTooling';
import type { SidecarCapabilities, QuotaSnapshot } from '@shared/contracts/sidecar';
import type { DiscoveredMcpServer, DiscoveredToolingState } from '@shared/domain/discoveredTooling';
import { listAcceptedDiscoveredMcpServers, listPendingDiscoveredMcpServers } from '@shared/domain/discoveredTooling';
import type { ModelDefinition } from '@shared/domain/models';
import type { PatternDefinition } from '@shared/domain/pattern';
@@ -26,8 +26,6 @@ interface SettingsPanelProps {
theme: AppearanceTheme;
toolingSettings: WorkspaceToolingSettings;
discoveredUserTooling: DiscoveredToolingState;
discoveredProjectTooling?: ProjectDiscoveredTooling;
selectedProjectName?: string;
isRefreshingCapabilities: boolean;
onRefreshCapabilities: () => void;
onClose: () => void;
@@ -43,9 +41,8 @@ interface SettingsPanelProps {
onSetTheme: (theme: AppearanceTheme) => void;
onOpenAppDataFolder: () => void;
onResetLocalWorkspace: () => Promise<void>;
onRescanProjectConfigs?: () => void;
onResolveUserDiscoveredTooling?: (serverIds: string[], resolution: 'accept' | 'dismiss') => void;
onResolveProjectDiscoveredTooling?: (serverIds: string[], resolution: 'accept' | 'dismiss') => void;
onGetQuota?: () => Promise<Record<string, QuotaSnapshot>>;
}
type SettingsSection = 'appearance' | 'connection' | 'patterns' | 'mcp-servers' | 'lsp-profiles' | 'troubleshooting';
@@ -107,8 +104,6 @@ export function SettingsPanel({
theme,
toolingSettings,
discoveredUserTooling,
discoveredProjectTooling,
selectedProjectName,
isRefreshingCapabilities,
onRefreshCapabilities,
onClose,
@@ -124,9 +119,8 @@ export function SettingsPanel({
onSetTheme,
onOpenAppDataFolder,
onResetLocalWorkspace,
onRescanProjectConfigs,
onResolveUserDiscoveredTooling,
onResolveProjectDiscoveredTooling,
onGetQuota,
}: SettingsPanelProps) {
const [activeSection, setActiveSection] = useState<SettingsSection>('appearance');
const [editingPattern, setEditingPattern] = useState<PatternDefinition | null>(null);
@@ -269,6 +263,7 @@ export function SettingsPanel({
isRefreshing={isRefreshingCapabilities}
modelCount={sidecarCapabilities?.models.length ?? 0}
onRefresh={onRefreshCapabilities}
onGetQuota={onGetQuota}
/>
)}
{activeSection === 'patterns' && (
@@ -287,12 +282,8 @@ export function SettingsPanel({
)}
{activeSection === 'mcp-servers' && (
<DiscoveredMcpSection
discoveredProjectTooling={discoveredProjectTooling}
discoveredUserTooling={discoveredUserTooling}
onRescanProjectConfigs={onRescanProjectConfigs}
onResolveProjectDiscoveredTooling={onResolveProjectDiscoveredTooling}
onResolveUserDiscoveredTooling={onResolveUserDiscoveredTooling}
selectedProjectName={selectedProjectName}
/>
)}
{activeSection === 'lsp-profiles' && (
@@ -377,11 +368,13 @@ function ConnectionSection({
modelCount,
isRefreshing,
onRefresh,
onGetQuota,
}: {
connection?: SidecarCapabilities['connection'];
modelCount: number;
isRefreshing: boolean;
onRefresh: () => void;
onGetQuota?: () => Promise<Record<string, QuotaSnapshot>>;
}) {
return (
<div>
@@ -396,6 +389,7 @@ function ConnectionSection({
connection={connection}
isRefreshing={isRefreshing}
modelCount={modelCount}
onGetQuota={onGetQuota}
onRefresh={onRefresh}
/>
</div>
@@ -607,68 +601,32 @@ function EmptyState({ children }: { children: ReactNode }) {
function DiscoveredMcpSection({
discoveredUserTooling,
discoveredProjectTooling,
selectedProjectName,
onRescanProjectConfigs,
onResolveUserDiscoveredTooling,
onResolveProjectDiscoveredTooling,
}: {
discoveredUserTooling: DiscoveredToolingState;
discoveredProjectTooling?: ProjectDiscoveredTooling;
selectedProjectName?: string;
onRescanProjectConfigs?: () => void;
onResolveUserDiscoveredTooling?: (serverIds: string[], resolution: 'accept' | 'dismiss') => void;
onResolveProjectDiscoveredTooling?: (serverIds: string[], resolution: 'accept' | 'dismiss') => void;
}) {
const acceptedUser = listAcceptedDiscoveredMcpServers(discoveredUserTooling);
const pendingUser = listPendingDiscoveredMcpServers(discoveredUserTooling);
const acceptedProject = listAcceptedDiscoveredMcpServers(discoveredProjectTooling);
const pendingProject = listPendingDiscoveredMcpServers(discoveredProjectTooling);
const hasAny = acceptedUser.length + pendingUser.length + acceptedProject.length + pendingProject.length > 0;
const hasAny = acceptedUser.length + pendingUser.length > 0;
if (!hasAny) return null;
return (
<div className="mt-8">
<SectionHeader
description="MCP servers discovered from project and user config files. Accepted servers are available for session tooling."
description="MCP servers discovered from user config files. Accepted servers are available for session tooling."
title="Discovered MCP Servers"
>
{onRescanProjectConfigs && (
<button
className="flex items-center gap-1.5 rounded-lg bg-zinc-800 px-3 py-1.5 text-[13px] font-medium text-zinc-200 transition hover:bg-zinc-700"
onClick={onRescanProjectConfigs}
title="Re-scan project config files"
type="button"
>
<RefreshCw className="size-3.5" />
Re-scan
</button>
)}
</SectionHeader>
/>
{/* User-level discovered */}
{(acceptedUser.length > 0 || pendingUser.length > 0) && (
<DiscoveredSubSection
label="User-level"
description="From ~/.copilot/mcp.json"
accepted={acceptedUser}
pending={pendingUser}
onResolve={onResolveUserDiscoveredTooling}
/>
)}
{/* Project-level discovered */}
{(acceptedProject.length > 0 || pendingProject.length > 0) && (
<DiscoveredSubSection
label={selectedProjectName ? `Project: ${selectedProjectName}` : 'Project-level'}
description="From .vscode/mcp.json, .mcp.json, or .copilot/mcp.json"
accepted={acceptedProject}
pending={pendingProject}
onResolve={onResolveProjectDiscoveredTooling}
/>
)}
<DiscoveredSubSection
label="User-level"
description="From ~/.copilot/mcp.json"
accepted={acceptedUser}
pending={pendingUser}
onResolve={onResolveUserDiscoveredTooling}
/>
</div>
);
}
+25 -2
View File
@@ -42,6 +42,7 @@ interface SidebarProps {
onProjectSelect: (projectId?: string) => void;
onSessionSelect: (sessionId: string) => void;
onOpenSettings: () => void;
onOpenProjectSettings: (projectId: string) => void;
onRenameSession: (sessionId: string, title: string) => void;
onDuplicateSession: (sessionId: string) => void;
onSetSessionPinned: (sessionId: string, isPinned: boolean) => void;
@@ -328,6 +329,7 @@ function ProjectGroup({
onRenameSubmit,
onRenameCancel,
onRefreshGitContext,
onOpenProjectSettings,
onNewSession,
newSessionLabel,
}: {
@@ -341,6 +343,7 @@ function ProjectGroup({
onRenameSubmit: (sessionId: string, title: string) => void;
onRenameCancel: () => void;
onRefreshGitContext?: (projectId: string) => void;
onOpenProjectSettings?: (projectId: string) => void;
onNewSession?: () => void;
newSessionLabel?: string;
}){
@@ -394,6 +397,19 @@ function ProjectGroup({
)}
<div className="ml-auto flex items-center gap-1.5">
{!isScratchpad && onOpenProjectSettings && (
<span
className="flex size-5 items-center justify-center rounded text-zinc-600 opacity-0 transition hover:bg-zinc-700 hover:text-zinc-300 group-hover:opacity-100"
onClick={(e) => {
e.stopPropagation();
onOpenProjectSettings(project.id);
}}
role="button"
title="Project settings"
>
<Settings className="size-3" />
</span>
)}
{!isScratchpad && onRefreshGitContext && (
<span
className="flex size-5 items-center justify-center rounded text-zinc-600 opacity-0 transition hover:bg-zinc-700 hover:text-zinc-300 group-hover:opacity-100"
@@ -415,8 +431,13 @@ function ProjectGroup({
)}
{pendingDiscoveryCount > 0 && (
<span
className="flex items-center gap-1 rounded-full bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-medium text-amber-400"
title={`${pendingDiscoveryCount} MCP server${pendingDiscoveryCount === 1 ? '' : 's'} discovered`}
className="flex cursor-pointer items-center gap-1 rounded-full bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-medium text-amber-400 transition hover:bg-amber-500/20"
onClick={(e) => {
e.stopPropagation();
onOpenProjectSettings?.(project.id);
}}
role="button"
title={`${pendingDiscoveryCount} MCP server${pendingDiscoveryCount === 1 ? '' : 's'} discovered — click to review`}
>
{pendingDiscoveryCount} new
</span>
@@ -475,6 +496,7 @@ export function Sidebar({
onProjectSelect,
onSessionSelect,
onOpenSettings,
onOpenProjectSettings,
onRenameSession,
onDuplicateSession,
onSetSessionPinned,
@@ -678,6 +700,7 @@ export function Sidebar({
onRenameSubmit={handleRenameSubmit}
onRenameCancel={() => setRenamingSessionId(undefined)}
onRefreshGitContext={onRefreshGitContext}
onOpenProjectSettings={onOpenProjectSettings}
renamingSessionId={renamingSessionId}
patterns={workspace.patterns}
project={project}
+284
View File
@@ -0,0 +1,284 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { RotateCcw, Minus, X } from 'lucide-react';
import { Terminal } from '@xterm/xterm';
import { FitAddon } from '@xterm/addon-fit';
import '@xterm/xterm/css/xterm.css';
import { getElectronApi } from '@renderer/lib/electronApi';
import type { TerminalSnapshot } from '@shared/domain/terminal';
import type { TerminalExitInfo } from '@shared/domain/terminal';
/* ── Theme ────────────────────────────────────────────────── */
const terminalTheme = {
background: '#09090b', // zinc-950
foreground: '#e4e4e7', // zinc-200
cursor: '#818cf8', // indigo-400
cursorAccent: '#09090b',
selectionBackground: '#6366f14d', // indigo-500/30
selectionForeground: '#e4e4e7',
black: '#27272a', // zinc-800
red: '#f87171', // red-400
green: '#4ade80', // green-400
yellow: '#facc15', // yellow-400
blue: '#60a5fa', // blue-400
magenta: '#c084fc', // purple-400
cyan: '#22d3ee', // cyan-400
white: '#e4e4e7', // zinc-200
brightBlack: '#52525b', // zinc-600
brightRed: '#fca5a5', // red-300
brightGreen: '#86efac', // green-300
brightYellow: '#fde047', // yellow-300
brightBlue: '#93c5fd', // blue-300
brightMagenta: '#d8b4fe',// purple-300
brightCyan: '#67e8f9', // cyan-300
brightWhite: '#fafafa', // zinc-50
};
/* ── Constants ────────────────────────────────────────────── */
const MIN_HEIGHT = 120;
const MAX_HEIGHT_FRACTION = 0.7;
const DEFAULT_HEIGHT = 280;
/* ── TerminalPanel ────────────────────────────────────────── */
interface TerminalPanelProps {
height: number;
onHeightChange: (height: number) => void;
onClose: () => void;
onMinimize: () => void;
}
export function TerminalPanel({
height,
onHeightChange,
onClose,
onMinimize,
}: TerminalPanelProps) {
const api = getElectronApi();
const containerRef = useRef<HTMLDivElement>(null);
const terminalRef = useRef<Terminal | null>(null);
const fitAddonRef = useRef<FitAddon | null>(null);
const [snapshot, setSnapshot] = useState<TerminalSnapshot>();
const [isRunning, setIsRunning] = useState(false);
const [isDragging, setIsDragging] = useState(false);
const dragStartRef = useRef<{ y: number; height: number } | null>(null);
// Create or recover terminal on mount
useEffect(() => {
let disposed = false;
void api.describeTerminal().then((existing) => {
if (disposed) return;
if (existing) {
setSnapshot(existing);
setIsRunning(true);
} else {
void api.createTerminal().then((created) => {
if (disposed) return;
setSnapshot(created);
setIsRunning(true);
});
}
});
return () => {
disposed = true;
};
}, [api]);
// Initialize xterm.js
useEffect(() => {
if (!containerRef.current) return;
const terminal = new Terminal({
theme: terminalTheme,
fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',
fontSize: 13,
lineHeight: 1.4,
cursorBlink: true,
cursorStyle: 'bar',
scrollback: 5000,
allowProposedApi: true,
});
const fitAddon = new FitAddon();
terminal.loadAddon(fitAddon);
terminal.open(containerRef.current);
terminalRef.current = terminal;
fitAddonRef.current = fitAddon;
// Send keystrokes to the backend
const dataDisposable = terminal.onData((data) => {
api.writeTerminal(data);
});
// Initial fit
requestAnimationFrame(() => {
fitAddon.fit();
api.resizeTerminal({ cols: terminal.cols, rows: terminal.rows });
});
return () => {
dataDisposable.dispose();
terminal.dispose();
terminalRef.current = null;
fitAddonRef.current = null;
};
}, [api]);
// Subscribe to terminal data and exit events
useEffect(() => {
const offData = api.onTerminalData((data) => {
terminalRef.current?.write(data);
});
const offExit = api.onTerminalExit((_info: TerminalExitInfo) => {
setIsRunning(false);
terminalRef.current?.write('\r\n\x1b[90m[Process exited]\x1b[0m\r\n');
});
return () => {
offData();
offExit();
};
}, [api]);
// Refit on height changes
useEffect(() => {
if (!fitAddonRef.current || !terminalRef.current) return;
requestAnimationFrame(() => {
fitAddonRef.current?.fit();
const terminal = terminalRef.current;
if (terminal) {
api.resizeTerminal({ cols: terminal.cols, rows: terminal.rows });
}
});
}, [height, api]);
// ResizeObserver for container width changes
useEffect(() => {
const container = containerRef.current;
if (!container) return;
const observer = new ResizeObserver(() => {
requestAnimationFrame(() => {
fitAddonRef.current?.fit();
const terminal = terminalRef.current;
if (terminal) {
api.resizeTerminal({ cols: terminal.cols, rows: terminal.rows });
}
});
});
observer.observe(container);
return () => observer.disconnect();
}, [api]);
// Drag-to-resize
const handleDragStart = useCallback((e: React.MouseEvent) => {
e.preventDefault();
dragStartRef.current = { y: e.clientY, height };
setIsDragging(true);
const handleDragMove = (moveEvent: MouseEvent) => {
if (!dragStartRef.current) return;
const maxHeight = window.innerHeight * MAX_HEIGHT_FRACTION;
const delta = dragStartRef.current.y - moveEvent.clientY;
const nextHeight = Math.max(MIN_HEIGHT, Math.min(maxHeight, dragStartRef.current.height + delta));
onHeightChange(nextHeight);
};
const handleDragEnd = () => {
setIsDragging(false);
dragStartRef.current = null;
document.removeEventListener('mousemove', handleDragMove);
document.removeEventListener('mouseup', handleDragEnd);
};
document.addEventListener('mousemove', handleDragMove);
document.addEventListener('mouseup', handleDragEnd);
}, [height, onHeightChange]);
const handleRestart = useCallback(() => {
void api.restartTerminal().then((restarted) => {
setSnapshot(restarted);
setIsRunning(true);
terminalRef.current?.clear();
});
}, [api]);
const handleClose = useCallback(() => {
void api.killTerminal();
onClose();
}, [api, onClose]);
return (
<div
className="flex flex-col border-t border-[var(--color-border)] bg-[#09090b]"
style={{ height, minHeight: MIN_HEIGHT }}
>
{/* Resize handle */}
<div
className={`h-1 shrink-0 cursor-row-resize transition-colors ${isDragging ? 'bg-indigo-500/40' : 'hover:bg-zinc-700/60'}`}
onMouseDown={handleDragStart}
role="separator"
aria-orientation="horizontal"
aria-label="Resize terminal"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === 'ArrowUp') {
e.preventDefault();
onHeightChange(Math.min(window.innerHeight * MAX_HEIGHT_FRACTION, height + 20));
} else if (e.key === 'ArrowDown') {
e.preventDefault();
onHeightChange(Math.max(MIN_HEIGHT, height - 20));
}
}}
/>
{/* Header bar */}
<div className="flex h-7 shrink-0 items-center gap-2 border-b border-zinc-800/60 px-3">
<span className={`size-1.5 shrink-0 rounded-full ${isRunning ? 'bg-emerald-400' : 'bg-zinc-600'}`} />
<span className="min-w-0 flex-1 truncate text-[11px] text-zinc-500">
{snapshot ? `${snapshot.shell}${snapshot.cwd}` : 'Terminal'}
</span>
<div className="flex items-center gap-0.5">
<button
aria-label="Restart terminal"
className="rounded p-0.5 text-zinc-600 transition hover:bg-zinc-800 hover:text-zinc-400"
onClick={handleRestart}
type="button"
>
<RotateCcw className="size-3" />
</button>
<button
aria-label="Minimize terminal"
className="rounded p-0.5 text-zinc-600 transition hover:bg-zinc-800 hover:text-zinc-400"
onClick={onMinimize}
type="button"
>
<Minus className="size-3" />
</button>
<button
aria-label="Close terminal"
className="rounded p-0.5 text-zinc-600 transition hover:bg-zinc-800 hover:text-red-400"
onClick={handleClose}
type="button"
>
<X className="size-3" />
</button>
</div>
</div>
{/* Terminal body */}
<div
className="min-h-0 flex-1 px-1 py-0.5"
ref={containerRef}
role="application"
aria-label="Terminal"
/>
</div>
);
}
export { DEFAULT_HEIGHT, MIN_HEIGHT };
+298 -55
View File
@@ -1,10 +1,11 @@
import { useState } from 'react';
import { ChevronDown, Sparkles } from 'lucide-react';
import { useMemo, useState } from 'react';
import { ChevronDown, ChevronRight, Loader2, Minus, Search, Sparkles, TerminalSquare } from 'lucide-react';
import { ProviderIcon } from '@renderer/components/ProviderIcons';
import { PopoverToggleRow } from '@renderer/components/ui';
import { useClickOutside } from '@renderer/hooks/useClickOutside';
import type { ApprovalToolDefinition, ApprovalToolKind, LspProfileDefinition, McpServerDefinition, SessionToolingSelection } from '@shared/domain/tooling';
import type { ApprovalToolDefinition, LspProfileDefinition, McpServerDefinition, SessionToolingSelection, WorkspaceToolingSettings } from '@shared/domain/tooling';
import { groupApprovalToolsByProvider, type ApprovalToolGroup } from '@shared/domain/tooling';
import { findModel, inferProvider, providerMeta, type ModelDefinition } from '@shared/domain/models';
import { reasoningEffortOptions, type ReasoningEffort } from '@shared/domain/pattern';
import { RotateCcw, Server, ShieldCheck } from 'lucide-react';
@@ -337,31 +338,64 @@ function McpServerGroup({
/* ── InlineApprovalPill ────────────────────────────────────── */
const approvalKindOrder: ApprovalToolKind[] = ['builtin', 'mcp', 'lsp', 'mixed'];
const approvalKindLabels: Record<ApprovalToolKind, string> = {
builtin: 'Built-in',
mcp: 'MCP Servers',
lsp: 'Language Servers',
mixed: 'Other',
};
const SEARCH_THRESHOLD = 10;
export function InlineApprovalPill({
approvalTools,
toolingSettings,
effectiveAutoApproved,
effectiveAutoApprovedCount,
isOverridden,
disabled,
mcpProbingServerIds,
onUpdate,
}: {
approvalTools: ApprovalToolDefinition[];
toolingSettings: WorkspaceToolingSettings;
effectiveAutoApproved: Set<string>;
effectiveAutoApprovedCount: number;
isOverridden: boolean;
disabled: boolean;
mcpProbingServerIds?: string[];
onUpdate: (settings: { autoApprovedToolNames?: string[] }) => void;
}){
const [open, setOpen] = useState(false);
const ref = useClickOutside<HTMLDivElement>(() => setOpen(false), open);
const [search, setSearch] = useState('');
const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());
const ref = useClickOutside<HTMLDivElement>(() => { setOpen(false); setSearch(''); }, open);
const probingSet = useMemo(
() => new Set(mcpProbingServerIds ?? []),
[mcpProbingServerIds],
);
const isProbingAny = probingSet.size > 0;
const groups = useMemo(
() => groupApprovalToolsByProvider(approvalTools, toolingSettings),
[approvalTools, toolingSettings],
);
const totalItemCount = groups.reduce(
(sum, g) => sum + Math.max(g.tools.length, g.serverApprovalKey ? 1 : 0),
0,
);
const showSearch = totalItemCount > SEARCH_THRESHOLD;
const searchLower = search.toLowerCase().trim();
const filteredGroups = useMemo(() => {
if (!searchLower) return groups;
return groups
.map((group) => ({
...group,
tools: group.tools.filter(
(t) =>
t.label.toLowerCase().includes(searchLower)
|| t.id.toLowerCase().includes(searchLower)
|| group.label.toLowerCase().includes(searchLower),
),
}))
.filter((g) => g.tools.length > 0 || g.label.toLowerCase().includes(searchLower));
}, [groups, searchLower]);
function toggleTool(toolId: string) {
const next = new Set(effectiveAutoApproved);
@@ -373,10 +407,68 @@ export function InlineApprovalPill({
onUpdate({ autoApprovedToolNames: [...next] });
}
const groups = approvalKindOrder
.map((kind) => ({ kind, tools: approvalTools.filter((t) => t.kind === kind) }))
.filter((g) => g.tools.length > 0);
const showHeaders = groups.length > 1;
function toggleGroup(group: ApprovalToolGroup) {
const next = new Set(effectiveAutoApproved);
if (group.serverApprovalKey) {
// MCP servers use server-level approval key
if (next.has(group.serverApprovalKey)) {
next.delete(group.serverApprovalKey);
} else {
next.add(group.serverApprovalKey);
}
// Also remove individual tool entries when toggling server-level
for (const tool of group.tools) {
next.delete(tool.id);
}
} else {
// Non-MCP groups: toggle individual tools
const allApproved = group.tools.every((t) => next.has(t.id));
for (const tool of group.tools) {
if (allApproved) {
next.delete(tool.id);
} else {
next.add(tool.id);
}
}
}
onUpdate({ autoApprovedToolNames: [...next] });
}
function isGroupApproved(group: ApprovalToolGroup): 'all' | 'some' | 'none' {
if (group.serverApprovalKey && effectiveAutoApproved.has(group.serverApprovalKey)) {
return 'all';
}
if (group.tools.length === 0) return 'none';
const approvedCount = group.tools.filter((t) => effectiveAutoApproved.has(t.id)).length;
if (approvedCount === group.tools.length) return 'all';
if (approvedCount > 0) return 'some';
return 'none';
}
function isGroupProbing(group: ApprovalToolGroup): boolean {
if (group.kind !== 'mcp') return false;
const serverId = group.id.replace(/^mcp:/, '');
return probingSet.has(serverId);
}
function toggleExpanded(groupId: string) {
setExpandedGroups((prev) => {
const next = new Set(prev);
if (next.has(groupId)) {
next.delete(groupId);
} else {
next.add(groupId);
}
return next;
});
}
function isGroupExpanded(groupId: string): boolean {
if (searchLower) return true;
return expandedGroups.has(groupId);
}
return (
<div className="relative" ref={ref}>
@@ -394,58 +486,209 @@ export function InlineApprovalPill({
onClick={() => setOpen(!open)}
type="button"
>
<ShieldCheck className="size-2.5" />
<span>{effectiveAutoApprovedCount}/{approvalTools.length} auto-approved</span>
{isProbingAny ? (
<Loader2 className="size-2.5 animate-spin" aria-label="Probing MCP servers" />
) : (
<ShieldCheck className="size-2.5" />
)}
<span>
{effectiveAutoApprovedCount}/{totalItemCount} auto-approved
{isProbingAny && <span className="text-zinc-500"> · probing</span>}
</span>
<ChevronDown className={`size-2.5 transition ${open ? 'rotate-180' : ''}`} />
</button>
{open && !disabled && (
<div className="absolute bottom-full left-0 z-40 mb-1.5 max-h-80 w-72 overflow-y-auto rounded-lg border border-zinc-700 bg-zinc-900 shadow-2xl">
<div className="flex items-center gap-2 border-b border-zinc-800 px-3 py-2">
<span className={`rounded-full px-2 py-0.5 text-[9px] font-semibold uppercase tracking-wider ${
isOverridden
? 'bg-amber-500/15 text-amber-400'
: 'bg-zinc-800 text-zinc-500'
}`}>
{isOverridden ? 'Session override' : 'Pattern defaults'}
</span>
{isOverridden && (
<button
className="flex items-center gap-1 rounded-full px-2 py-0.5 text-[9px] font-medium text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300"
onClick={() => onUpdate({})}
type="button"
>
<RotateCcw className="size-2.5" />
Reset
</button>
<div className="absolute bottom-full left-0 z-40 mb-1.5 max-h-[28rem] w-80 overflow-y-auto rounded-lg border border-zinc-700 bg-zinc-900 shadow-2xl">
{/* Header: session override / pattern defaults */}
<div className="sticky top-0 z-10 border-b border-zinc-800 bg-zinc-900">
<div className="flex items-center gap-2 px-3 py-2">
<span className={`rounded-full px-2 py-0.5 text-[9px] font-semibold uppercase tracking-wider ${
isOverridden
? 'bg-amber-500/15 text-amber-400'
: 'bg-zinc-800 text-zinc-500'
}`}>
{isOverridden ? 'Session override' : 'Pattern defaults'}
</span>
{isOverridden && (
<button
className="flex items-center gap-1 rounded-full px-2 py-0.5 text-[9px] font-medium text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300"
onClick={() => onUpdate({})}
type="button"
>
<RotateCcw className="size-2.5" />
Reset
</button>
)}
</div>
{/* Search */}
{showSearch && (
<div className="border-t border-zinc-800/50 px-3 py-1.5">
<div className="flex items-center gap-2 rounded border border-zinc-800 bg-zinc-800/30 px-2 py-1">
<Search className="size-3 shrink-0 text-zinc-600" />
<input
autoFocus
className="w-full bg-transparent text-[12px] text-zinc-300 placeholder-zinc-600 outline-none"
onChange={(e) => setSearch(e.target.value)}
placeholder="Filter tools…"
type="text"
value={search}
/>
</div>
</div>
)}
</div>
{/* Tool groups */}
<div className="py-1">
{groups.map((group, i) => (
<div key={group.kind}>
{showHeaders && (
<div className={`px-3 pb-1 ${i > 0 ? 'pt-2' : 'pt-1'} text-[9px] font-semibold uppercase tracking-wider text-zinc-600`}>
{approvalKindLabels[group.kind]}
</div>
)}
{group.tools.map((tool) => {
const detail = tool.description || (tool.providerNames.length > 0 ? tool.providerNames.join(', ') : undefined);
return (
<PopoverToggleRow
detail={detail}
enabled={effectiveAutoApproved.has(tool.id)}
key={tool.id}
label={tool.label}
onToggle={() => toggleTool(tool.id)}
/>
);
})}
{filteredGroups.map((group, groupIdx) => {
const isBuiltin = group.kind === 'builtin';
const isCollapsible = !isBuiltin;
const expanded = isBuiltin || isGroupExpanded(group.id);
const probing = isGroupProbing(group);
const groupState = isGroupApproved(group);
const allApproved = groupState === 'all';
const someApproved = groupState === 'some';
const approvedLabel = group.serverApprovalKey && allApproved
? 'all'
: `${group.tools.filter((t) => effectiveAutoApproved.has(t.id)).length}/${group.tools.length}`;
return (
<div key={group.id}>
{/* Group header */}
{isBuiltin ? (
<div className={`px-3 pb-1 ${groupIdx > 0 ? 'pt-2.5' : 'pt-1'} text-[9px] font-semibold uppercase tracking-wider text-zinc-600`}>
{group.label}
</div>
) : (
<div
className={`flex w-full cursor-pointer items-center gap-1.5 px-2.5 py-1.5 text-left transition hover:bg-zinc-800/60 ${groupIdx > 0 ? 'mt-0.5' : ''}`}
onClick={() => toggleExpanded(group.id)}
onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggleExpanded(group.id); } }}
role="button"
tabIndex={0}
>
{probing ? (
<Loader2 className="size-3 shrink-0 animate-spin text-indigo-400" aria-label="Probing server" />
) : group.tools.length > 0 ? (
<ChevronRight className={`size-3 shrink-0 text-zinc-600 transition ${expanded ? 'rotate-90' : ''}`} />
) : (
<Server className="size-3 shrink-0 text-zinc-600" />
)}
<span className="min-w-0 flex-1 truncate text-[12px] font-medium text-zinc-300">{group.label}</span>
{probing ? (
<span className="shrink-0 rounded-full bg-indigo-500/10 px-1.5 py-px text-[9px] font-medium text-indigo-400">
probing
</span>
) : (
<span className="shrink-0 rounded-full bg-zinc-800/80 px-1.5 py-px text-[9px] font-medium tabular-nums text-zinc-500">
{approvedLabel}
</span>
)}
{!probing && (
<GroupToggle
allApproved={allApproved}
someApproved={someApproved}
onToggle={(e) => { e.stopPropagation(); toggleGroup(group); }}
/>
)}
</div>
)}
{/* Group tools */}
{expanded && group.tools.map((tool) => {
const detail = tool.description || (
!isBuiltin && tool.providerNames.length > 1
? tool.providerNames.join(', ')
: undefined
);
return (
<div key={tool.id} className={isCollapsible ? 'pl-3' : ''}>
<PopoverToggleRow
detail={detail}
enabled={effectiveAutoApproved.has(tool.id)}
label={tool.label}
onToggle={() => toggleTool(tool.id)}
/>
</div>
);
})}
</div>
);
})}
{filteredGroups.length === 0 && searchLower && (
<div className="px-3 py-4 text-center text-[12px] text-zinc-600">
No tools match "{search}"
</div>
))}
)}
</div>
</div>
)}
</div>
);
}
function GroupToggle({
allApproved,
someApproved,
onToggle,
}: {
allApproved: boolean;
someApproved: boolean;
onToggle: (e: React.MouseEvent) => void;
}) {
return (
<button
aria-pressed={allApproved}
className={`relative inline-flex h-[16px] w-[28px] shrink-0 items-center rounded-full transition-colors ${
allApproved ? 'bg-indigo-500' : someApproved ? 'bg-zinc-600' : 'bg-zinc-700'
}`}
onClick={onToggle}
type="button"
>
{someApproved ? (
<Minus className="absolute left-1/2 size-2 -translate-x-1/2 text-zinc-300" strokeWidth={3} />
) : (
<span
className={`inline-block size-[12px] rounded-full bg-white shadow transition-transform ${
allApproved ? 'translate-x-[13px]' : 'translate-x-[2px]'
}`}
/>
)}
</button>
);
}
/* ── InlineTerminalPill ────────────────────────────────────── */
export function InlineTerminalPill({
disabled,
isRunning,
isOpen,
onToggle,
}: {
disabled: boolean;
isRunning: boolean;
isOpen: boolean;
onToggle: () => void;
}) {
return (
<button
aria-pressed={isOpen}
className={`inline-flex items-center gap-1 rounded-lg px-2 py-1 text-[11px] font-medium transition ${
isOpen
? 'bg-indigo-500/15 text-indigo-300 hover:bg-indigo-500/20'
: 'text-zinc-500 hover:bg-zinc-800 hover:text-zinc-300'
} disabled:cursor-not-allowed disabled:opacity-50`}
disabled={disabled}
onClick={onToggle}
type="button"
>
{isRunning && <span className="size-1.5 shrink-0 rounded-full bg-emerald-400" />}
<TerminalSquare className="size-3" />
<span>Terminal</span>
</button>
);
}
@@ -0,0 +1,253 @@
import { useCallback, useMemo, useState } from 'react';
import { ArrowUp, FileText, X } from 'lucide-react';
import { useClickOutside } from '@renderer/hooks/useClickOutside';
import type { ProjectPromptFile, ProjectPromptVariable } from '@shared/domain/projectCustomization';
const promptVariablePattern = /\$\{input:([a-zA-Z0-9_-]+):[^}]+\}/g;
function resolvePromptTemplate(template: string, values: Record<string, string>): string {
return template.replace(promptVariablePattern, (_match, name: string) => {
return values[name] ?? '';
});
}
export function InlinePromptPill({
promptFiles,
disabled,
onSubmit,
}: {
promptFiles: ReadonlyArray<ProjectPromptFile>;
disabled: boolean;
onSubmit: (resolvedContent: string) => void;
}) {
const [open, setOpen] = useState(false);
const [selectedPrompt, setSelectedPrompt] = useState<ProjectPromptFile | null>(null);
const [variableValues, setVariableValues] = useState<Record<string, string>>({});
const ref = useClickOutside<HTMLDivElement>(() => handleClose(), open);
const handleClose = useCallback(() => {
setOpen(false);
setSelectedPrompt(null);
setVariableValues({});
}, []);
const handleSelectPrompt = useCallback((prompt: ProjectPromptFile) => {
if (prompt.variables.length === 0) {
onSubmit(prompt.template.trim());
handleClose();
} else {
setSelectedPrompt(prompt);
setVariableValues({});
}
}, [onSubmit, handleClose]);
const handleSubmitWithVariables = useCallback(() => {
if (!selectedPrompt) return;
const resolved = resolvePromptTemplate(selectedPrompt.template, variableValues).trim();
if (!resolved) return;
onSubmit(resolved);
handleClose();
}, [selectedPrompt, variableValues, onSubmit, handleClose]);
const handleVariableChange = useCallback((name: string, value: string) => {
setVariableValues((prev) => ({ ...prev, [name]: value }));
}, []);
const allVariablesFilled = useMemo(() => {
if (!selectedPrompt) return false;
return selectedPrompt.variables.every((v) => (variableValues[v.name] ?? '').trim().length > 0);
}, [selectedPrompt, variableValues]);
if (promptFiles.length === 0) return null;
return (
<div className="relative" ref={ref}>
<button
aria-expanded={open}
aria-haspopup="listbox"
className="inline-flex items-center gap-1 rounded-lg px-2 py-1 text-[11px] font-medium text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300"
disabled={disabled}
onClick={() => setOpen(!open)}
type="button"
>
<FileText className="size-3" />
Prompts
<span className="text-zinc-600">({promptFiles.length})</span>
</button>
{open && !disabled && (
<div
className="absolute bottom-full left-0 z-40 mb-1.5 w-80 rounded-lg border border-zinc-700 bg-zinc-900 shadow-xl"
role="listbox"
>
{selectedPrompt ? (
<PromptVariableForm
onBack={() => {
setSelectedPrompt(null);
setVariableValues({});
}}
onSubmit={handleSubmitWithVariables}
onVariableChange={handleVariableChange}
prompt={selectedPrompt}
submitDisabled={!allVariablesFilled}
values={variableValues}
/>
) : (
<PromptList
onSelect={handleSelectPrompt}
promptFiles={promptFiles}
/>
)}
</div>
)}
</div>
);
}
function PromptList({
promptFiles,
onSelect,
}: {
promptFiles: ReadonlyArray<ProjectPromptFile>;
onSelect: (prompt: ProjectPromptFile) => void;
}) {
return (
<div className="max-h-64 overflow-y-auto py-1">
<div className="px-3 py-2 text-[10px] font-semibold uppercase tracking-wider text-zinc-500">
Prompt files
</div>
{promptFiles.map((prompt) => (
<button
key={prompt.id}
className="flex w-full items-start gap-2.5 px-3 py-2 text-left transition hover:bg-zinc-800"
onClick={() => onSelect(prompt)}
role="option"
type="button"
>
<FileText className="mt-0.5 size-3.5 shrink-0 text-zinc-500" />
<div className="min-w-0 flex-1">
<div className="truncate text-[12px] font-medium text-zinc-200">
{prompt.name}
</div>
{prompt.description && (
<div className="mt-0.5 truncate text-[11px] text-zinc-500">
{prompt.description}
</div>
)}
{prompt.variables.length > 0 && (
<div className="mt-1 flex flex-wrap gap-1">
{prompt.variables.map((v) => (
<span
key={v.name}
className="rounded bg-zinc-800 px-1.5 py-0.5 text-[10px] text-zinc-500"
>
{v.name}
</span>
))}
</div>
)}
</div>
</button>
))}
</div>
);
}
function PromptVariableForm({
prompt,
values,
submitDisabled,
onVariableChange,
onSubmit,
onBack,
}: {
prompt: ProjectPromptFile;
values: Record<string, string>;
submitDisabled: boolean;
onVariableChange: (name: string, value: string) => void;
onSubmit: () => void;
onBack: () => void;
}) {
return (
<div className="p-3">
<div className="mb-3 flex items-center gap-2">
<button
className="flex size-5 items-center justify-center rounded text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300"
onClick={onBack}
type="button"
aria-label="Back to prompt list"
>
<X className="size-3" />
</button>
<div className="min-w-0 flex-1">
<div className="truncate text-[12px] font-medium text-zinc-200">
{prompt.name}
</div>
{prompt.description && (
<div className="truncate text-[10px] text-zinc-500">{prompt.description}</div>
)}
</div>
</div>
<div className="space-y-2.5">
{prompt.variables.map((variable) => (
<PromptVariableInput
key={variable.name}
onChange={(value) => onVariableChange(variable.name, value)}
onSubmit={!submitDisabled ? onSubmit : undefined}
value={values[variable.name] ?? ''}
variable={variable}
/>
))}
</div>
<button
className={`mt-3 flex w-full items-center justify-center gap-1.5 rounded-lg px-3 py-2 text-[12px] font-medium transition ${
submitDisabled
? 'bg-zinc-800 text-zinc-600'
: 'bg-indigo-600 text-white hover:bg-indigo-500'
}`}
disabled={submitDisabled}
onClick={onSubmit}
type="button"
>
<ArrowUp className="size-3.5" />
Send prompt
</button>
</div>
);
}
function PromptVariableInput({
variable,
value,
onChange,
onSubmit,
}: {
variable: ProjectPromptVariable;
value: string;
onChange: (value: string) => void;
onSubmit?: () => void;
}) {
return (
<div>
<label className="mb-1 block text-[11px] font-medium text-zinc-400">
{variable.name}
</label>
<input
className="w-full rounded-lg border border-zinc-700 bg-zinc-800 px-2.5 py-1.5 text-[12px] text-zinc-200 placeholder-zinc-600 transition focus:border-indigo-500/50 focus:outline-none"
onChange={(e) => onChange(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && onSubmit) {
e.preventDefault();
onSubmit();
}
}}
placeholder={variable.placeholder}
type="text"
value={value}
/>
</div>
);
}
@@ -0,0 +1,89 @@
import { useEffect, useState } from 'react';
import { Bot, CheckCircle2, Loader2, XCircle } from 'lucide-react';
import type { ActiveSubagent } from '@renderer/lib/subagentTracker';
function formatElapsed(startedAt: string): string {
const seconds = Math.floor((Date.now() - new Date(startedAt).getTime()) / 1000);
if (seconds < 60) return `${seconds}s`;
const minutes = Math.floor(seconds / 60);
const remainder = seconds % 60;
return `${minutes}m ${remainder}s`;
}
function StatusIcon({ status }: { status: ActiveSubagent['status'] }) {
switch (status) {
case 'running':
return <Loader2 className="size-3.5 animate-spin text-sky-400" aria-label="Running" />;
case 'completed':
return <CheckCircle2 className="size-3.5 text-emerald-400" aria-label="Completed" />;
case 'failed':
return <XCircle className="size-3.5 text-red-400" aria-label="Failed" />;
}
}
function ElapsedTimer({ startedAt }: { startedAt: string }) {
const [elapsed, setElapsed] = useState(() => formatElapsed(startedAt));
useEffect(() => {
const id = setInterval(() => setElapsed(formatElapsed(startedAt)), 1000);
return () => clearInterval(id);
}, [startedAt]);
return (
<span className="ml-auto shrink-0 text-[10px] tabular-nums text-zinc-600">{elapsed}</span>
);
}
interface SubagentActivityCardProps {
subagent: ActiveSubagent;
}
function SubagentActivityCard({ subagent }: SubagentActivityCardProps) {
const borderClass =
subagent.status === 'running'
? 'border-sky-500/20'
: subagent.status === 'failed'
? 'border-red-500/20'
: 'border-emerald-500/20';
return (
<div
className={`flex items-center gap-2 rounded-lg border bg-zinc-900/60 px-3 py-1.5 ${borderClass}`}
role="status"
aria-label={`Sub-agent ${subagent.name}: ${subagent.activityLabel}`}
>
<StatusIcon status={subagent.status} />
<Bot className="size-3 text-zinc-500" />
<span className="text-[11px] font-medium text-zinc-300">{subagent.name}</span>
<span className="text-[10px] text-zinc-600"></span>
<span className="text-[10px] text-zinc-500">{subagent.activityLabel}</span>
{subagent.status === 'running' && <ElapsedTimer startedAt={subagent.startedAt} />}
{subagent.error && (
<span className="truncate text-[10px] text-red-400" title={subagent.error}>
{subagent.error}
</span>
)}
</div>
);
}
interface SubagentActivityListProps {
subagents: ReadonlyArray<ActiveSubagent>;
}
export function SubagentActivityList({ subagents }: SubagentActivityListProps) {
if (subagents.length === 0) return null;
// Only show running subagents in the chat stream
const visible = subagents.filter((s) => s.status === 'running');
if (visible.length === 0) return null;
return (
<div className="flex flex-col gap-1 py-1" aria-label="Active sub-agents">
{visible.map((subagent) => (
<SubagentActivityCard key={subagent.toolCallId} subagent={subagent} />
))}
</div>
);
}
+79 -2
View File
@@ -1,9 +1,16 @@
import { CodeHighlightNode, CodeNode } from '@lexical/code';
import { $isCodeHighlightNode, CodeHighlightNode, CodeNode } from '@lexical/code';
import { AutoLinkNode, LinkNode } from '@lexical/link';
import { type Transformer, TRANSFORMERS } from '@lexical/markdown';
import { ListItemNode, ListNode } from '@lexical/list';
import { HeadingNode, QuoteNode } from '@lexical/rich-text';
import { type Klass, type LexicalNode } from 'lexical';
import {
$getSelection,
$isLineBreakNode,
$isRangeSelection,
$isTextNode,
type Klass,
type LexicalNode,
} from 'lexical';
import { normalizeChatMessageLineEndings } from '@shared/utils/chatMessage';
@@ -96,3 +103,73 @@ export function inspectMarkdownPaste(text: string): MarkdownPasteInspection {
export function shouldImportMarkdownPaste(text: string): boolean {
return inspectMarkdownPaste(text).shouldImportMarkdown;
}
/* ── Code-node selection helpers ──────────────────────── */
/**
* Returns the absolute character offset of a selection point within a CodeNode.
* LineBreakNodes count as 1 character; all other children use their text content size.
*/
export function getCodeNodeAbsoluteOffset(
codeNode: CodeNode,
point: { key: string; offset: number },
): number {
let offset = 0;
for (const child of codeNode.getChildren()) {
if (child.getKey() === point.key) return offset + point.offset;
offset += $isLineBreakNode(child) ? 1 : child.getTextContentSize();
}
return offset;
}
/**
* Converts an absolute character offset within a CodeNode into a valid Lexical
* selection point (node key, local offset, and point type).
*
* The returned point always targets either a text-like child (`type: 'text'`)
* or the parent CodeNode itself (`type: 'element'`). It never targets a
* LineBreakNode directly — doing so would crash Lexical because LineBreakNode
* is not an ElementNode.
*/
export function findCodeNodeSelectionPoint(
codeNode: CodeNode,
target: number,
): { key: string; offset: number; type: 'text' | 'element' } {
const children = codeNode.getChildren();
let offset = 0;
for (let i = 0; i < children.length; i++) {
const child = children[i];
const size = $isLineBreakNode(child) ? 1 : child.getTextContentSize();
if (offset + size > target || (offset + size === target && $isTextNode(child))) {
if ($isTextNode(child) || $isCodeHighlightNode(child)) {
return { key: child.getKey(), offset: target - offset, type: 'text' as const };
}
// Non-text child (e.g. LineBreakNode): target the parent CodeNode at this child index
return { key: codeNode.getKey(), offset: i, type: 'element' as const };
}
offset += size;
}
const last = children.length > 0 ? children[children.length - 1] : undefined;
if (last && ($isTextNode(last) || $isCodeHighlightNode(last))) {
return { key: last.getKey(), offset: last.getTextContentSize(), type: 'text' as const };
}
return { key: codeNode.getKey(), offset: children.length, type: 'element' as const };
}
/**
* Restores a range selection within a CodeNode from absolute character offsets.
* Must be called inside an editor update or read context.
*/
export function restoreCodeNodeSelection(
codeNode: CodeNode,
anchorOff: number,
focusOff: number,
): void {
const anchor = findCodeNodeSelectionPoint(codeNode, anchorOff);
const focus = findCodeNodeSelectionPoint(codeNode, focusOff);
const selection = $getSelection();
if ($isRangeSelection(selection)) {
selection.anchor.set(anchor.key, anchor.offset, anchor.type);
selection.focus.set(focus.key, focus.offset, focus.type);
}
}
+117
View File
@@ -1,5 +1,6 @@
import type { PatternDefinition } from '@shared/domain/pattern';
import type { SessionEventRecord } from '@shared/domain/event';
import type { QuotaSnapshot } from '@shared/contracts/sidecar';
export interface AgentActivityState {
agentId: string;
@@ -335,3 +336,119 @@ export function pruneTurnEventLogs(
return changed || Object.keys(next).length !== Object.keys(current).length ? next : current;
}
/* ── Assistant usage accumulator ────────────────────────────── */
export interface AgentUsageAccumulator {
inputTokens: number;
outputTokens: number;
cost: number;
durationMs: number;
requestCount: number;
}
export interface SessionRequestUsageState {
totalInputTokens: number;
totalOutputTokens: number;
totalCost: number;
totalDurationMs: number;
totalNanoAiu: number;
requestCount: number;
perAgent: Record<string, AgentUsageAccumulator>;
latestQuotaSnapshots?: Record<string, QuotaSnapshot>;
}
export type SessionRequestUsageMap = Record<string, SessionRequestUsageState | undefined>;
function createEmptyUsageAccumulator(): AgentUsageAccumulator {
return { inputTokens: 0, outputTokens: 0, cost: 0, durationMs: 0, requestCount: 0 };
}
export function applyAssistantUsageEvent(
current: SessionRequestUsageMap,
event: SessionEventRecord,
): SessionRequestUsageMap {
if (event.kind !== 'assistant-usage') {
return current;
}
const prev = current[event.sessionId] ?? {
totalInputTokens: 0,
totalOutputTokens: 0,
totalCost: 0,
totalDurationMs: 0,
totalNanoAiu: 0,
requestCount: 0,
perAgent: {},
};
const inputTokens = event.usageInputTokens ?? 0;
const outputTokens = event.usageOutputTokens ?? 0;
const cost = event.usageCost ?? 0;
const durationMs = event.usageDuration ?? 0;
const nanoAiu = event.usageTotalNanoAiu ?? 0;
const next: SessionRequestUsageState = {
totalInputTokens: prev.totalInputTokens + inputTokens,
totalOutputTokens: prev.totalOutputTokens + outputTokens,
totalCost: prev.totalCost + cost,
totalDurationMs: prev.totalDurationMs + durationMs,
totalNanoAiu: nanoAiu > 0 ? nanoAiu : prev.totalNanoAiu,
requestCount: prev.requestCount + 1,
perAgent: { ...prev.perAgent },
latestQuotaSnapshots: event.usageQuotaSnapshots ?? prev.latestQuotaSnapshots,
};
const agentKey = event.agentId?.trim() || event.agentName?.trim();
if (agentKey) {
const agentPrev = next.perAgent[agentKey] ?? createEmptyUsageAccumulator();
next.perAgent[agentKey] = {
inputTokens: agentPrev.inputTokens + inputTokens,
outputTokens: agentPrev.outputTokens + outputTokens,
cost: agentPrev.cost + cost,
durationMs: agentPrev.durationMs + durationMs,
requestCount: agentPrev.requestCount + 1,
};
}
return { ...current, [event.sessionId]: next };
}
export function pruneSessionRequestUsage(
current: SessionRequestUsageMap,
sessionIds: Iterable<string>,
): SessionRequestUsageMap {
const allowed = new Set(sessionIds);
const next: SessionRequestUsageMap = {};
let changed = false;
for (const [sessionId, usage] of Object.entries(current)) {
if (!allowed.has(sessionId)) {
changed = true;
continue;
}
next[sessionId] = usage;
}
return changed || Object.keys(next).length !== Object.keys(current).length ? next : current;
}
/* ── Formatting helpers ─────────────────────────────────────── */
export function formatTokenCount(tokens: number): string {
if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1)}M`;
if (tokens >= 1_000) return `${(tokens / 1_000).toFixed(1)}k`;
return String(tokens);
}
export function formatNanoAiu(nanoAiu: number): string {
const aiu = nanoAiu / 1e9;
if (aiu >= 100) return aiu.toFixed(0);
if (aiu >= 10) return aiu.toFixed(1);
return aiu.toFixed(2);
}
export function formatDuration(ms: number): string {
if (ms >= 60_000) return `${(ms / 60_000).toFixed(1)}m`;
return `${(ms / 1_000).toFixed(1)}s`;
}
+9 -1
View File
@@ -112,10 +112,18 @@ function applyMessageDeltaEvent(session: SessionRecord, event: SessionEventRecor
};
}
// Auto-complete any previously pending assistant messages so only
// the new message shows the "Thinking" indicator.
const completedMessages = session.messages.map((message) =>
message.pending && message.role === 'assistant'
? { ...message, pending: false }
: message,
);
return {
...session,
messages: [
...session.messages,
...completedMessages,
{
id: event.messageId,
role: 'assistant',
+162
View File
@@ -0,0 +1,162 @@
import type { SessionEventRecord, SubagentEventKind } from '@shared/domain/event';
export interface ActiveSubagent {
toolCallId: string;
name: string;
description?: string;
model?: string;
activityLabel: string;
startedAt: string;
status: 'running' | 'completed' | 'failed';
error?: string;
}
export type ActiveSubagentMap = Record<string, ReadonlyArray<ActiveSubagent> | undefined>;
function subagentKey(event: SessionEventRecord): string {
return event.subagentToolCallId ?? event.customAgentName ?? 'unknown';
}
function subagentDisplayName(event: SessionEventRecord): string {
return event.customAgentDisplayName ?? event.customAgentName ?? 'Sub-agent';
}
function activityLabelForKind(kind: SubagentEventKind | undefined): string {
switch (kind) {
case 'started':
return 'Starting…';
case 'selected':
return 'Selected';
case 'completed':
return 'Completed';
case 'failed':
return 'Failed';
case 'deselected':
return 'Deselected';
default:
return 'Working…';
}
}
export function applySubagentEvent(
current: ActiveSubagentMap,
event: SessionEventRecord,
): ActiveSubagentMap {
if (event.kind !== 'subagent') {
// Clear all subagents when session goes idle
if (event.kind === 'status' && event.status === 'idle') {
if (!current[event.sessionId]?.length) return current;
const next = { ...current };
delete next[event.sessionId];
return next;
}
// Update running subagent activity from agent-activity events
if (event.kind === 'agent-activity' && event.agentName) {
const existing = current[event.sessionId];
if (!existing?.length) return current;
const agentName = event.agentName.trim();
const hasMatch = existing.some(
(s) => s.status === 'running' && s.name === agentName,
);
if (!hasMatch) return current;
let label: string;
switch (event.activityType) {
case 'tool-calling':
label = `Using ${event.toolName?.trim() || 'a tool'}`;
break;
case 'thinking':
label = 'Thinking…';
break;
case 'handoff':
label = 'Handling handoff…';
break;
default:
return current;
}
return {
...current,
[event.sessionId]: existing.map((s) =>
s.status === 'running' && s.name === agentName
? { ...s, activityLabel: label }
: s,
),
};
}
return current;
}
const key = subagentKey(event);
const existing = current[event.sessionId] ?? [];
switch (event.subagentEventKind) {
case 'started': {
const entry: ActiveSubagent = {
toolCallId: key,
name: subagentDisplayName(event),
description: event.customAgentDescription,
model: event.subagentModel,
activityLabel: activityLabelForKind('started'),
startedAt: event.occurredAt,
status: 'running',
};
return {
...current,
[event.sessionId]: [...existing.filter((s) => s.toolCallId !== key), entry],
};
}
case 'completed': {
return {
...current,
[event.sessionId]: existing.map((s) =>
s.toolCallId === key
? { ...s, status: 'completed' as const, activityLabel: activityLabelForKind('completed') }
: s,
),
};
}
case 'failed': {
return {
...current,
[event.sessionId]: existing.map((s) =>
s.toolCallId === key
? {
...s,
status: 'failed' as const,
activityLabel: activityLabelForKind('failed'),
error: event.subagentError,
}
: s,
),
};
}
default:
return current;
}
}
export function pruneSubagentMap(
current: ActiveSubagentMap,
sessionIds: Iterable<string>,
): ActiveSubagentMap {
const allowed = new Set(sessionIds);
const next: ActiveSubagentMap = {};
let changed = false;
for (const [sessionId, subagents] of Object.entries(current)) {
if (!allowed.has(sessionId)) {
changed = true;
continue;
}
next[sessionId] = subagents;
}
return changed || Object.keys(next).length !== Object.keys(current).length ? next : current;
}
+1 -1
View File
@@ -145,7 +145,7 @@ body {
min-height: 52px;
max-height: 200px;
overflow-y: auto;
padding: 10px 48px 10px 16px;
padding: 10px 16px 4px 16px;
font-size: 14px;
line-height: 1.6;
color: #f4f4f5;
+12
View File
@@ -7,15 +7,24 @@ export const ipcChannels = {
resolveWorkspaceDiscoveredTooling: 'workspace:resolve-discovered-tooling',
refreshProjectGitContext: 'projects:refresh-git-context',
rescanProjectConfigs: 'project:rescan-configs',
rescanProjectCustomization: 'project:rescan-customization',
resolveProjectDiscoveredTooling: 'project:resolve-discovered-tooling',
setProjectAgentProfileEnabled: 'project:set-agent-profile-enabled',
savePattern: 'patterns:save',
deletePattern: 'patterns:delete',
setPatternFavorite: 'patterns:set-favorite',
setTheme: 'settings:set-theme',
setTerminalHeight: 'settings:set-terminal-height',
saveMcpServer: 'tooling:mcp:save',
deleteMcpServer: 'tooling:mcp:delete',
saveLspProfile: 'tooling:lsp:save',
deleteLspProfile: 'tooling:lsp:delete',
describeTerminal: 'terminal:describe',
createTerminal: 'terminal:create',
restartTerminal: 'terminal:restart',
writeTerminal: 'terminal:write',
resizeTerminal: 'terminal:resize',
killTerminal: 'terminal:kill',
updateSessionTooling: 'sessions:update-tooling',
updateSessionApprovalSettings: 'sessions:update-approval-settings',
createSession: 'sessions:create',
@@ -39,6 +48,9 @@ export const ipcChannels = {
selectSession: 'selection:session',
openAppDataFolder: 'troubleshooting:open-app-data-folder',
resetLocalWorkspace: 'troubleshooting:reset-local-workspace',
terminalData: 'terminal:data',
terminalExit: 'terminal:exit',
workspaceUpdated: 'workspace:updated',
sessionEvent: 'sessions:event',
getQuota: 'sidecar:get-quota',
} as const;
+33 -1
View File
@@ -1,9 +1,10 @@
import type { ApprovalDecision } from '@shared/domain/approval';
import type { SidecarCapabilities, InteractionMode, MessageMode } from '@shared/contracts/sidecar';
import type { SidecarCapabilities, InteractionMode, MessageMode, QuotaSnapshot } from '@shared/contracts/sidecar';
import type { PatternDefinition, ReasoningEffort } from '@shared/domain/pattern';
import type { ProjectRecord } from '@shared/domain/project';
import type { QuerySessionsInput, SessionQueryResult } from '@shared/domain/sessionLibrary';
import type { SessionEventRecord } from '@shared/domain/event';
import type { TerminalExitInfo, TerminalSnapshot } from '@shared/domain/terminal';
import type {
LspProfileDefinition,
McpServerDefinition,
@@ -91,12 +92,22 @@ export interface RescanProjectConfigsInput {
projectId: string;
}
export interface RescanProjectCustomizationInput {
projectId: string;
}
export interface ResolveProjectDiscoveredToolingInput {
projectId: string;
serverIds: string[];
resolution: DiscoveredToolingResolution;
}
export interface SetProjectAgentProfileEnabledInput {
projectId: string;
agentProfileId: string;
enabled: boolean;
}
export interface ResolveWorkspaceDiscoveredToolingInput {
serverIds: string[];
resolution: DiscoveredToolingResolution;
@@ -132,6 +143,15 @@ export interface DeleteSessionInput {
sessionId: string;
}
export interface ResizeTerminalInput {
cols: number;
rows: number;
}
export interface SetTerminalHeightInput {
height?: number;
}
export interface ElectronApi {
describeSidecarCapabilities(): Promise<SidecarCapabilities>;
refreshSidecarCapabilities(): Promise<SidecarCapabilities>;
@@ -141,7 +161,9 @@ export interface ElectronApi {
resolveWorkspaceDiscoveredTooling(input: ResolveWorkspaceDiscoveredToolingInput): Promise<WorkspaceState>;
refreshProjectGitContext(projectId?: string): Promise<WorkspaceState>;
rescanProjectConfigs(input: RescanProjectConfigsInput): Promise<WorkspaceState>;
rescanProjectCustomization(input: RescanProjectCustomizationInput): Promise<WorkspaceState>;
resolveProjectDiscoveredTooling(input: ResolveProjectDiscoveredToolingInput): Promise<WorkspaceState>;
setProjectAgentProfileEnabled(input: SetProjectAgentProfileEnabledInput): Promise<WorkspaceState>;
savePattern(input: SavePatternInput): Promise<WorkspaceState>;
deletePattern(patternId: string): Promise<WorkspaceState>;
saveMcpServer(input: SaveMcpServerInput): Promise<WorkspaceState>;
@@ -171,8 +193,18 @@ export interface ElectronApi {
selectSession(sessionId?: string): Promise<WorkspaceState>;
setPatternFavorite(input: SetPatternFavoriteInput): Promise<WorkspaceState>;
setTheme(theme: AppearanceTheme): Promise<WorkspaceState>;
setTerminalHeight(input: SetTerminalHeightInput): Promise<WorkspaceState>;
describeTerminal(): Promise<TerminalSnapshot | undefined>;
createTerminal(): Promise<TerminalSnapshot>;
restartTerminal(): Promise<TerminalSnapshot>;
killTerminal(): Promise<void>;
writeTerminal(data: string): void;
resizeTerminal(input: ResizeTerminalInput): void;
openAppDataFolder(): Promise<void>;
resetLocalWorkspace(): Promise<WorkspaceState>;
getQuota(): Promise<Record<string, QuotaSnapshot>>;
onTerminalData(listener: (data: string) => void): () => void;
onTerminalExit(listener: (info: TerminalExitInfo) => void): () => void;
onWorkspaceUpdated(listener: (workspace: WorkspaceState) => void): () => void;
onSessionEvent(listener: (event: SessionEventRecord) => void): () => void;
}
+42 -1
View File
@@ -80,6 +80,7 @@ export interface RunTurnCommand {
workspaceKind?: 'project' | 'scratchpad';
mode?: InteractionMode;
messageMode?: MessageMode;
projectInstructions?: string;
pattern: PatternDefinition;
messages: ChatMessageRecord[];
attachments?: ChatMessageAttachment[];
@@ -143,7 +144,8 @@ export type SidecarCommand =
| ResolveUserInputCommand
| ListSessionsCommand
| DeleteSessionCommand
| DisconnectSessionCommand;
| DisconnectSessionCommand
| GetQuotaCommand;
export interface RunTurnLocalMcpServerConfig {
id: string;
@@ -469,6 +471,43 @@ export interface CommandErrorEvent {
message: string;
}
export interface AssistantUsageEvent {
type: 'assistant-usage';
requestId: string;
sessionId: string;
agentId?: string;
agentName?: string;
model: string;
inputTokens?: number;
outputTokens?: number;
cacheReadTokens?: number;
cacheWriteTokens?: number;
cost?: number;
duration?: number;
totalNanoAiu?: number;
quotaSnapshots?: Record<string, QuotaSnapshot>;
}
export interface QuotaSnapshot {
entitlementRequests: number;
usedRequests: number;
remainingPercentage: number;
overage: number;
overageAllowedWithExhaustedQuota: boolean;
resetDate?: string;
}
export interface GetQuotaCommand {
type: 'get-quota';
requestId: string;
}
export interface QuotaResultEvent {
type: 'quota-result';
requestId: string;
quotaSnapshots: Record<string, QuotaSnapshot>;
}
export interface CommandCompleteEvent {
type: 'command-complete';
requestId: string;
@@ -493,5 +532,7 @@ export type SidecarEvent =
| SessionsListedEvent
| SessionsDeletedEvent
| SessionDisconnectedEvent
| AssistantUsageEvent
| QuotaResultEvent
| CommandErrorEvent
| CommandCompleteEvent;
+2
View File
@@ -7,6 +7,7 @@ export interface BaseDiscoveredMcpServer {
name: string;
transport: DiscoveredMcpServerTransport;
tools: string[];
probedTools?: { name: string; description?: string }[];
timeoutMs?: number;
scope: DiscoveredToolingScope;
scannerId: string;
@@ -121,6 +122,7 @@ export function mergeDiscoveredToolingState(
return {
...server,
status: existing.status,
probedTools: existing.probedTools,
} satisfies DiscoveredMcpServer;
}
+19 -1
View File
@@ -1,5 +1,7 @@
import type { SessionRunRecord } from '@shared/domain/runTimeline';
import type { QuotaSnapshot } from '@shared/contracts/sidecar';
export type SessionActivityType = 'thinking' | 'tool-calling' | 'handoff' | 'completed';
export type SessionEventKind =
@@ -14,7 +16,8 @@ export type SessionEventKind =
| 'hook-lifecycle'
| 'session-usage'
| 'session-compaction'
| 'pending-messages-modified';
| 'pending-messages-modified'
| 'assistant-usage';
export type SubagentEventKind = 'started' | 'completed' | 'failed' | 'selected' | 'deselected';
@@ -40,6 +43,10 @@ export interface SessionEventRecord {
subagentEventKind?: SubagentEventKind;
customAgentName?: string;
customAgentDisplayName?: string;
customAgentDescription?: string;
subagentError?: string;
subagentToolCallId?: string;
subagentModel?: string;
// Skill invoked fields
skillName?: string;
@@ -63,4 +70,15 @@ export interface SessionEventRecord {
preCompactionTokens?: number;
postCompactionTokens?: number;
tokensRemoved?: number;
// Assistant usage fields
usageModel?: string;
usageInputTokens?: number;
usageOutputTokens?: number;
usageCacheReadTokens?: number;
usageCacheWriteTokens?: number;
usageCost?: number;
usageDuration?: number;
usageTotalNanoAiu?: number;
usageQuotaSnapshots?: Record<string, QuotaSnapshot>;
}
+2
View File
@@ -1,5 +1,6 @@
import { nowIso } from '@shared/utils/ids';
import type { ProjectDiscoveredTooling } from '@shared/domain/discoveredTooling';
import type { ProjectCustomizationState } from '@shared/domain/projectCustomization';
export type ProjectGitContextStatus = 'ready' | 'not-repository' | 'git-missing' | 'error';
@@ -39,6 +40,7 @@ export interface ProjectRecord {
addedAt: string;
git?: ProjectGitContext;
discoveredTooling?: ProjectDiscoveredTooling;
customization?: ProjectCustomizationState;
}
export const SCRATCHPAD_PROJECT_ID = 'project-scratchpad';
+276
View File
@@ -0,0 +1,276 @@
export interface ProjectInstructionFile {
id: string;
sourcePath: string;
content: string;
}
export interface ProjectAgentProfileMcpServerConfig {
[key: string]: unknown;
}
export interface ProjectAgentProfile {
id: string;
name: string;
displayName?: string;
description?: string;
tools?: string[];
prompt: string;
mcpServers?: Record<string, ProjectAgentProfileMcpServerConfig>;
infer?: boolean;
sourcePath: string;
enabled: boolean;
}
export interface ProjectPromptVariable {
name: string;
placeholder: string;
}
export interface ProjectPromptFile {
id: string;
name: string;
description?: string;
agent?: string;
template: string;
variables: ProjectPromptVariable[];
sourcePath: string;
}
export interface ProjectCustomizationState {
instructions: ProjectInstructionFile[];
agentProfiles: ProjectAgentProfile[];
promptFiles: ProjectPromptFile[];
lastScannedAt?: string;
}
export function createProjectCustomizationState(): ProjectCustomizationState {
return {
instructions: [],
agentProfiles: [],
promptFiles: [],
};
}
export function normalizeProjectCustomizationState(
value?: Partial<ProjectCustomizationState>,
): ProjectCustomizationState {
return {
instructions: (value?.instructions ?? [])
.map(normalizeProjectInstructionFile)
.filter((instruction) => instruction.content.length > 0)
.sort(compareProjectFiles),
agentProfiles: (value?.agentProfiles ?? [])
.map(normalizeProjectAgentProfile)
.filter((profile) => profile.name.length > 0 && profile.prompt.length > 0)
.sort(compareProjectFiles),
promptFiles: (value?.promptFiles ?? [])
.map(normalizeProjectPromptFile)
.filter((promptFile) => promptFile.name.length > 0 && promptFile.template.length > 0)
.sort(compareProjectFiles),
lastScannedAt: normalizeOptionalString(value?.lastScannedAt),
};
}
export function mergeProjectCustomizationState(
current: ProjectCustomizationState | undefined,
scanned: Omit<ProjectCustomizationState, 'lastScannedAt'>,
lastScannedAt: string,
): ProjectCustomizationState {
const normalizedCurrent = normalizeProjectCustomizationState(current);
const currentProfilesById = new Map(
normalizedCurrent.agentProfiles.map((profile) => [profile.id, profile]),
);
return {
instructions: scanned.instructions
.map(normalizeProjectInstructionFile)
.filter((instruction) => instruction.content.length > 0)
.sort(compareProjectFiles),
agentProfiles: scanned.agentProfiles
.map(normalizeProjectAgentProfile)
.filter((profile) => profile.name.length > 0 && profile.prompt.length > 0)
.map((profile) => ({
...profile,
enabled: currentProfilesById.get(profile.id)?.enabled ?? profile.enabled,
}))
.sort(compareProjectFiles),
promptFiles: scanned.promptFiles
.map(normalizeProjectPromptFile)
.filter((promptFile) => promptFile.name.length > 0 && promptFile.template.length > 0)
.sort(compareProjectFiles),
lastScannedAt,
};
}
export function listEnabledProjectAgentProfiles(
state?: Partial<ProjectCustomizationState>,
): ProjectAgentProfile[] {
return normalizeProjectCustomizationState(state).agentProfiles.filter((profile) => profile.enabled);
}
export function resolveProjectInstructionsContent(
state?: Partial<ProjectCustomizationState>,
): string | undefined {
const content = normalizeProjectCustomizationState(state).instructions
.map((instruction) => instruction.content)
.filter((value) => value.length > 0)
.join('\n\n')
.trim();
return content.length > 0 ? content : undefined;
}
export function setProjectAgentProfileEnabled(
state: ProjectCustomizationState | undefined,
agentProfileId: string,
enabled: boolean,
): ProjectCustomizationState {
const normalizedState = normalizeProjectCustomizationState(state);
return {
...normalizedState,
agentProfiles: normalizedState.agentProfiles.map((profile) =>
profile.id === agentProfileId
? {
...profile,
enabled,
}
: profile),
};
}
function normalizeProjectInstructionFile(file: ProjectInstructionFile): ProjectInstructionFile {
return {
id: file.id.trim(),
sourcePath: normalizePathLikeString(file.sourcePath),
content: file.content.trim(),
};
}
function normalizeProjectAgentProfile(profile: ProjectAgentProfile): ProjectAgentProfile {
const tools = normalizeOptionalStringArray(profile.tools);
const normalizedProfile: ProjectAgentProfile = {
id: profile.id.trim(),
name: profile.name.trim(),
prompt: profile.prompt.trim(),
sourcePath: normalizePathLikeString(profile.sourcePath),
enabled: profile.enabled !== false,
};
const displayName = normalizeOptionalString(profile.displayName);
if (displayName) {
normalizedProfile.displayName = displayName;
}
const description = normalizeOptionalString(profile.description);
if (description) {
normalizedProfile.description = description;
}
if (tools) {
normalizedProfile.tools = tools;
}
const mcpServers = normalizeOptionalMcpServers(profile.mcpServers);
if (mcpServers) {
normalizedProfile.mcpServers = mcpServers;
}
if (typeof profile.infer === 'boolean') {
normalizedProfile.infer = profile.infer;
}
return normalizedProfile;
}
function normalizeProjectPromptFile(promptFile: ProjectPromptFile): ProjectPromptFile {
const normalizedPromptFile: ProjectPromptFile = {
id: promptFile.id.trim(),
name: promptFile.name.trim(),
template: promptFile.template.trim(),
variables: promptFile.variables
.map((variable) => ({
name: variable.name.trim(),
placeholder: variable.placeholder.trim(),
}))
.filter((variable) => variable.name.length > 0),
sourcePath: normalizePathLikeString(promptFile.sourcePath),
};
const description = normalizeOptionalString(promptFile.description);
if (description) {
normalizedPromptFile.description = description;
}
const agent = normalizeOptionalString(promptFile.agent);
if (agent) {
normalizedPromptFile.agent = agent;
}
return normalizedPromptFile;
}
function compareProjectFiles(
left: Pick<ProjectInstructionFile | ProjectAgentProfile | ProjectPromptFile, 'sourcePath' | 'id'>,
right: Pick<ProjectInstructionFile | ProjectAgentProfile | ProjectPromptFile, 'sourcePath' | 'id'>,
): number {
return left.sourcePath.localeCompare(right.sourcePath) || left.id.localeCompare(right.id);
}
function normalizeOptionalMcpServers(
value?: Record<string, ProjectAgentProfileMcpServerConfig>,
): Record<string, ProjectAgentProfileMcpServerConfig> | undefined {
if (!value) {
return undefined;
}
const normalizedEntries = Object.entries(value)
.map(([name, config]) => [name.trim(), normalizeYamlValue(config)] as const)
.filter(([name, config]) => name.length > 0 && isPlainObject(config))
.sort(([leftName], [rightName]) => leftName.localeCompare(rightName));
if (normalizedEntries.length === 0) {
return undefined;
}
return Object.fromEntries(
normalizedEntries.map(([name, config]) => [name, config as ProjectAgentProfileMcpServerConfig]),
);
}
function normalizeOptionalString(value?: string): string | undefined {
const trimmed = value?.trim();
return trimmed ? trimmed : undefined;
}
function normalizeOptionalStringArray(values?: ReadonlyArray<string>): string[] | undefined {
if (!values) {
return undefined;
}
return [...new Set(values.map((value) => value.trim()).filter((value) => value.length > 0))];
}
function normalizePathLikeString(value: string): string {
return value.trim().replaceAll('/', '\\');
}
function normalizeYamlValue(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map(normalizeYamlValue);
}
if (!isPlainObject(value)) {
return typeof value === 'string' ? value.trim() : value;
}
return Object.fromEntries(
Object.entries(value)
.map(([key, nestedValue]) => [key.trim(), normalizeYamlValue(nestedValue)] as const)
.filter(([key]) => key.length > 0)
.sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey)),
);
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === 'object' && !Array.isArray(value);
}
+12
View File
@@ -0,0 +1,12 @@
export interface TerminalSnapshot {
cwd: string;
shell: string;
pid: number;
cols: number;
rows: number;
}
export interface TerminalExitInfo {
exitCode: number;
signal?: number;
}
+136 -4
View File
@@ -9,11 +9,17 @@ import { nowIso } from '@shared/utils/ids';
export type McpServerTransport = 'local' | 'http' | 'sse';
export interface McpProbedTool {
name: string;
description?: string;
}
export interface BaseMcpServerDefinition {
id: string;
name: string;
transport: McpServerTransport;
tools: string[];
probedTools?: McpProbedTool[];
timeoutMs?: number;
createdAt: string;
updatedAt: string;
@@ -57,6 +63,7 @@ export interface WorkspaceSettings {
theme: AppearanceTheme;
tooling: WorkspaceToolingSettings;
discoveredUserTooling: DiscoveredToolingState;
terminalHeight?: number;
}
export interface SessionToolingSelection {
@@ -149,6 +156,12 @@ const fallbackRuntimeApprovalTools: ReadonlyArray<RuntimeToolDefinition> = [
{ id: 'store_memory', label: 'Store memory' },
];
const MCP_SERVER_APPROVAL_PREFIX = 'mcp_server:';
export function buildMcpServerApprovalKey(serverName: string): string {
return `${MCP_SERVER_APPROVAL_PREFIX}${serverName}`;
}
export function createWorkspaceSettings(): WorkspaceSettings {
return {
theme: 'dark',
@@ -173,7 +186,17 @@ export function normalizeTheme(value?: string): AppearanceTheme {
return validThemes.has(value ?? '') ? (value as AppearanceTheme) : 'dark';
}
export function normalizeTerminalHeight(value?: number): number | undefined {
if (typeof value !== 'number' || !Number.isFinite(value)) {
return undefined;
}
const normalized = Math.round(value);
return normalized >= 120 ? normalized : undefined;
}
export function normalizeWorkspaceSettings(settings?: Partial<WorkspaceSettings>): WorkspaceSettings {
const terminalHeight = normalizeTerminalHeight(settings?.terminalHeight);
return {
theme: normalizeTheme(settings?.theme),
tooling: {
@@ -181,6 +204,7 @@ export function normalizeWorkspaceSettings(settings?: Partial<WorkspaceSettings>
lspProfiles: (settings?.tooling?.lspProfiles ?? []).map(normalizeLspProfileDefinition),
},
discoveredUserTooling: normalizeDiscoveredToolingState(settings?.discoveredUserTooling),
...(terminalHeight !== undefined ? { terminalHeight } : {}),
};
}
@@ -230,10 +254,16 @@ export function listApprovalToolDefinitions(
}
for (const server of tooling.mcpServers) {
for (const toolName of normalizeStringArray(server.tools)) {
const declaredTools = normalizeStringArray(server.tools);
const toolEntries = declaredTools.length > 0
? declaredTools.map((name) => ({ name, description: undefined }))
: (server.probedTools ?? []).filter((t) => t.name.trim().length > 0);
for (const tool of toolEntries) {
registerApprovalTool(toolsById, {
id: toolName,
label: toolName,
id: tool.name,
label: tool.name,
description: tool.description,
kind: 'mcp',
providerId: server.id,
providerName: server.name,
@@ -262,7 +292,103 @@ export function listApprovalToolNames(
tooling: WorkspaceToolingSettings,
runtimeTools?: ReadonlyArray<RuntimeToolDefinition>,
): string[] {
return listApprovalToolDefinitions(tooling, runtimeTools).map((tool) => tool.id);
const toolNames = listApprovalToolDefinitions(tooling, runtimeTools).map((tool) => tool.id);
for (const server of tooling.mcpServers) {
toolNames.push(buildMcpServerApprovalKey(server.name));
}
return [...new Set(toolNames)];
}
export interface ApprovalToolGroup {
id: string;
label: string;
kind: ApprovalToolKind;
tools: ApprovalToolDefinition[];
serverApprovalKey?: string;
}
const approvalToolGroupKindOrder: ApprovalToolKind[] = ['builtin', 'mcp', 'lsp', 'mixed'];
export function groupApprovalToolsByProvider(
tools: ReadonlyArray<ApprovalToolDefinition>,
tooling: WorkspaceToolingSettings,
): ApprovalToolGroup[] {
const serverNames = new Map(tooling.mcpServers.map((s) => [s.id, s.name]));
const profileNames = new Map(tooling.lspProfiles.map((p) => [p.id, p.name]));
const groups = new Map<string, ApprovalToolGroup>();
for (const tool of tools) {
// Place MCP tools in every provider group they belong to, so each server
// shows its own tools even when multiple servers share the same tool names.
if (tool.kind === 'mcp' && tool.providerIds.length > 1) {
for (const providerId of tool.providerIds) {
const groupId = `mcp:${providerId}`;
let group = groups.get(groupId);
if (!group) {
const label = serverNames.get(providerId) ?? providerId;
group = { id: groupId, label, kind: 'mcp', tools: [] };
groups.set(groupId, group);
}
group.tools.push(tool);
}
continue;
}
const groupKey = resolveApprovalToolGroupKey(tool, serverNames, profileNames);
let group = groups.get(groupKey.id);
if (!group) {
group = { id: groupKey.id, label: groupKey.label, kind: groupKey.kind, tools: [] };
groups.set(groupKey.id, group);
}
group.tools.push(tool);
}
// Ensure every MCP server has a group (even with no declared tools) and
// attach server-level approval keys.
for (const server of tooling.mcpServers) {
const groupId = `mcp:${server.id}`;
let group = groups.get(groupId);
if (!group) {
group = { id: groupId, label: server.name, kind: 'mcp', tools: [] };
groups.set(groupId, group);
}
group.serverApprovalKey = buildMcpServerApprovalKey(server.name);
}
return [...groups.values()].sort((a, b) => {
const kindDiff = approvalToolGroupKindOrder.indexOf(a.kind) - approvalToolGroupKindOrder.indexOf(b.kind);
if (kindDiff !== 0) return kindDiff;
return a.label.localeCompare(b.label);
});
}
function resolveApprovalToolGroupKey(
tool: ApprovalToolDefinition,
serverNames: ReadonlyMap<string, string>,
profileNames: ReadonlyMap<string, string>,
): { id: string; label: string; kind: ApprovalToolKind } {
if (tool.kind === 'builtin') {
return { id: 'builtin', label: 'Built-in', kind: 'builtin' };
}
const primaryProviderId = tool.providerIds[0];
if (tool.kind === 'mcp' && primaryProviderId) {
return {
id: `mcp:${primaryProviderId}`,
label: serverNames.get(primaryProviderId) ?? tool.providerNames[0] ?? primaryProviderId,
kind: 'mcp',
};
}
if (tool.kind === 'lsp' && primaryProviderId) {
return {
id: `lsp:${primaryProviderId}`,
label: profileNames.get(primaryProviderId) ?? tool.providerNames[0] ?? primaryProviderId,
kind: 'lsp',
};
}
return { id: 'other', label: 'Other', kind: 'mixed' };
}
export function validateMcpServerDefinition(server: McpServerDefinition): string | undefined {
@@ -379,6 +505,10 @@ function toResolvedMcpServerDefinition(
server: ReturnType<typeof listAcceptedDiscoveredMcpServers>[number],
timestamp = nowIso(),
): McpServerDefinition {
const probedTools = server.probedTools && server.probedTools.length > 0
? [...server.probedTools]
: undefined;
if (server.transport === 'local') {
return normalizeMcpServerDefinition({
id: server.id,
@@ -389,6 +519,7 @@ function toResolvedMcpServerDefinition(
cwd: server.cwd,
env: server.env ? { ...server.env } : undefined,
tools: [...server.tools],
probedTools,
timeoutMs: server.timeoutMs,
createdAt: timestamp,
updatedAt: timestamp,
@@ -402,6 +533,7 @@ function toResolvedMcpServerDefinition(
url: server.url,
headers: server.headers ? { ...server.headers } : undefined,
tools: [...server.tools],
probedTools,
timeoutMs: server.timeoutMs,
createdAt: timestamp,
updatedAt: timestamp,
+2
View File
@@ -10,6 +10,8 @@ export interface WorkspaceState {
patterns: PatternDefinition[];
sessions: SessionRecord[];
settings: WorkspaceSettings;
/** Runtime-only MCP probe progress for live UI updates. */
mcpProbingServerIds?: string[];
selectedProjectId?: string;
selectedPatternId?: string;
selectedSessionId?: string;
@@ -0,0 +1,260 @@
import { describe, expect, mock, test } from 'bun:test';
import type { PendingApprovalRecord } from '@shared/domain/approval';
import type { PendingMcpAuthRecord } from '@shared/domain/mcpAuth';
import type { PatternDefinition } from '@shared/domain/pattern';
import type { PendingPlanReviewRecord } from '@shared/domain/planReview';
import type { SessionRunRecord } from '@shared/domain/runTimeline';
import type { SessionRecord } from '@shared/domain/session';
import type { PendingUserInputRecord } from '@shared/domain/userInput';
import { createWorkspaceSeed, type WorkspaceState } from '@shared/domain/workspace';
const TIMESTAMP = '2026-03-28T00:00:00.000Z';
const INTERRUPTED_RUN_ERROR =
'This session was interrupted because Aryx restarted while a run was in progress.';
mock.module('electron', () => {
const electronMock = {
app: {
isPackaged: false,
getAppPath: () => 'C:\\workspace\\personal\\repositories\\aryx',
getPath: () => 'C:\\workspace\\personal\\repositories\\aryx\\tests\\fixtures',
},
dialog: {
showOpenDialog: async () => ({ canceled: true, filePaths: [] }),
},
shell: {
openPath: async () => '',
},
};
return {
...electronMock,
default: electronMock,
};
});
mock.module('keytar', () => ({
default: {
getPassword: async () => null,
setPassword: async () => undefined,
deletePassword: async () => false,
},
}));
const { AryxAppService } = await import('@main/AryxAppService');
function requireSinglePattern(workspace: WorkspaceState): PatternDefinition {
const pattern = workspace.patterns.find((candidate) => candidate.mode === 'single');
if (!pattern) {
throw new Error('Expected the workspace seed to include a single-agent pattern.');
}
return pattern;
}
function createSession(patternId: string, overrides?: Partial<SessionRecord>): SessionRecord {
return {
id: 'session-1',
projectId: 'project-1',
patternId,
title: 'Session',
createdAt: TIMESTAMP,
updatedAt: TIMESTAMP,
status: 'idle',
messages: [],
runs: [],
...overrides,
};
}
function createRun(
pattern: PatternDefinition,
overrides?: Partial<SessionRunRecord>,
): SessionRunRecord {
return {
id: 'run-1',
requestId: 'request-1',
projectId: 'project-1',
projectPath: 'C:\\workspace\\personal\\repositories\\aryx',
workspaceKind: 'project',
patternId: pattern.id,
patternName: pattern.name,
patternMode: pattern.mode,
triggerMessageId: 'message-1',
startedAt: TIMESTAMP,
status: 'running',
agents: [],
events: [
{
id: 'run-event-1',
kind: 'run-started',
occurredAt: TIMESTAMP,
status: 'completed',
},
],
...overrides,
};
}
function createPendingApproval(id: string, title: string): PendingApprovalRecord {
return {
id,
kind: 'tool-call',
status: 'pending',
requestedAt: TIMESTAMP,
title,
};
}
function createPendingUserInput(overrides?: Partial<PendingUserInputRecord>): PendingUserInputRecord {
return {
id: 'user-input-1',
status: 'pending',
question: 'What should I do next?',
allowFreeform: true,
requestedAt: TIMESTAMP,
...overrides,
};
}
function createPendingPlanReview(overrides?: Partial<PendingPlanReviewRecord>): PendingPlanReviewRecord {
return {
id: 'plan-review-1',
status: 'pending',
summary: 'Review the plan before continuing.',
planContent: '1. Investigate\n2. Implement',
requestedAt: TIMESTAMP,
...overrides,
};
}
function createPendingMcpAuth(overrides?: Partial<PendingMcpAuthRecord>): PendingMcpAuthRecord {
return {
id: 'oauth-1',
status: 'pending',
serverName: 'Example MCP',
serverUrl: 'https://example.com/mcp',
requestedAt: TIMESTAMP,
...overrides,
};
}
function createService(
workspace: WorkspaceState,
): {
service: InstanceType<typeof AryxAppService>;
getSaveCalls: () => number;
} {
let saveCalls = 0;
const service = new AryxAppService();
const internals = service as unknown as Record<string, unknown>;
internals.workspaceRepository = {
load: async () => workspace,
save: async () => {
saveCalls += 1;
},
};
internals.syncUserDiscoveredTooling = async () => false;
internals.syncProjectDiscoveredTooling = async () => false;
internals.pruneUnavailableSessionToolingSelections = () => false;
internals.pruneUnavailableApprovalTools = async () => false;
internals.refreshProjectGitContext = async () => undefined;
return {
service,
getSaveCalls: () => saveCalls,
};
}
describe('AryxAppService interrupted session cleanup', () => {
test('clears stale approvals and user input, then fails the interrupted run on load', async () => {
const workspace = createWorkspaceSeed();
const pattern = requireSinglePattern(workspace);
const runningRun = createRun(pattern);
const session = createSession(pattern.id, {
status: 'running',
pendingApproval: createPendingApproval('approval-1', 'Approve reading the repo'),
pendingApprovalQueue: [createPendingApproval('approval-2', 'Approve writing the repo')],
pendingUserInput: createPendingUserInput(),
runs: [runningRun],
});
workspace.sessions = [session];
const { service, getSaveCalls } = createService(workspace);
const loaded = await service.loadWorkspace();
const cleanedSession = loaded.sessions[0];
if (!cleanedSession) {
throw new Error('Expected loadWorkspace to return the interrupted session.');
}
expect(cleanedSession.pendingApproval).toBeUndefined();
expect(cleanedSession.pendingApprovalQueue).toBeUndefined();
expect(cleanedSession.pendingUserInput).toBeUndefined();
expect(cleanedSession.status).toBe('error');
expect(cleanedSession.lastError).toBe(INTERRUPTED_RUN_ERROR);
expect(getSaveCalls()).toBe(1);
const failedRun = cleanedSession.runs[0];
if (!failedRun) {
throw new Error('Expected the interrupted run to remain attached to the session.');
}
expect(failedRun.status).toBe('error');
expect(failedRun.completedAt).toBe(cleanedSession.updatedAt);
expect(failedRun.events.some((event) => event.kind === 'run-failed' && event.error === INTERRUPTED_RUN_ERROR))
.toBe(true);
expect(failedRun.events.filter((event) => event.kind === 'approval').map((event) => event.decision))
.toEqual(['rejected', 'rejected']);
});
test('fails sessions that were left in running state even without pending interaction records', async () => {
const workspace = createWorkspaceSeed();
const pattern = requireSinglePattern(workspace);
const session = createSession(pattern.id, {
status: 'running',
runs: [createRun(pattern)],
});
workspace.sessions = [session];
const { service, getSaveCalls } = createService(workspace);
const loaded = await service.loadWorkspace();
const cleanedSession = loaded.sessions[0];
if (!cleanedSession) {
throw new Error('Expected loadWorkspace to return the running session.');
}
expect(cleanedSession.status).toBe('error');
expect(cleanedSession.lastError).toBe(INTERRUPTED_RUN_ERROR);
expect(cleanedSession.runs[0]?.status).toBe('error');
expect(getSaveCalls()).toBe(1);
});
test('preserves restart-safe plan review and MCP auth prompts', async () => {
const workspace = createWorkspaceSeed();
const pattern = requireSinglePattern(workspace);
const planReview = createPendingPlanReview();
const mcpAuth = createPendingMcpAuth();
const session = createSession(pattern.id, {
pendingPlanReview: planReview,
pendingMcpAuth: mcpAuth,
});
workspace.sessions = [session];
const { service, getSaveCalls } = createService(workspace);
const loaded = await service.loadWorkspace();
const cleanedSession = loaded.sessions[0];
if (!cleanedSession) {
throw new Error('Expected loadWorkspace to return the session.');
}
expect(cleanedSession.status).toBe('idle');
expect(cleanedSession.pendingPlanReview).toEqual(planReview);
expect(cleanedSession.pendingMcpAuth).toEqual(mcpAuth);
expect(getSaveCalls()).toBe(0);
});
});
+278
View File
@@ -0,0 +1,278 @@
import { beforeEach, describe, expect, mock, test } from 'bun:test';
import type { ProjectRecord } from '@shared/domain/project';
import { createWorkspaceSeed, type WorkspaceState } from '@shared/domain/workspace';
const TIMESTAMP = '2026-03-28T00:00:00.000Z';
type MockProbeResult = {
serverId: string;
serverName: string;
tools: Array<{ name: string; description?: string }>;
status: 'success' | 'failed';
error?: string;
};
const probeCalls: string[][] = [];
let probeResults: MockProbeResult[] = [];
mock.module('electron', () => {
const electronMock = {
app: {
isPackaged: false,
getAppPath: () => 'C:\\workspace\\personal\\repositories\\aryx',
getPath: () => 'C:\\workspace\\personal\\repositories\\aryx\\tests\\fixtures',
},
dialog: {
showOpenDialog: async () => ({ canceled: true, filePaths: [] }),
},
shell: {
openPath: async () => '',
},
};
return {
...electronMock,
default: electronMock,
};
});
mock.module('keytar', () => ({
default: {
getPassword: async () => null,
setPassword: async () => undefined,
deletePassword: async () => false,
},
}));
const { AryxAppService } = await import('@main/AryxAppService');
beforeEach(() => {
probeCalls.length = 0;
probeResults = [];
});
function createProject(overrides?: Partial<ProjectRecord>): ProjectRecord {
return {
id: 'project-alpha',
name: 'alpha',
path: 'C:\\workspace\\alpha',
addedAt: TIMESTAMP,
...overrides,
};
}
function cloneWorkspaceState(workspace: WorkspaceState): WorkspaceState {
return JSON.parse(JSON.stringify(workspace)) as WorkspaceState;
}
function createService(workspace: WorkspaceState): {
service: InstanceType<typeof AryxAppService>;
snapshots: WorkspaceState[];
} {
const service = new AryxAppService();
const internals = service as unknown as Record<string, unknown>;
const snapshots: WorkspaceState[] = [];
internals.loadWorkspace = async () => workspace;
internals.persistAndBroadcast = async (nextWorkspace: WorkspaceState) => {
snapshots.push(cloneWorkspaceState(nextWorkspace));
return nextWorkspace;
};
internals.probeMcpServers = async (
servers: Array<{ id: string }>,
_tokenLookup?: (serverUrl: string) => string | undefined,
onResult?: (result: MockProbeResult) => void | Promise<void>,
) => {
probeCalls.push(servers.map((server) => server.id));
for (const result of probeResults) {
await onResult?.(result);
}
return probeResults;
};
return { service, snapshots };
}
describe('AryxAppService MCP probing', () => {
test('probes accepted discovered and manual MCP servers in one batch with incremental workspace updates', async () => {
const workspace = createWorkspaceSeed();
const project = createProject({
discoveredTooling: {
mcpServers: [
{
id: 'project-server',
name: 'Project MCP',
transport: 'local',
command: 'project-mcp',
args: [],
tools: [],
scope: 'project',
scannerId: 'vscode-mcp',
sourcePath: 'C:\\workspace\\alpha\\.vscode\\mcp.json',
sourceLabel: '.vscode\\mcp.json',
fingerprint: 'project-fingerprint',
status: 'accepted',
},
],
lastScannedAt: TIMESTAMP,
},
});
workspace.projects = [project];
workspace.settings.discoveredUserTooling = {
mcpServers: [
{
id: 'user-server',
name: 'User MCP',
transport: 'local',
command: 'user-mcp',
args: [],
tools: [],
scope: 'user',
scannerId: 'copilot-user-mcp',
sourcePath: 'C:\\Users\\tester\\.copilot\\mcp.json',
sourceLabel: '~\\.copilot\\mcp.json',
fingerprint: 'user-fingerprint',
status: 'accepted',
},
],
lastScannedAt: TIMESTAMP,
};
workspace.settings.tooling.mcpServers = [
{
id: 'manual-server',
name: 'Manual MCP',
transport: 'local',
command: 'manual-mcp',
args: [],
tools: [],
createdAt: TIMESTAMP,
updatedAt: TIMESTAMP,
},
];
probeResults = [
{
serverId: 'project-server',
serverName: 'Project MCP',
status: 'success',
tools: [{ name: 'project.status' }],
},
{
serverId: 'manual-server',
serverName: 'Manual MCP',
status: 'success',
tools: [{ name: 'manual.status' }],
},
{
serverId: 'user-server',
serverName: 'User MCP',
status: 'failed',
tools: [],
error: 'boom',
},
];
const { service, snapshots } = createService(workspace);
await (
service as unknown as {
probeAllAcceptedMcpServers: (nextWorkspace: WorkspaceState) => Promise<void>;
}
).probeAllAcceptedMcpServers(workspace);
expect(probeCalls).toEqual([[
'user-server',
'project-server',
'manual-server',
]]);
expect(snapshots.map((snapshot) => snapshot.mcpProbingServerIds)).toEqual([
['user-server', 'project-server', 'manual-server'],
['user-server', 'manual-server'],
['user-server'],
undefined,
]);
expect(workspace.projects[0]?.discoveredTooling?.mcpServers[0]?.probedTools).toEqual([
{ name: 'project.status' },
]);
expect(workspace.settings.tooling.mcpServers[0]?.probedTools).toEqual([
{ name: 'manual.status' },
]);
expect(workspace.settings.discoveredUserTooling.mcpServers[0]?.probedTools).toBeUndefined();
});
test('tracks probing progress while re-probing matching remote MCP servers after OAuth', async () => {
const workspace = createWorkspaceSeed();
workspace.settings.discoveredUserTooling = {
mcpServers: [
{
id: 'discovered-remote',
name: 'Discovered Remote',
transport: 'http',
url: 'https://example.com/mcp',
headers: { 'X-Test': '1' },
tools: [],
scope: 'user',
scannerId: 'copilot-user-mcp',
sourcePath: 'C:\\Users\\tester\\.copilot\\mcp.json',
sourceLabel: '~\\.copilot\\mcp.json',
fingerprint: 'remote-fingerprint',
status: 'accepted',
},
],
lastScannedAt: TIMESTAMP,
};
workspace.settings.tooling.mcpServers = [
{
id: 'manual-remote',
name: 'Manual Remote',
transport: 'http',
url: 'https://example.com/mcp',
headers: { Authorization: 'Bearer token' },
tools: [],
createdAt: TIMESTAMP,
updatedAt: TIMESTAMP,
},
];
probeResults = [
{
serverId: 'manual-remote',
serverName: 'Manual Remote',
status: 'success',
tools: [{ name: 'manual.remote' }],
},
{
serverId: 'discovered-remote',
serverName: 'Discovered Remote',
status: 'success',
tools: [{ name: 'discovered.remote' }],
},
];
const { service, snapshots } = createService(workspace);
await (
service as unknown as {
reprobeServerByUrl: (serverUrl: string) => Promise<void>;
}
).reprobeServerByUrl('https://example.com/mcp');
expect(probeCalls).toEqual([[
'manual-remote',
'discovered-remote',
]]);
expect(snapshots.map((snapshot) => snapshot.mcpProbingServerIds)).toEqual([
['manual-remote', 'discovered-remote'],
['discovered-remote'],
undefined,
]);
expect(workspace.settings.tooling.mcpServers[0]?.probedTools).toEqual([
{ name: 'manual.remote' },
]);
expect(workspace.settings.discoveredUserTooling.mcpServers[0]?.probedTools).toEqual([
{ name: 'discovered.remote' },
]);
});
});
@@ -0,0 +1,244 @@
import { describe, expect, mock, test } from 'bun:test';
import type { RunTurnCommand } from '@shared/contracts/sidecar';
import type { PatternDefinition } from '@shared/domain/pattern';
import type { ProjectRecord } from '@shared/domain/project';
import type { SessionRecord } from '@shared/domain/session';
import { createWorkspaceSeed, type WorkspaceState } from '@shared/domain/workspace';
const TIMESTAMP = '2026-03-28T00:00:00.000Z';
mock.module('electron', () => {
const electronMock = {
app: {
isPackaged: false,
getAppPath: () => 'C:\\workspace\\personal\\repositories\\aryx',
getPath: () => 'C:\\workspace\\personal\\repositories\\aryx\\tests\\fixtures',
},
dialog: {
showOpenDialog: async () => ({ canceled: true, filePaths: [] }),
},
shell: {
openPath: async () => '',
},
};
return {
...electronMock,
default: electronMock,
};
});
mock.module('keytar', () => ({
default: {
getPassword: async () => null,
setPassword: async () => undefined,
deletePassword: async () => false,
},
}));
const { AryxAppService } = await import('@main/AryxAppService');
function createProject(overrides?: Partial<ProjectRecord>): ProjectRecord {
return {
id: 'project-alpha',
name: 'alpha',
path: 'C:\\workspace\\alpha',
addedAt: TIMESTAMP,
...overrides,
};
}
function createSession(projectId: string, patternId: string, overrides?: Partial<SessionRecord>): SessionRecord {
return {
id: 'session-alpha',
projectId,
patternId,
title: 'Alpha session',
createdAt: TIMESTAMP,
updatedAt: TIMESTAMP,
status: 'idle',
messages: [],
runs: [],
...overrides,
};
}
function createService(
workspace: WorkspaceState,
pattern: PatternDefinition,
options?: {
captureRunTurn?: (command: RunTurnCommand) => void;
},
): InstanceType<typeof AryxAppService> {
const service = new AryxAppService();
const internals = service as unknown as Record<string, unknown>;
internals.loadWorkspace = async () => workspace;
internals.persistAndBroadcast = async (nextWorkspace: WorkspaceState) => nextWorkspace;
internals.buildEffectivePattern = async () => pattern;
internals.awaitFinalResponseApproval = async () => undefined;
internals.finalizeTurn = () => undefined;
internals.emitSessionEvent = () => undefined;
internals.pruneUnavailableApprovalTools = async () => false;
internals.pruneUnavailableSessionToolingSelections = () => false;
(
service as unknown as {
sidecar: {
runTurn: (command: RunTurnCommand) => Promise<[]>;
resolveApproval: () => Promise<void>;
};
}
).sidecar = {
runTurn: async (command) => {
options?.captureRunTurn?.(command);
return [];
},
resolveApproval: async () => undefined,
};
return service;
}
describe('AryxAppService project customization', () => {
test('sendSessionMessage injects project instructions and enabled project agent profiles', async () => {
const workspace = createWorkspaceSeed();
const basePattern = workspace.patterns.find((candidate) => candidate.mode === 'single');
if (!basePattern) {
throw new Error('Expected a single-agent pattern in the workspace seed.');
}
const pattern: PatternDefinition = {
...basePattern,
agents: [
{
...basePattern.agents[0]!,
copilot: {
customAgents: [
{
name: 'reviewer',
prompt: 'Built-in reviewer prompt.',
},
],
},
},
],
};
const project = createProject({
customization: {
instructions: [
{
id: 'instruction-repo',
sourcePath: '.github\\copilot-instructions.md',
content: 'Use TypeScript.',
},
{
id: 'instruction-agents',
sourcePath: 'AGENTS.md',
content: 'Prefer focused tests.',
},
],
agentProfiles: [
{
id: 'agent-reviewer',
name: 'reviewer',
prompt: 'Project reviewer prompt.',
sourcePath: '.github\\agents\\reviewer.agent.md',
enabled: true,
},
{
id: 'agent-readme',
name: 'readme-specialist',
description: 'Documentation specialist',
tools: ['read', 'edit'],
prompt: 'Focus on README improvements.',
sourcePath: '.github\\agents\\readme-specialist.agent.md',
enabled: true,
},
{
id: 'agent-disabled',
name: 'disabled-specialist',
prompt: 'Should never be injected.',
sourcePath: '.github\\agents\\disabled-specialist.agent.md',
enabled: false,
},
],
promptFiles: [],
lastScannedAt: TIMESTAMP,
},
});
const session = createSession(project.id, pattern.id);
workspace.projects = [project];
workspace.sessions = [session];
workspace.selectedProjectId = project.id;
workspace.selectedPatternId = pattern.id;
workspace.selectedSessionId = session.id;
let command: RunTurnCommand | undefined;
const service = createService(workspace, pattern, {
captureRunTurn: (capturedCommand) => {
command = capturedCommand;
},
});
await service.sendSessionMessage(session.id, 'Use the repository guidance.');
expect(command?.projectInstructions).toBe('Use TypeScript.\n\nPrefer focused tests.');
expect(command?.pattern.agents[0]?.copilot?.customAgents).toEqual([
{
name: 'reviewer',
prompt: 'Built-in reviewer prompt.',
},
{
name: 'readme-specialist',
description: 'Documentation specialist',
tools: ['read', 'edit'],
prompt: 'Focus on README improvements.',
infer: undefined,
},
]);
});
test('setProjectAgentProfileEnabled persists the updated enabled state', async () => {
const workspace = createWorkspaceSeed();
const pattern = workspace.patterns.find((candidate) => candidate.mode === 'single');
if (!pattern) {
throw new Error('Expected a single-agent pattern in the workspace seed.');
}
const project = createProject({
customization: {
instructions: [],
agentProfiles: [
{
id: 'agent-readme',
name: 'readme-specialist',
prompt: 'Focus on docs.',
sourcePath: '.github\\agents\\readme-specialist.agent.md',
enabled: true,
},
],
promptFiles: [],
lastScannedAt: TIMESTAMP,
},
});
const session = createSession(project.id, pattern.id);
workspace.projects = [project];
workspace.sessions = [session];
const service = createService(workspace, pattern);
const updated = await service.setProjectAgentProfileEnabled(project.id, 'agent-readme', false);
expect(updated.projects[0]?.customization?.agentProfiles).toEqual([
{
id: 'agent-readme',
name: 'readme-specialist',
prompt: 'Focus on docs.',
sourcePath: '.github\\agents\\readme-specialist.agent.md',
enabled: false,
},
]);
});
});
+189
View File
@@ -0,0 +1,189 @@
import { describe, expect, mock, test } from 'bun:test';
import type { ProjectRecord } from '@shared/domain/project';
import type { TerminalSnapshot } from '@shared/domain/terminal';
import type { SessionRecord } from '@shared/domain/session';
import { createWorkspaceSeed, type WorkspaceState } from '@shared/domain/workspace';
const TIMESTAMP = '2026-03-28T00:00:00.000Z';
mock.module('electron', () => {
const electronMock = {
app: {
isPackaged: false,
getAppPath: () => 'C:\\workspace\\personal\\repositories\\aryx',
getPath: () => 'C:\\workspace\\personal\\repositories\\aryx\\tests\\fixtures',
},
dialog: {
showOpenDialog: async () => ({ canceled: true, filePaths: [] }),
},
shell: {
openPath: async () => '',
},
};
return {
...electronMock,
default: electronMock,
};
});
mock.module('keytar', () => ({
default: {
getPassword: async () => null,
setPassword: async () => undefined,
deletePassword: async () => false,
},
}));
const { AryxAppService } = await import('@main/AryxAppService');
function createProject(overrides?: Partial<ProjectRecord>): ProjectRecord {
return {
id: 'project-1',
name: 'Project One',
path: 'C:\\workspace\\project-one',
addedAt: TIMESTAMP,
...overrides,
};
}
function createSession(patternId: string, overrides?: Partial<SessionRecord>): SessionRecord {
return {
id: 'session-1',
projectId: 'project-1',
patternId,
title: 'Terminal Session',
createdAt: TIMESTAMP,
updatedAt: TIMESTAMP,
status: 'idle',
messages: [],
runs: [],
...overrides,
};
}
function createTerminalSnapshot(overrides?: Partial<TerminalSnapshot>): TerminalSnapshot {
return {
cwd: 'C:\\workspace\\project-one',
shell: 'PowerShell',
pid: 100,
cols: 80,
rows: 24,
...overrides,
};
}
function createService(workspace: WorkspaceState, terminalSnapshot = createTerminalSnapshot()) {
let saveCalls = 0;
const terminalCreateCwds: string[] = [];
const terminalRestartCwds: string[] = [];
const writes: string[] = [];
const resizes: Array<{ cols: number; rows: number }> = [];
let killCalls = 0;
const service = new AryxAppService();
const internals = service as unknown as Record<string, unknown>;
internals.workspaceRepository = {
load: async () => workspace,
save: async () => {
saveCalls += 1;
},
};
internals.syncUserDiscoveredTooling = async () => false;
internals.syncProjectDiscoveredTooling = async () => false;
internals.syncProjectCustomization = async () => false;
internals.pruneUnavailableSessionToolingSelections = () => false;
internals.pruneUnavailableApprovalTools = async () => false;
internals.didScheduleInitialProjectGitRefresh = true;
internals.ptyManager = {
create: async (cwd: string) => {
terminalCreateCwds.push(cwd);
return { ...terminalSnapshot, cwd };
},
restart: async (cwd: string) => {
terminalRestartCwds.push(cwd);
return { ...terminalSnapshot, cwd };
},
kill: () => {
killCalls += 1;
},
write: (data: string) => {
writes.push(data);
},
resize: (cols: number, rows: number) => {
resizes.push({ cols, rows });
},
getSnapshot: () => terminalSnapshot,
dispose: () => undefined,
on: () => internals.ptyManager,
};
return {
service,
getSaveCalls: () => saveCalls,
terminalCreateCwds,
terminalRestartCwds,
writes,
resizes,
getKillCalls: () => killCalls,
};
}
describe('AryxAppService terminal integration', () => {
test('uses the selected session cwd when creating and restarting the terminal', async () => {
const workspace = createWorkspaceSeed();
const pattern = workspace.patterns[0];
if (!pattern) {
throw new Error('Expected a seeded pattern.');
}
workspace.projects = [createProject()];
workspace.sessions = [createSession(pattern.id, { cwd: 'C:\\workspace\\scratchpad\\session-1' })];
workspace.selectedProjectId = 'project-1';
workspace.selectedSessionId = 'session-1';
const { service, terminalCreateCwds, terminalRestartCwds } = createService(workspace);
await service.createTerminal();
await service.restartTerminal();
expect(terminalCreateCwds).toEqual(['C:\\workspace\\scratchpad\\session-1']);
expect(terminalRestartCwds).toEqual(['C:\\workspace\\scratchpad\\session-1']);
});
test('falls back to the selected project path and delegates terminal controls', async () => {
const workspace = createWorkspaceSeed();
workspace.projects = [createProject()];
workspace.selectedProjectId = 'project-1';
const { service, terminalCreateCwds, writes, resizes, getKillCalls } = createService(workspace);
await expect(service.describeTerminal()).resolves.toEqual(createTerminalSnapshot());
await service.createTerminal();
service.writeTerminal('dir\r');
service.resizeTerminal(120, 40);
await service.killTerminal();
expect(terminalCreateCwds).toEqual(['C:\\workspace\\project-one']);
expect(writes).toEqual(['dir\r']);
expect(resizes).toEqual([{ cols: 120, rows: 40 }]);
expect(getKillCalls()).toBe(1);
});
test('normalizes and persists terminal height settings', async () => {
const workspace = createWorkspaceSeed();
const { service, getSaveCalls } = createService(workspace);
await service.setTerminalHeight(240.4);
expect(workspace.settings.terminalHeight).toBe(240);
expect(getSaveCalls()).toBe(1);
await service.setTerminalHeight(240);
expect(getSaveCalls()).toBe(1);
await service.setTerminalHeight(0);
expect(workspace.settings.terminalHeight).toBeUndefined();
expect(getSaveCalls()).toBe(2);
});
});
+160
View File
@@ -0,0 +1,160 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { ProjectCustomizationScanner } from '@main/services/customizationScanner';
const temporaryPaths: string[] = [];
afterEach(async () => {
await Promise.all(
temporaryPaths.splice(0).map((path) => rm(path, { recursive: true, force: true })),
);
});
async function createTempDirectory(): Promise<string> {
const directory = await mkdtemp(join(tmpdir(), 'aryx-customization-scanner-'));
temporaryPaths.push(directory);
return directory;
}
describe('ProjectCustomizationScanner', () => {
test('discovers project instructions, custom agents, and prompt files', async () => {
const projectPath = await createTempDirectory();
await mkdir(join(projectPath, '.github', 'agents'), { recursive: true });
await mkdir(join(projectPath, '.github', 'prompts'), { recursive: true });
await writeFile(
join(projectPath, '.github', 'copilot-instructions.md'),
'# Repo instructions\nUse TypeScript.\n',
'utf8',
);
await writeFile(
join(projectPath, 'AGENTS.md'),
'# Agent guidance\nPrefer clear tests.\n',
'utf8',
);
await writeFile(
join(projectPath, '.github', 'agents', 'readme-specialist.agent.md'),
`---
name: readme-specialist
description: README specialist
tools:
- read
- edit
infer: true
mcp-servers:
docs-mcp:
type: local
command: node
args:
- docs-server.js
---
Focus on repository documentation only.
`,
'utf8',
);
await writeFile(
join(projectPath, '.github', 'prompts', 'explain-code.prompt.md'),
`---
agent: agent
description: Generate a clear explanation
---
Explain the following code:
\${input:code:Paste your code here}
Audience: \${input:audience:Who is this for?}
`,
'utf8',
);
const scanned = await new ProjectCustomizationScanner().scanProject(projectPath);
expect(scanned.instructions).toEqual([
{
id: expect.any(String),
sourcePath: '.github\\copilot-instructions.md',
content: '# Repo instructions\nUse TypeScript.',
},
{
id: expect.any(String),
sourcePath: 'AGENTS.md',
content: '# Agent guidance\nPrefer clear tests.',
},
]);
expect(scanned.agentProfiles).toEqual([
{
id: expect.any(String),
name: 'readme-specialist',
description: 'README specialist',
tools: ['read', 'edit'],
prompt: 'Focus on repository documentation only.',
infer: true,
mcpServers: {
'docs-mcp': {
args: ['docs-server.js'],
command: 'node',
type: 'local',
},
},
sourcePath: '.github\\agents\\readme-specialist.agent.md',
enabled: true,
},
]);
expect(scanned.promptFiles).toEqual([
{
id: expect.any(String),
name: 'explain-code',
description: 'Generate a clear explanation',
agent: 'agent',
template: 'Explain the following code:\n${input:code:Paste your code here}\nAudience: ${input:audience:Who is this for?}',
variables: [
{ name: 'code', placeholder: 'Paste your code here' },
{ name: 'audience', placeholder: 'Who is this for?' },
],
sourcePath: '.github\\prompts\\explain-code.prompt.md',
},
]);
expect(scanned.lastScannedAt).toEqual(expect.any(String));
});
test('retains the previous parsed agent profile when frontmatter becomes malformed', async () => {
const projectPath = await createTempDirectory();
await mkdir(join(projectPath, '.github', 'agents'), { recursive: true });
const filePath = join(projectPath, '.github', 'agents', 'reviewer.agent.md');
await writeFile(
filePath,
`---
name: reviewer
description: Review specialist
tools: [read, search]
---
Review code changes carefully.
`,
'utf8',
);
const scanner = new ProjectCustomizationScanner();
const firstScan = await scanner.scanProject(projectPath);
const previousState = {
...firstScan,
agentProfiles: firstScan.agentProfiles.map((profile) => ({ ...profile, enabled: false })),
};
await writeFile(
filePath,
`---
name: [reviewer
description: broken yaml
---
This should not replace the previous state.
`,
'utf8',
);
const secondScan = await scanner.scanProject(projectPath, previousState);
expect(secondScan.agentProfiles).toEqual(previousState.agentProfiles);
});
});
+23 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test';
import { buildWellKnownUrl, buildWellKnownUrlFallback } from '@main/services/mcpTokenStore';
import { buildWellKnownUrl, buildWellKnownUrlFallback, buildWellKnownUrlOriginOnly } from '@main/services/mcpTokenStore';
describe('buildWellKnownUrl', () => {
test('inserts well-known segment after origin for URL with path', () => {
@@ -50,3 +50,25 @@ describe('buildWellKnownUrlFallback', () => {
.toBe('https://auth.example.com/.well-known/oauth-authorization-server');
});
});
describe('buildWellKnownUrlOriginOnly', () => {
test('strips path and returns origin-only well-known URL', () => {
expect(buildWellKnownUrlOriginOnly('https://eschat.microsoft.com/mcp', 'oauth-protected-resource'))
.toBe('https://eschat.microsoft.com/.well-known/oauth-protected-resource');
});
test('handles multi-level path', () => {
expect(buildWellKnownUrlOriginOnly('https://example.com/v1/mcp/api', 'oauth-protected-resource'))
.toBe('https://example.com/.well-known/oauth-protected-resource');
});
test('matches RFC URL when base has no path', () => {
expect(buildWellKnownUrlOriginOnly('https://auth.example.com/', 'oauth-authorization-server'))
.toBe('https://auth.example.com/.well-known/oauth-authorization-server');
});
test('handles URL with port', () => {
expect(buildWellKnownUrlOriginOnly('https://mcp.example.com:8443/v1/', 'oauth-protected-resource'))
.toBe('https://mcp.example.com:8443/.well-known/oauth-protected-resource');
});
});
+133
View File
@@ -0,0 +1,133 @@
import { beforeEach, describe, expect, mock, test } from 'bun:test';
const commandDelaysMs = new Map<string, number>();
let activeListTools = 0;
let maxActiveListTools = 0;
class FakeStdioClientTransport {
readonly command: string;
readonly args?: string[];
readonly env?: Record<string, string>;
readonly cwd?: string;
readonly stderr?: 'ignore';
onmessage?: (message: unknown) => void;
constructor(options: {
command: string;
args?: string[];
env?: Record<string, string>;
cwd?: string;
stderr?: 'ignore';
}) {
this.command = options.command;
this.args = options.args;
this.env = options.env;
this.cwd = options.cwd;
this.stderr = options.stderr;
}
async send(_message: unknown): Promise<void> {}
}
class FakeSSEClientTransport {
onmessage?: (message: unknown) => void;
constructor(_url: URL, _options?: unknown) {}
async send(_message: unknown): Promise<void> {}
}
class FakeStreamableHTTPClientTransport {
onmessage?: (message: unknown) => void;
constructor(_url: URL, _options?: unknown) {}
async send(_message: unknown): Promise<void> {}
}
class FakeClient {
private transport?: FakeStdioClientTransport;
constructor(_clientInfo: unknown, _options: unknown) {}
async connect(transport: FakeStdioClientTransport): Promise<void> {
this.transport = transport;
}
async listTools(): Promise<{ tools: Array<{ name: string }> }> {
const command = this.transport?.command;
if (!command) {
throw new Error('Expected a command for the fake MCP transport.');
}
activeListTools += 1;
maxActiveListTools = Math.max(maxActiveListTools, activeListTools);
await new Promise((resolve) => setTimeout(resolve, commandDelaysMs.get(command) ?? 0));
activeListTools -= 1;
return {
tools: [{ name: `${command}.tool` }],
};
}
async close(): Promise<void> {}
}
mock.module('@modelcontextprotocol/sdk/client/index.js', () => ({
Client: FakeClient,
}));
mock.module('@modelcontextprotocol/sdk/client/stdio.js', () => ({
StdioClientTransport: FakeStdioClientTransport,
}));
mock.module('@modelcontextprotocol/sdk/client/sse.js', () => ({
SSEClientTransport: FakeSSEClientTransport,
}));
mock.module('@modelcontextprotocol/sdk/client/streamableHttp.js', () => ({
StreamableHTTPClientTransport: FakeStreamableHTTPClientTransport,
}));
const { probeServers } = await import('../../src/main/services/mcpToolProber');
const TIMESTAMP = '2026-03-28T00:00:00.000Z';
beforeEach(() => {
commandDelaysMs.clear();
activeListTools = 0;
maxActiveListTools = 0;
});
describe('probeServers', () => {
test('fires onResult as probes finish while preserving input order and concurrency limit', async () => {
const servers = Array.from({ length: 7 }, (_, index) => ({
id: `server-${index}`,
name: `Server ${index}`,
transport: 'local' as const,
command: `cmd-${index}`,
args: [] as string[],
tools: [] as string[],
createdAt: TIMESTAMP,
updatedAt: TIMESTAMP,
}));
const delays = [70, 60, 50, 40, 30, 20, 10];
for (const [index, server] of servers.entries()) {
commandDelaysMs.set(server.command, delays[index] ?? 0);
}
const callbackOrder: string[] = [];
const results = await probeServers(servers, undefined, (result) => {
callbackOrder.push(result.serverId);
});
expect(results.map((result) => result.serverId)).toEqual(servers.map((server) => server.id));
expect(results.map((result) => result.tools[0]?.name)).toEqual(
servers.map((server) => `${server.command}.tool`),
);
expect(callbackOrder).not.toEqual(servers.map((server) => server.id));
expect([...callbackOrder].sort()).toEqual(servers.map((server) => server.id).sort());
expect(maxActiveListTools).toBe(5);
});
});
+209
View File
@@ -0,0 +1,209 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { TerminalExitInfo, TerminalSnapshot } from '@shared/domain/terminal';
import { PtyManager } from '@main/services/ptyManager';
class FakePty {
readonly pid: number;
readonly writes: string[] = [];
readonly resizeCalls: Array<{ cols: number; rows: number }> = [];
killCalls = 0;
private readonly dataListeners = new Set<(data: string) => void>();
private readonly exitListeners = new Set<(event: TerminalExitInfo) => void>();
constructor(pid: number) {
this.pid = pid;
}
write(data: string): void {
this.writes.push(data);
}
resize(cols: number, rows: number): void {
this.resizeCalls.push({ cols, rows });
}
kill(): void {
this.killCalls += 1;
this.emitExit({ exitCode: 0 });
}
onData(listener: (data: string) => void): { dispose(): void } {
this.dataListeners.add(listener);
return {
dispose: () => {
this.dataListeners.delete(listener);
},
};
}
onExit(listener: (event: TerminalExitInfo) => void): { dispose(): void } {
this.exitListeners.add(listener);
return {
dispose: () => {
this.exitListeners.delete(listener);
},
};
}
emitData(data: string): void {
for (const listener of this.dataListeners) {
listener(data);
}
}
emitExit(event: TerminalExitInfo): void {
for (const listener of this.exitListeners) {
listener(event);
}
}
}
const tempDirectories: string[] = [];
async function createTempDirectory(): Promise<string> {
const path = await mkdtemp(join(tmpdir(), 'aryx-pty-'));
tempDirectories.push(path);
return path;
}
afterEach(async () => {
while (tempDirectories.length > 0) {
const path = tempDirectories.pop();
if (path) {
await rm(path, { force: true, recursive: true });
}
}
});
describe('PtyManager', () => {
test('prefers PowerShell on Windows when available', async () => {
const cwd = await createTempDirectory();
const spawnCalls: Array<{ file: string; args: string[]; options: { cwd: string } }> = [];
const pty = new FakePty(101);
const manager = new PtyManager({
platform: 'win32',
env: { SystemRoot: 'C:\\Windows' },
commandExists: async (command) => command === 'pwsh.exe',
spawnPty: async (file, args, options) => {
spawnCalls.push({ file, args, options });
return pty;
},
});
const snapshot = await manager.create(cwd);
expect(spawnCalls).toHaveLength(1);
expect(spawnCalls[0]?.file).toBe('pwsh.exe');
expect(spawnCalls[0]?.args).toEqual(['-NoLogo']);
expect(spawnCalls[0]?.options.cwd).toBe(cwd);
expect(snapshot).toEqual({
cwd,
shell: 'PowerShell',
pid: 101,
cols: 80,
rows: 24,
} satisfies TerminalSnapshot);
});
test('forwards data, writes input, and tracks resized dimensions', async () => {
const cwd = await createTempDirectory();
const pty = new FakePty(202);
const chunks: string[] = [];
const manager = new PtyManager({
platform: 'linux',
env: { SHELL: '/bin/zsh', PATH: '/bin' },
commandExists: async () => true,
spawnPty: async () => pty,
});
manager.on('data', (data) => {
chunks.push(data);
});
await manager.create(cwd);
pty.emitData('$ ready');
manager.write('npm test\r');
manager.resize(120.2, 41.6);
expect(chunks).toEqual(['$ ready']);
expect(pty.writes).toEqual(['npm test\r']);
expect(pty.resizeCalls).toEqual([{ cols: 120, rows: 42 }]);
expect(manager.getSnapshot()).toEqual({
cwd,
shell: 'zsh',
pid: 202,
cols: 120,
rows: 42,
} satisfies TerminalSnapshot);
});
test('kills the active terminal, emits exit, and clears the snapshot', async () => {
const cwd = await createTempDirectory();
const exits: TerminalExitInfo[] = [];
const pty = new FakePty(303);
const manager = new PtyManager({
platform: 'linux',
env: { SHELL: '/bin/bash', PATH: '/bin' },
commandExists: async () => true,
spawnPty: async () => pty,
});
manager.on('exit', (event) => {
exits.push(event);
});
await manager.create(cwd);
manager.kill();
expect(exits).toEqual([{ exitCode: 0 }]);
expect(manager.getSnapshot()).toBeUndefined();
});
test('restarts without forwarding the replaced terminal exit event', async () => {
const cwd = await createTempDirectory();
const exits: TerminalExitInfo[] = [];
const ptys = [new FakePty(404), new FakePty(405)];
let spawnIndex = 0;
const manager = new PtyManager({
platform: 'linux',
env: { SHELL: '/bin/bash', PATH: '/bin' },
commandExists: async () => true,
spawnPty: async () => ptys[spawnIndex++]!,
});
manager.on('exit', (event) => {
exits.push(event);
});
await manager.create(cwd);
manager.resize(132, 36);
const restarted = await manager.restart(cwd);
expect(ptys[0].killCalls).toBe(1);
expect(exits).toEqual([]);
expect(restarted).toEqual({
cwd,
shell: 'bash',
pid: 405,
cols: 132,
rows: 36,
} satisfies TerminalSnapshot);
});
test('throws when the working directory does not exist', async () => {
const manager = new PtyManager({
platform: 'linux',
env: { SHELL: '/bin/bash', PATH: '/bin' },
commandExists: async () => true,
spawnPty: async () => new FakePty(500),
});
await expect(manager.create('C:\\workspace\\personal\\repositories\\aryx\\does-not-exist'))
.rejects
.toThrow('Terminal working directory');
});
});
@@ -87,4 +87,18 @@ describe('WorkspaceRepository scratchpad migration', () => {
const persisted = JSON.parse(await readFile(workspaceFilePath, 'utf8')) as WorkspaceState;
expect(persisted.sessions[0]?.cwd).toBe(expectedSessionPath);
});
test('strips runtime MCP probing state before persisting workspace data', async () => {
const workspaceFilePath = join(USER_DATA_PATH, 'workspace.json');
await mkdir(USER_DATA_PATH, { recursive: true });
const repository = new WorkspaceRepository();
const workspace = createStoredWorkspace();
workspace.mcpProbingServerIds = ['server-a', 'server-b'];
await repository.save(workspace);
const persisted = JSON.parse(await readFile(workspaceFilePath, 'utf8')) as WorkspaceState;
expect('mcpProbingServerIds' in persisted).toBe(false);
});
});
+132
View File
@@ -1,12 +1,26 @@
import { describe, expect, test } from 'bun:test';
import { createHeadlessEditor } from '@lexical/headless';
import { $convertFromMarkdownString, $convertToMarkdownString } from '@lexical/markdown';
import {
$createCodeNode,
$createCodeHighlightNode,
CodeNode,
} from '@lexical/code';
import {
$createLineBreakNode,
$createRangeSelection,
$getRoot,
$setSelection,
} from 'lexical';
import {
findCodeNodeSelectionPoint,
getCodeNodeAbsoluteOffset,
inspectMarkdownPaste,
markdownEditorNamespace,
markdownEditorNodes,
markdownEditorTransformers,
restoreCodeNodeSelection,
} from '@renderer/lib/markdownEditor';
function roundTripMarkdown(markdown: string): string {
@@ -71,3 +85,121 @@ describe('markdown editor contract', () => {
});
});
});
/* ── Code-node selection helpers ──────────────────────── */
function createTestEditor() {
return createHeadlessEditor({
namespace: markdownEditorNamespace,
nodes: [...markdownEditorNodes],
onError(error) {
throw error;
},
});
}
describe('code-node selection helpers', () => {
test('findCodeNodeSelectionPoint targets CodeNode (not LineBreakNode) for linebreak-only content', () => {
const editor = createTestEditor();
editor.update(() => {
const codeNode = $createCodeNode();
codeNode.append($createLineBreakNode());
$getRoot().clear().append(codeNode);
// target=0 → before the LineBreakNode
const before = findCodeNodeSelectionPoint(codeNode, 0);
expect(before.key).toBe(codeNode.getKey());
expect(before.offset).toBe(0);
expect(before.type).toBe('element');
// target=1 → after the LineBreakNode (fallback)
const after = findCodeNodeSelectionPoint(codeNode, 1);
expect(after.key).toBe(codeNode.getKey());
expect(after.offset).toBe(1);
expect(after.type).toBe('element');
}, { discrete: true });
});
test('findCodeNodeSelectionPoint targets text nodes correctly', () => {
const editor = createTestEditor();
editor.update(() => {
const codeNode = $createCodeNode();
codeNode.append($createCodeHighlightNode('hello'));
codeNode.append($createLineBreakNode());
codeNode.append($createCodeHighlightNode('world'));
$getRoot().clear().append(codeNode);
// target=3 → inside "hello"
const mid = findCodeNodeSelectionPoint(codeNode, 3);
expect(mid.key).toBe(codeNode.getChildren()[0].getKey());
expect(mid.offset).toBe(3);
expect(mid.type).toBe('text');
// target=5 → end of "hello" (text boundary)
const endHello = findCodeNodeSelectionPoint(codeNode, 5);
expect(endHello.key).toBe(codeNode.getChildren()[0].getKey());
expect(endHello.offset).toBe(5);
expect(endHello.type).toBe('text');
// target=6 → after the LineBreakNode → start of "world"
const startWorld = findCodeNodeSelectionPoint(codeNode, 6);
expect(startWorld.key).toBe(codeNode.getChildren()[2].getKey());
expect(startWorld.offset).toBe(0);
expect(startWorld.type).toBe('text');
}, { discrete: true });
});
test('findCodeNodeSelectionPoint handles empty CodeNode', () => {
const editor = createTestEditor();
editor.update(() => {
const codeNode = $createCodeNode();
$getRoot().clear().append(codeNode);
const point = findCodeNodeSelectionPoint(codeNode, 0);
expect(point.key).toBe(codeNode.getKey());
expect(point.offset).toBe(0);
expect(point.type).toBe('element');
}, { discrete: true });
});
test('restoreCodeNodeSelection does not throw on linebreak-only CodeNode', () => {
const editor = createTestEditor();
editor.update(() => {
const codeNode = $createCodeNode();
codeNode.append($createLineBreakNode());
$getRoot().clear().append(codeNode);
// Create a valid selection so restoreCodeNodeSelection has one to update
const sel = $createRangeSelection();
sel.anchor.set(codeNode.getKey(), 0, 'element');
sel.focus.set(codeNode.getKey(), 0, 'element');
$setSelection(sel);
// This would throw before the fix because findPoint returned a point
// targeting the LineBreakNode with type 'element'
expect(() => restoreCodeNodeSelection(codeNode, 1, 1)).not.toThrow();
}, { discrete: true });
});
test('getCodeNodeAbsoluteOffset computes character offsets correctly', () => {
const editor = createTestEditor();
editor.update(() => {
const codeNode = $createCodeNode();
const hello = $createCodeHighlightNode('hello');
const lb = $createLineBreakNode();
const world = $createCodeHighlightNode('world');
codeNode.append(hello, lb, world);
$getRoot().clear().append(codeNode);
expect(getCodeNodeAbsoluteOffset(codeNode, { key: hello.getKey(), offset: 0 })).toBe(0);
expect(getCodeNodeAbsoluteOffset(codeNode, { key: hello.getKey(), offset: 3 })).toBe(3);
expect(getCodeNodeAbsoluteOffset(codeNode, { key: lb.getKey(), offset: 0 })).toBe(5);
expect(getCodeNodeAbsoluteOffset(codeNode, { key: world.getKey(), offset: 2 })).toBe(8);
}, { discrete: true });
});
});
+148
View File
@@ -2,12 +2,18 @@ import { describe, expect, test } from 'bun:test';
import {
applySessionEventActivity,
applyAssistantUsageEvent,
buildAgentActivityRows,
formatAgentActivityLabel,
formatDuration,
formatNanoAiu,
formatTokenCount,
isAgentActivityActive,
isAgentActivityCompleted,
pruneSessionActivities,
pruneSessionRequestUsage,
type SessionActivityMap,
type SessionRequestUsageMap,
} from '@renderer/lib/sessionActivity';
import type { PatternDefinition } from '@shared/domain/pattern';
import type { SessionEventRecord } from '@shared/domain/event';
@@ -379,3 +385,145 @@ describe('session activity helpers', () => {
});
});
});
describe('assistant usage accumulator', () => {
function makeUsageEvent(overrides: Partial<SessionEventRecord> = {}): SessionEventRecord {
return {
sessionId: 'session-1',
kind: 'assistant-usage',
occurredAt: '2026-03-23T00:00:00.000Z',
agentId: 'architect',
agentName: 'Architect',
usageModel: 'gpt-5.4',
usageInputTokens: 1200,
usageOutputTokens: 300,
usageCost: 0.42,
usageDuration: 8200,
usageTotalNanoAiu: 1_200_000_000,
...overrides,
};
}
test('accumulates session-level totals from assistant-usage events', () => {
let state: SessionRequestUsageMap = {};
state = applyAssistantUsageEvent(state, makeUsageEvent());
state = applyAssistantUsageEvent(state, makeUsageEvent({
usageInputTokens: 800,
usageOutputTokens: 200,
usageCost: 0.28,
usageDuration: 5000,
usageTotalNanoAiu: 2_400_000_000,
}));
const usage = state['session-1']!;
expect(usage.requestCount).toBe(2);
expect(usage.totalInputTokens).toBe(2000);
expect(usage.totalOutputTokens).toBe(500);
expect(usage.totalCost).toBeCloseTo(0.70);
expect(usage.totalDurationMs).toBe(13200);
expect(usage.totalNanoAiu).toBe(2_400_000_000);
});
test('accumulates per-agent totals keyed by agentId', () => {
let state: SessionRequestUsageMap = {};
state = applyAssistantUsageEvent(state, makeUsageEvent({ agentId: 'architect' }));
state = applyAssistantUsageEvent(state, makeUsageEvent({
agentId: 'reviewer',
agentName: 'Reviewer',
usageInputTokens: 500,
usageOutputTokens: 100,
usageCost: 0.10,
usageDuration: 3000,
}));
state = applyAssistantUsageEvent(state, makeUsageEvent({
agentId: 'architect',
usageInputTokens: 600,
usageOutputTokens: 150,
usageCost: 0.20,
usageDuration: 4000,
}));
const usage = state['session-1']!;
expect(usage.perAgent['architect']!.requestCount).toBe(2);
expect(usage.perAgent['architect']!.inputTokens).toBe(1800);
expect(usage.perAgent['reviewer']!.requestCount).toBe(1);
expect(usage.perAgent['reviewer']!.inputTokens).toBe(500);
});
test('ignores non-assistant-usage events', () => {
const state: SessionRequestUsageMap = {};
const result = applyAssistantUsageEvent(state, {
sessionId: 'session-1',
kind: 'session-usage',
occurredAt: '2026-03-23T00:00:00.000Z',
tokenLimit: 100000,
currentTokens: 5000,
});
expect(result).toBe(state);
});
test('stores latest quota snapshots', () => {
const snapshots = {
premium_interactions: {
entitlementRequests: 50,
usedRequests: 12,
remainingPercentage: 76,
overage: 0,
overageAllowedWithExhaustedQuota: true,
resetDate: '2026-04-01T00:00:00Z',
},
};
let state: SessionRequestUsageMap = {};
state = applyAssistantUsageEvent(state, makeUsageEvent({ usageQuotaSnapshots: snapshots }));
expect(state['session-1']!.latestQuotaSnapshots).toEqual(snapshots);
});
test('prunes request usage for removed sessions', () => {
const current: SessionRequestUsageMap = {
'session-1': {
totalInputTokens: 1000,
totalOutputTokens: 200,
totalCost: 0.3,
totalDurationMs: 5000,
totalNanoAiu: 1_000_000_000,
requestCount: 1,
perAgent: {},
},
'session-2': {
totalInputTokens: 500,
totalOutputTokens: 100,
totalCost: 0.1,
totalDurationMs: 2000,
totalNanoAiu: 500_000_000,
requestCount: 1,
perAgent: {},
},
};
const pruned = pruneSessionRequestUsage(current, ['session-2']);
expect(pruned).toEqual({ 'session-2': current['session-2'] });
expect(pruned).not.toBe(current);
});
});
describe('usage formatting helpers', () => {
test('formatTokenCount formats values at different scales', () => {
expect(formatTokenCount(500)).toBe('500');
expect(formatTokenCount(1200)).toBe('1.2k');
expect(formatTokenCount(45300)).toBe('45.3k');
expect(formatTokenCount(1_500_000)).toBe('1.5M');
});
test('formatNanoAiu converts nano-AIU to human-readable', () => {
expect(formatNanoAiu(420_000_000)).toBe('0.42');
expect(formatNanoAiu(12_300_000_000)).toBe('12.3');
expect(formatNanoAiu(150_000_000_000)).toBe('150');
});
test('formatDuration formats milliseconds', () => {
expect(formatDuration(8200)).toBe('8.2s');
expect(formatDuration(150_000)).toBe('2.5m');
});
});
+40
View File
@@ -228,6 +228,46 @@ describe('session workspace helpers', () => {
expect(updated?.sessions[0].runs).toEqual([run]);
});
test('auto-completes previous pending assistant messages when a new message starts', () => {
const first = applySessionEventWorkspace(createWorkspace(), {
sessionId: 'session-1',
kind: 'message-delta',
occurredAt: '2026-03-23T00:00:01.000Z',
messageId: 'assistant-1',
authorName: 'Primary Agent',
contentDelta: 'Exploring the codebase...',
content: 'Exploring the codebase...',
} satisfies SessionEventRecord);
expect(first?.sessions[0].messages).toHaveLength(1);
expect(first?.sessions[0].messages[0]).toMatchObject({
id: 'assistant-1',
pending: true,
});
const second = applySessionEventWorkspace(first, {
sessionId: 'session-1',
kind: 'message-delta',
occurredAt: '2026-03-23T00:00:02.000Z',
messageId: 'assistant-2',
authorName: 'Primary Agent',
contentDelta: 'Still exploring...',
content: 'Still exploring...',
} satisfies SessionEventRecord);
expect(second?.sessions[0].messages).toHaveLength(2);
expect(second?.sessions[0].messages[0]).toMatchObject({
id: 'assistant-1',
content: 'Exploring the codebase...',
pending: false,
});
expect(second?.sessions[0].messages[1]).toMatchObject({
id: 'assistant-2',
content: 'Still exploring...',
pending: true,
});
});
test('ignores events for unknown sessions', () => {
const workspace = createWorkspace();
expect(
+246
View File
@@ -0,0 +1,246 @@
import { describe, expect, test } from 'bun:test';
import {
applySubagentEvent,
pruneSubagentMap,
type ActiveSubagentMap,
} from '@renderer/lib/subagentTracker';
import type { SessionEventRecord } from '@shared/domain/event';
function subagentStarted(overrides: Partial<SessionEventRecord> = {}): SessionEventRecord {
return {
sessionId: 'session-1',
kind: 'subagent',
occurredAt: '2026-03-28T10:00:00.000Z',
subagentEventKind: 'started',
customAgentName: 'explore',
customAgentDisplayName: 'Explore Agent',
customAgentDescription: 'Explores the codebase',
subagentToolCallId: 'tc-1',
subagentModel: 'claude-haiku-4.5',
...overrides,
};
}
function subagentCompleted(overrides: Partial<SessionEventRecord> = {}): SessionEventRecord {
return {
sessionId: 'session-1',
kind: 'subagent',
occurredAt: '2026-03-28T10:00:05.000Z',
subagentEventKind: 'completed',
customAgentName: 'explore',
customAgentDisplayName: 'Explore Agent',
subagentToolCallId: 'tc-1',
...overrides,
};
}
function subagentFailed(overrides: Partial<SessionEventRecord> = {}): SessionEventRecord {
return {
sessionId: 'session-1',
kind: 'subagent',
occurredAt: '2026-03-28T10:00:05.000Z',
subagentEventKind: 'failed',
customAgentName: 'explore',
customAgentDisplayName: 'Explore Agent',
subagentToolCallId: 'tc-1',
subagentError: 'Something went wrong',
...overrides,
};
}
function agentActivity(overrides: Partial<SessionEventRecord> = {}): SessionEventRecord {
return {
sessionId: 'session-1',
kind: 'agent-activity',
occurredAt: '2026-03-28T10:00:01.000Z',
activityType: 'thinking',
agentName: 'Explore Agent',
...overrides,
};
}
describe('subagent tracker', () => {
describe('applySubagentEvent', () => {
test('adds a running subagent on started event', () => {
const result = applySubagentEvent({}, subagentStarted());
const subagents = result['session-1'];
expect(subagents).toHaveLength(1);
expect(subagents![0]).toEqual(expect.objectContaining({
toolCallId: 'tc-1',
name: 'Explore Agent',
description: 'Explores the codebase',
model: 'claude-haiku-4.5',
status: 'running',
}));
});
test('marks subagent completed', () => {
let state: ActiveSubagentMap = {};
state = applySubagentEvent(state, subagentStarted());
state = applySubagentEvent(state, subagentCompleted());
const subagents = state['session-1'];
expect(subagents).toHaveLength(1);
expect(subagents![0]!.status).toBe('completed');
expect(subagents![0]!.activityLabel).toBe('Completed');
});
test('marks subagent failed with error', () => {
let state: ActiveSubagentMap = {};
state = applySubagentEvent(state, subagentStarted());
state = applySubagentEvent(state, subagentFailed());
const subagents = state['session-1'];
expect(subagents).toHaveLength(1);
expect(subagents![0]!.status).toBe('failed');
expect(subagents![0]!.error).toBe('Something went wrong');
});
test('tracks multiple subagents concurrently', () => {
let state: ActiveSubagentMap = {};
state = applySubagentEvent(state, subagentStarted({ subagentToolCallId: 'tc-1', customAgentDisplayName: 'Agent A' }));
state = applySubagentEvent(state, subagentStarted({ subagentToolCallId: 'tc-2', customAgentDisplayName: 'Agent B' }));
const subagents = state['session-1'];
expect(subagents).toHaveLength(2);
expect(subagents![0]!.name).toBe('Agent A');
expect(subagents![1]!.name).toBe('Agent B');
});
test('completes one subagent while another keeps running', () => {
let state: ActiveSubagentMap = {};
state = applySubagentEvent(state, subagentStarted({ subagentToolCallId: 'tc-1', customAgentDisplayName: 'Agent A' }));
state = applySubagentEvent(state, subagentStarted({ subagentToolCallId: 'tc-2', customAgentDisplayName: 'Agent B' }));
state = applySubagentEvent(state, subagentCompleted({ subagentToolCallId: 'tc-1' }));
const subagents = state['session-1'];
expect(subagents).toHaveLength(2);
expect(subagents![0]!.status).toBe('completed');
expect(subagents![1]!.status).toBe('running');
});
test('clears subagents when session goes idle', () => {
let state: ActiveSubagentMap = {};
state = applySubagentEvent(state, subagentStarted());
state = applySubagentEvent(state, {
sessionId: 'session-1',
kind: 'status',
occurredAt: '2026-03-28T10:00:10.000Z',
status: 'idle',
});
expect(state['session-1']).toBeUndefined();
});
test('returns same reference when idle event has no subagents', () => {
const state: ActiveSubagentMap = {};
const result = applySubagentEvent(state, {
sessionId: 'session-1',
kind: 'status',
occurredAt: '2026-03-28T10:00:10.000Z',
status: 'idle',
});
expect(result).toBe(state);
});
test('ignores unrelated event kinds', () => {
const state: ActiveSubagentMap = {};
const result = applySubagentEvent(state, {
sessionId: 'session-1',
kind: 'message-delta',
occurredAt: '2026-03-28T10:00:00.000Z',
contentDelta: 'hello',
});
expect(result).toBe(state);
});
test('updates activity label from agent-activity event', () => {
let state: ActiveSubagentMap = {};
state = applySubagentEvent(state, subagentStarted());
state = applySubagentEvent(state, agentActivity({
activityType: 'tool-calling',
toolName: 'grep',
}));
expect(state['session-1']![0]!.activityLabel).toBe('Using grep…');
});
test('updates activity label to thinking', () => {
let state: ActiveSubagentMap = {};
state = applySubagentEvent(state, subagentStarted());
state = applySubagentEvent(state, agentActivity({
activityType: 'thinking',
}));
expect(state['session-1']![0]!.activityLabel).toBe('Thinking…');
});
test('ignores agent-activity for non-matching agent name', () => {
let state: ActiveSubagentMap = {};
state = applySubagentEvent(state, subagentStarted());
const before = state;
state = applySubagentEvent(state, agentActivity({
agentName: 'Completely Different Agent',
activityType: 'thinking',
}));
expect(state).toBe(before);
});
test('does not update completed subagent from agent-activity', () => {
let state: ActiveSubagentMap = {};
state = applySubagentEvent(state, subagentStarted());
state = applySubagentEvent(state, subagentCompleted());
const before = state;
state = applySubagentEvent(state, agentActivity({
activityType: 'thinking',
}));
expect(state).toBe(before);
});
test('uses customAgentName when displayName is absent', () => {
const result = applySubagentEvent({}, subagentStarted({
customAgentDisplayName: undefined,
customAgentName: 'task-agent',
}));
expect(result['session-1']![0]!.name).toBe('task-agent');
});
test('uses toolCallId as key, falls back to customAgentName', () => {
const result = applySubagentEvent({}, subagentStarted({
subagentToolCallId: undefined,
customAgentName: 'fallback-key',
}));
expect(result['session-1']![0]!.toolCallId).toBe('fallback-key');
});
});
describe('pruneSubagentMap', () => {
test('removes entries for deleted sessions', () => {
const state: ActiveSubagentMap = {
'session-1': [{ toolCallId: 'tc-1', name: 'A', activityLabel: 'Working…', startedAt: '', status: 'running' }],
'session-2': [{ toolCallId: 'tc-2', name: 'B', activityLabel: 'Working…', startedAt: '', status: 'running' }],
};
const result = pruneSubagentMap(state, ['session-1']);
expect(result['session-1']).toBeDefined();
expect(result['session-2']).toBeUndefined();
});
test('returns same reference when nothing is pruned', () => {
const state: ActiveSubagentMap = {
'session-1': [],
};
const result = pruneSubagentMap(state, ['session-1']);
expect(result).toBe(state);
});
});
});
+46
View File
@@ -105,4 +105,50 @@ describe('discovered tooling helpers', () => {
expect(listPendingDiscoveredMcpServers(dismissed)).toEqual([]);
expect(dismissed.mcpServers[1]?.status).toBe('dismissed');
});
test('preserves probedTools when fingerprint is unchanged on re-scan', () => {
const probedTools = [
{ name: 'git_status', description: 'Get git status' },
{ name: 'git_diff', description: 'Get git diff' },
];
const current = {
mcpServers: [
createDiscoveredServer({
status: 'accepted',
probedTools,
}),
],
lastScannedAt: TIMESTAMP,
};
const merged = mergeDiscoveredToolingState(
current,
[createDiscoveredServer()],
'2026-03-25T01:00:00.000Z',
);
expect(merged.mcpServers[0]?.probedTools).toEqual(probedTools);
expect(merged.mcpServers[0]?.status).toBe('accepted');
});
test('drops probedTools when fingerprint changes on re-scan', () => {
const current = {
mcpServers: [
createDiscoveredServer({
status: 'accepted',
probedTools: [{ name: 'git_status' }],
}),
],
lastScannedAt: TIMESTAMP,
};
const merged = mergeDiscoveredToolingState(
current,
[createDiscoveredServer({ args: ['server.js', '--debug'] })],
'2026-03-25T01:00:00.000Z',
);
expect(merged.mcpServers[0]?.probedTools).toBeUndefined();
expect(merged.mcpServers[0]?.status).toBe('pending');
});
});
+280
View File
@@ -1,7 +1,10 @@
import { describe, expect, test } from 'bun:test';
import {
buildMcpServerApprovalKey,
groupApprovalToolsByProvider,
listApprovalToolDefinitions,
listApprovalToolNames,
normalizeWorkspaceSettings,
resolveProjectToolingSettings,
resolveToolLabel,
@@ -10,6 +13,7 @@ import {
validateMcpServerDefinition,
type LspProfileDefinition,
type McpServerDefinition,
type WorkspaceToolingSettings,
} from '@shared/domain/tooling';
const TIMESTAMP = '2026-03-23T00:00:00.000Z';
@@ -17,6 +21,7 @@ const TIMESTAMP = '2026-03-23T00:00:00.000Z';
describe('tooling settings helpers', () => {
test('normalizes persisted MCP and LSP definitions into trimmed stable settings', () => {
const workspaceSettings = normalizeWorkspaceSettings({
terminalHeight: 240.4,
tooling: {
mcpServers: [
{
@@ -60,6 +65,7 @@ describe('tooling settings helpers', () => {
expect(workspaceSettings).toEqual({
theme: 'dark',
terminalHeight: 240,
tooling: {
mcpServers: [
{
@@ -105,6 +111,11 @@ describe('tooling settings helpers', () => {
});
});
test('drops invalid persisted terminal height values', () => {
expect(normalizeWorkspaceSettings({ terminalHeight: 119 }).terminalHeight).toBeUndefined();
expect(normalizeWorkspaceSettings({ terminalHeight: Number.NaN }).terminalHeight).toBeUndefined();
});
test('validates required MCP transport settings', () => {
const localServer: McpServerDefinition = {
id: 'mcp-local',
@@ -378,3 +389,272 @@ describe('tooling settings helpers', () => {
});
});
});
describe('groupApprovalToolsByProvider', () => {
const TIMESTAMP = '2026-03-28T00:00:00.000Z';
function makeTooling(
mcpServers: McpServerDefinition[] = [],
lspProfiles: LspProfileDefinition[] = [],
): WorkspaceToolingSettings {
return { mcpServers, lspProfiles };
}
function makeMcpServer(id: string, name: string, tools: string[]): McpServerDefinition {
return { id, name, transport: 'local', command: 'node', args: [], tools, createdAt: TIMESTAMP, updatedAt: TIMESTAMP };
}
function makeLspProfile(id: string, name: string): LspProfileDefinition {
return { id, name, command: 'lsp-server', args: ['--stdio'], languageId: 'typescript', fileExtensions: ['.ts'], createdAt: TIMESTAMP, updatedAt: TIMESTAMP };
}
test('groups MCP tools by server', () => {
const tooling = makeTooling([
makeMcpServer('git', 'Git MCP', ['git.status', 'git.diff']),
makeMcpServer('fs', 'Filesystem', ['fs.read', 'fs.write']),
]);
const tools = listApprovalToolDefinitions(tooling);
const groups = groupApprovalToolsByProvider(tools, tooling);
const mcpGroups = groups.filter((g) => g.kind === 'mcp');
expect(mcpGroups.length).toBe(2);
const fsGroup = mcpGroups.find((g) => g.label === 'Filesystem');
expect(fsGroup).toBeDefined();
expect(fsGroup!.tools.map((t) => t.id).sort()).toEqual(['fs.read', 'fs.write']);
const gitGroup = mcpGroups.find((g) => g.label === 'Git MCP');
expect(gitGroup).toBeDefined();
expect(gitGroup!.tools.map((t) => t.id).sort()).toEqual(['git.diff', 'git.status']);
});
test('groups LSP tools by profile', () => {
const tooling = makeTooling([], [makeLspProfile('ts', 'TypeScript')]);
const tools = listApprovalToolDefinitions(tooling);
const groups = groupApprovalToolsByProvider(tools, tooling);
const lspGroups = groups.filter((g) => g.kind === 'lsp');
expect(lspGroups.length).toBe(1);
expect(lspGroups[0].label).toBe('TypeScript');
expect(lspGroups[0].tools.length).toBe(5);
});
test('keeps builtins in one group', () => {
const tooling = makeTooling();
const tools = listApprovalToolDefinitions(tooling);
const groups = groupApprovalToolsByProvider(tools, tooling);
const builtinGroups = groups.filter((g) => g.kind === 'builtin');
expect(builtinGroups.length).toBe(1);
expect(builtinGroups[0].label).toBe('Built-in');
expect(builtinGroups[0].tools.length).toBe(5);
});
test('multi-provider tools appear in all provider groups', () => {
const tooling = makeTooling([
makeMcpServer('git-a', 'Git A', ['git.status']),
makeMcpServer('git-b', 'Git B', ['git.status']),
]);
const tools = listApprovalToolDefinitions(tooling);
const groups = groupApprovalToolsByProvider(tools, tooling);
const mcpGroups = groups.filter((g) => g.kind === 'mcp');
expect(mcpGroups.length).toBe(2);
const gitA = mcpGroups.find((g) => g.label === 'Git A');
expect(gitA).toBeDefined();
expect(gitA!.tools.length).toBe(1);
expect(gitA!.tools[0].providerNames).toEqual(['Git A', 'Git B']);
const gitB = mcpGroups.find((g) => g.label === 'Git B');
expect(gitB).toBeDefined();
expect(gitB!.tools.length).toBe(1);
expect(gitB!.tools[0].id).toBe('git.status');
});
test('sorts builtin first, then MCP by name, then LSP by name', () => {
const tooling = makeTooling(
[makeMcpServer('z', 'Zebra', ['z.tool']), makeMcpServer('a', 'Alpha', ['a.tool'])],
[makeLspProfile('ts', 'TypeScript')],
);
const tools = listApprovalToolDefinitions(tooling);
const groups = groupApprovalToolsByProvider(tools, tooling);
const kindOrder = groups.map((g) => g.kind);
expect(kindOrder[0]).toBe('builtin');
const mcpIdx = kindOrder.indexOf('mcp');
const lspIdx = kindOrder.indexOf('lsp');
expect(mcpIdx).toBeLessThan(lspIdx);
const mcpLabels = groups.filter((g) => g.kind === 'mcp').map((g) => g.label);
expect(mcpLabels).toEqual(['Alpha', 'Zebra']);
});
test('creates groups with serverApprovalKey for MCP servers', () => {
const tooling = makeTooling([
makeMcpServer('git', 'Git MCP', ['git.status']),
]);
const tools = listApprovalToolDefinitions(tooling);
const groups = groupApprovalToolsByProvider(tools, tooling);
const mcpGroup = groups.find((g) => g.kind === 'mcp');
expect(mcpGroup).toBeDefined();
expect(mcpGroup!.serverApprovalKey).toBe('mcp_server:Git MCP');
});
test('creates groups for MCP servers with empty tools array', () => {
const tooling = makeTooling([
makeMcpServer('empty', 'Empty Server', []),
]);
const tools = listApprovalToolDefinitions(tooling);
const groups = groupApprovalToolsByProvider(tools, tooling);
const mcpGroups = groups.filter((g) => g.kind === 'mcp');
expect(mcpGroups.length).toBe(1);
expect(mcpGroups[0].label).toBe('Empty Server');
expect(mcpGroups[0].tools.length).toBe(0);
expect(mcpGroups[0].serverApprovalKey).toBe('mcp_server:Empty Server');
});
test('builtin groups do not have serverApprovalKey', () => {
const tooling = makeTooling();
const tools = listApprovalToolDefinitions(tooling);
const groups = groupApprovalToolsByProvider(tools, tooling);
const builtinGroup = groups.find((g) => g.kind === 'builtin');
expect(builtinGroup!.serverApprovalKey).toBeUndefined();
});
});
describe('server-level approval keys', () => {
test('buildMcpServerApprovalKey produces mcp_server: prefixed key', () => {
expect(buildMcpServerApprovalKey('My Server')).toBe('mcp_server:My Server');
expect(buildMcpServerApprovalKey('git')).toBe('mcp_server:git');
});
test('listApprovalToolNames includes server-level keys', () => {
const tooling: WorkspaceToolingSettings = {
mcpServers: [{
id: 'git', name: 'Git MCP', transport: 'local', command: 'node', args: [],
tools: [], createdAt: '2026-03-28T00:00:00.000Z', updatedAt: '2026-03-28T00:00:00.000Z',
}],
lspProfiles: [],
};
const names = listApprovalToolNames(tooling);
expect(names).toContain('mcp_server:Git MCP');
// Also includes builtins
expect(names).toContain('read');
expect(names).toContain('shell');
});
});
describe('probed tools', () => {
const TS = '2026-03-28T00:00:00.000Z';
function makeTooling(mcpServers: McpServerDefinition[] = []): WorkspaceToolingSettings {
return { mcpServers, lspProfiles: [] };
}
test('listApprovalToolDefinitions uses probedTools when tools array is empty', () => {
const tooling = makeTooling([{
id: 'mcp-1', name: 'Probed Server', transport: 'local', command: 'node', args: [],
tools: [],
probedTools: [
{ name: 'search', description: 'Search files' },
{ name: 'index', description: 'Build index' },
],
createdAt: TS, updatedAt: TS,
}]);
const defs = listApprovalToolDefinitions(tooling);
const mcpDefs = defs.filter((d) => d.kind === 'mcp');
expect(mcpDefs.length).toBe(2);
expect(mcpDefs.map((d) => d.id).sort()).toEqual(['index', 'search']);
expect(mcpDefs[0].providerNames).toContain('Probed Server');
});
test('listApprovalToolDefinitions prefers declared tools over probedTools', () => {
const tooling = makeTooling([{
id: 'mcp-2', name: 'Declared Server', transport: 'local', command: 'node', args: [],
tools: ['read_file', 'write_file'],
probedTools: [
{ name: 'read_file' },
{ name: 'write_file' },
{ name: 'delete_file' },
],
createdAt: TS, updatedAt: TS,
}]);
const defs = listApprovalToolDefinitions(tooling);
const mcpDefs = defs.filter((d) => d.kind === 'mcp');
expect(mcpDefs.length).toBe(2);
expect(mcpDefs.map((d) => d.id).sort()).toEqual(['read_file', 'write_file']);
});
test('listApprovalToolDefinitions returns no MCP tools when both tools and probedTools are empty', () => {
const tooling = makeTooling([{
id: 'mcp-3', name: 'Empty Server', transport: 'local', command: 'node', args: [],
tools: [],
probedTools: [],
createdAt: TS, updatedAt: TS,
}]);
const defs = listApprovalToolDefinitions(tooling);
const mcpDefs = defs.filter((d) => d.kind === 'mcp');
expect(mcpDefs.length).toBe(0);
});
test('listApprovalToolDefinitions handles undefined probedTools gracefully', () => {
const tooling = makeTooling([{
id: 'mcp-4', name: 'No Probe Server', transport: 'local', command: 'node', args: [],
tools: [],
createdAt: TS, updatedAt: TS,
}]);
const defs = listApprovalToolDefinitions(tooling);
const mcpDefs = defs.filter((d) => d.kind === 'mcp');
expect(mcpDefs.length).toBe(0);
});
test('probed tools with blank names are filtered out', () => {
const tooling = makeTooling([{
id: 'mcp-5', name: 'Blank Tools', transport: 'local', command: 'node', args: [],
tools: [],
probedTools: [
{ name: 'valid_tool' },
{ name: ' ' },
{ name: '' },
],
createdAt: TS, updatedAt: TS,
}]);
const defs = listApprovalToolDefinitions(tooling);
const mcpDefs = defs.filter((d) => d.kind === 'mcp');
expect(mcpDefs.length).toBe(1);
expect(mcpDefs[0].id).toBe('valid_tool');
});
test('groupApprovalToolsByProvider shows probed tools in MCP group', () => {
const tooling = makeTooling([{
id: 'mcp-6', name: 'Probed MCP', transport: 'local', command: 'node', args: [],
tools: [],
probedTools: [
{ name: 'tool_a', description: 'Tool A desc' },
{ name: 'tool_b' },
],
createdAt: TS, updatedAt: TS,
}]);
const defs = listApprovalToolDefinitions(tooling);
const groups = groupApprovalToolsByProvider(defs, tooling);
const mcpGroup = groups.find((g) => g.kind === 'mcp' && g.label === 'Probed MCP');
expect(mcpGroup).toBeDefined();
expect(mcpGroup!.tools.length).toBe(2);
expect(mcpGroup!.serverApprovalKey).toBe('mcp_server:Probed MCP');
});
test('listApprovalToolNames includes probed tool names', () => {
const tooling = makeTooling([{
id: 'mcp-7', name: 'Probed Keys', transport: 'local', command: 'node', args: [],
tools: [],
probedTools: [{ name: 'probe_tool_1' }, { name: 'probe_tool_2' }],
createdAt: TS, updatedAt: TS,
}]);
const names = listApprovalToolNames(tooling);
expect(names).toContain('probe_tool_1');
expect(names).toContain('probe_tool_2');
expect(names).toContain('mcp_server:Probed Keys');
});
});
Binary file not shown.

Before

Width:  |  Height:  |  Size: 198 KiB

After

Width:  |  Height:  |  Size: 206 KiB

+27 -1
View File
@@ -141,7 +141,7 @@ import Base from '../layouts/Base.astro';
</div>
<h3 class="text-base font-semibold">Live Visibility</h3>
<p class="mt-2 text-sm leading-relaxed text-zinc-400">
Watch each agent think, delegate to sub-agents, invoke skills, and run hooks in real time. A context-usage bar shows how much of the model's window you've used.
Watch each agent think, delegate to sub-agents, invoke skills, and run hooks in real time. Track premium request consumption, per-agent token usage, and account quota remaining alongside the context-window bar.
</p>
</div>
@@ -262,6 +262,32 @@ import Base from '../layouts/Base.astro';
Every turn is recorded in a structured run timeline — see tool calls, agent delegation, hook execution, and context usage at a glance.
</p>
</div>
<!-- Feature 14: Copilot Customization Files -->
<div class="group rounded-2xl border border-zinc-800 bg-zinc-900/40 p-6 transition hover:border-zinc-700 hover:bg-zinc-900/60">
<div class="mb-4 flex size-10 items-center justify-center rounded-xl bg-violet-500/10 text-violet-400">
<svg class="size-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
</div>
<h3 class="text-base font-semibold">Copilot Customization</h3>
<p class="mt-2 text-sm leading-relaxed text-zinc-400">
Automatically discovers <code class="text-zinc-300">.github/copilot-instructions.md</code>, <code class="text-zinc-300">AGENTS.md</code>, custom agent profiles, and prompt files from your repository. Zero configuration needed.
</p>
</div>
<!-- Feature 15: Integrated Terminal -->
<div class="group rounded-2xl border border-zinc-800 bg-zinc-900/40 p-6 transition hover:border-zinc-700 hover:bg-zinc-900/60">
<div class="mb-4 flex size-10 items-center justify-center rounded-xl bg-emerald-500/10 text-emerald-400">
<svg class="size-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
</div>
<h3 class="text-base font-semibold">Integrated Terminal</h3>
<p class="mt-2 text-sm leading-relaxed text-zinc-400">
A full PTY-backed terminal panel right inside the workspace. Toggle with <kbd class="text-zinc-300">Ctrl+`</kbd>, resize by dragging, and run commands alongside your agent sessions.
</p>
</div>
</div>
</div>
</section>