Compare commits

..
58 Commits
Author SHA1 Message Date
David KayaandCopilot 3b69a9c0f7 chore: bump version to 0.0.12
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 00:39:25 +02:00
David KayaandCopilot 023ea9b3e4 fix: set releaseType to release in electron-builder publish config
The release workflow creates a published GitHub release before
electron-builder runs. electron-builder defaults to releaseType=draft,
causing a type mismatch that prevents all asset uploads.

Setting releaseType to release tells electron-builder to upload assets
to the existing published release.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 00:38:34 +02:00
David KayaandCopilot bf2a454ef2 fix: auto-allow internal orchestration tools
Allow SDK-managed orchestration tools to bypass pre-tool approval prompts so Aryx matches Copilot CLI behavior for non-side-effectful meta tools.

Keep store_memory under the existing memory approval category.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 00:36:52 +02:00
Dávid KayaandGitHub a1932788ae feat: GPLv3 license 2026-03-30 00:26:14 +02:00
David KayaandCopilot c3e611dc74 fix: normalize macOS signing certificate
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 00:16:16 +02:00
David KayaandCopilot dcabc65dbf feat: inline file change preview in run timeline
Show expandable file change previews on tool-call timeline events
when file changes are present. Each tool-call row gains a compact
summary (file count, +/- stats, GitHub-style stats bar) that
expands to per-file entries with collapsible unified diffs.

- FileChangePreview component in chat/ feature directory
- DiffLine with background highlighting for additions/deletions
- DiffStatsBar mini visualization (5-block addition/deletion ratio)
- New file detection with FilePlus2 icon and 'new' badge
- TimelineEventRow restructured to wrapper div for proper nesting

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 00:05:17 +02:00
David KayaandCopilot 1068ed39e4 fix: harden macOS signing asset prep
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 00:01:19 +02:00
David KayaandCopilot e956f8ea6c feat: emit tool-call file previews
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 23:55:25 +02:00
David KayaandCopilot af69d494a5 chore: bump version to 0.0.8
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 23:41:22 +02:00
David KayaandCopilot e72bb7c7ca build: add macos signing to release workflow
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 23:39:02 +02:00
David KayaandCopilot 5f4318e761 feat: add message actions frontend UI
- Hover action toolbar on messages: copy, pin/unpin, branch, edit (user),
  regenerate (last assistant)
- Inline edit composer for user messages with save & resend flow
- Pinned message bookmark indicator next to author name
- Action-specific branch origin banners (branched, regenerated, edited)
- Sidebar branch icons distinguish branch/regenerate/edit-and-resend
- CSS animation for action toolbar entrance

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 23:12:34 +02:00
David KayaandCopilot d88ce0f00c feat: add message actions backend
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 22:59:56 +02:00
David KayaandCopilot 15071fdc47 feat: migrate packaging and auto updates
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 22:36:44 +02:00
David KayaandCopilot 66b2a94977 fix: auto-allow infrastructure tool hooks
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 22:01:56 +02:00
David KayaandCopilot 4726e2acea feat: allow branching from both user and assistant messages
- Relax branchSessionRecord validation to accept user or assistant roles
- Show "Branch from here" hover button on all conversation messages
- Contextual tooltip: "starting from this message" vs "continuing from this response"
- Add test for branching from assistant message
- Replace non-user rejection test with non-conversation rejection test

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 21:43:58 +02:00
David KayaandCopilot c0a37b0cd4 feat: add session branching frontend UI
- Add "Branch from here" hover button on user messages in ChatPane
- Wire onBranchFromMessage to api.branchSession IPC call
- Show branch origin banner at top of branched session transcripts
- Display GitBranch indicator on branched sessions in sidebar
- Resolve source session title from workspace for origin display

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 18:31:34 +02:00
David KayaandCopilot 7aae1b2cd5 feat: add backend session branching support
Add the backend contract and session-domain support for
'Branch from here':
- new branchSession IPC method and sessions:branch channel
- branchOrigin metadata on SessionRecord
- session branching helper that truncates the transcript at a
  chosen user message and clears runtime state
- AryxAppService branching flow with scratchpad directory support
- persistence normalization and regression coverage

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 18:24:05 +02:00
David KayaandCopilot a670817870 feat: add system tray with quick actions and minimize-to-tray
System tray:
- Always-visible tray icon with context menu
- Quick Scratchpad action from tray (triggers session creation
  via IPC bridge to renderer)
- Running session count in tray tooltip and menu
- Click tray icon to show/focus window
- Quit option in tray menu

Minimize to tray:
- New 'Minimize to tray on close' toggle in Settings > Appearance
- When enabled, closing the window hides to tray instead of
  quitting (configurable per-user, default off)
- macOS: hides dock icon when minimized to tray
- Proper force-quit handling (Cmd+Q on macOS, tray Quit)

Full IPC contract chain:
- minimizeToTray setting in WorkspaceSettings
- setMinimizeToTray channel + ElectronApi method
- Preload bridge, service handler, IPC registration
- Preserved through workspace normalization

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 18:10:38 +02:00
David KayaandCopilot 8813f9e90a feat: improve onboarding and first-run experience
Redesigned WelcomePane with context-aware onboarding:
- Getting Started progress tracker with animated progress bar
  showing Copilot connection + project setup completion
- Adaptive CTAs: highlights 'Connect GitHub Copilot' when not
  connected, or 'Try a Quick Scratchpad' when connected
- Setup steps with checkmarks for completed items
- Keyboard shortcut hints for returning users
- First-run vs returning-user messaging

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 18:02:49 +02:00
David KayaandCopilot 20b400be56 feat: add session content search with Ctrl+Shift+F
Full-text search across all session messages via a global search
overlay. Shows matching messages with highlighted context snippets,
session title, project name, and author. Click or Enter to jump
directly to the matching message in its session.

Available via Ctrl+Shift+F shortcut or the command palette.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 18:00:20 +02:00
David KayaandCopilot 05dded9b37 feat: add animated transitions and micro-interactions
Add entrance animations to overlays, modals, chat messages, sidebar
session items, and approval banners:
- overlay-slide-enter: settings and project settings panels
- overlay-backdrop-enter + overlay-panel-enter: modals
- message-enter: chat message fade-up on mount
- session-item-enter: sidebar item slide-in
- banner-slide-enter: approval banner slide-down

All animations use cubic-bezier(0.16, 1, 0.3, 1) for a snappy feel
and stay under 250ms. Respects prefers-reduced-motion.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 17:57:05 +02:00
David KayaandCopilot ea58f7d66a feat: add rich keyboard shortcuts with cheat sheet overlay
Comprehensive keybindings for power-user navigation:
- Ctrl+N: new session, Ctrl+W: archive session
- Ctrl+Tab / Ctrl+Shift+Tab: cycle between sessions
- Ctrl+,: open settings, Ctrl+/: shortcuts cheat sheet
- Ctrl+.: quick-approve pending tool call
- Ctrl+L: focus composer, Escape: cancel turn / close overlay

Centralized shortcut registry in lib/keyboardShortcuts.ts drives
both the cheat sheet panel and command palette shortcut badges.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 17:49:06 +02:00
David KayaandCopilot bb713f61be feat: add desktop notifications for run completion
Show native OS notifications when a session run completes, fails, or
needs approval while the app window is unfocused. Clicking a
notification focuses the window and selects the relevant session.

Includes a toggle in Settings > Appearance to enable/disable
notifications (enabled by default).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 17:40:59 +02:00
David KayaandCopilot 395965c639 feat: add command palette (Ctrl+K / Cmd+K)
Fuzzy-searchable command palette accessible from anywhere via Ctrl+K
(Windows/Linux) or Cmd+K (macOS). Supports keyboard navigation with
arrow keys, Enter to select, and Escape to close.

Available commands:
- Switch between sessions and projects
- Create new sessions and scratchpads
- Pin, archive, and duplicate the current session
- Open settings, project settings, and app data folder
- Toggle terminal
- Switch theme (dark/light/system)
- Add new projects

Implementation:
- New CommandPalette component with glass surface and glow border
- Palette entry/exit CSS animations
- Capture-phase Escape handler to prevent leaking to other overlays
- Commands built dynamically from workspace state
- Results grouped by category with fuzzy scoring

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 17:30:47 +02:00
David Kaya be3f8d4cb3 feat: add new screenshots 2026-03-29 17:17:14 +02:00
David KayaandCopilot f8b4c3cf4f feat: Luminous Depth UI redesign
Complete visual overhaul of the Aryx application with the Luminous Depth
design language — blue-tinted dark surfaces, brand gradient accents,
glass-morphism effects, and refined typography.

Design Foundation:
- New color system with CSS custom properties for all surfaces, borders,
  text, accents, and status colors
- Typography: Outfit (display), DM Sans (body), JetBrains Mono (code)
- Animations: accent-flow, thinking-wave, ambient-glow
- Utility classes: glass-surface, glow-border, brand-gradient-bg/text
- Light theme with cool-tinted whites and blue-tinted shadows

Components Updated:
- UI primitives (TextInput, SelectInput, ToggleSwitch, FormField, etc.)
- AppShell with ambient glow background
- Sidebar with brand gradient selection and accent-flow running bars
- ChatPane with semantic phase tinting and gradient user avatars
- WelcomePane with nebula background and motion entrance animations
- All chat banners (Approval, UserInput, PlanReview, MCP Auth, etc.)
- ActivityPanel and RunTimeline with glass-surface cards
- Settings panels, modals, and editor shells
- TerminalPanel with harmonized ANSI palette
- PatternGraph nodes with glass-surface styling
- MarkdownComposer toolbar

Zero hardcoded zinc/indigo color classes remain in renderer components.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 17:10:00 +02:00
David Kaya 2f1c5bc6d7 feat: redesign of the website 2026-03-29 16:51:00 +02:00
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
147 changed files with 15763 additions and 2546 deletions
+135 -26
View File
@@ -96,20 +96,12 @@ jobs:
include:
- os: windows-latest
label: Windows
release_dir_name: Aryx-windows-x64
asset_path: release/Aryx-windows-x64-setup.exe
- os: macos-15-intel
label: macOS (x64)
release_dir_name: Aryx-macos-x64
asset_path: release/Aryx-macos-x64.dmg
- os: macos-15
label: macOS (arm64)
release_dir_name: Aryx-macos-arm64
asset_path: release/Aryx-macos-arm64.dmg
- os: ubuntu-latest
label: Linux
release_dir_name: Aryx-linux-x64
asset_path: release/aryx-linux-x64.deb
steps:
- name: Check out repository
@@ -131,28 +123,145 @@ jobs:
sudo apt-get update
sudo apt-get install -y libsecret-1-dev
- name: Install Inno Setup
if: runner.os == 'Windows'
shell: pwsh
run: choco install innosetup -y --no-progress
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Package current platform
run: bun run package
- name: Ad-hoc sign macOS app bundle
- name: Prepare Apple signing assets
if: runner.os == 'macOS'
run: codesign --force --deep --sign - "release/${{ matrix.release_dir_name }}/Aryx.app"
- name: Create platform installer
run: bun run scripts/create-installer.ts
- name: Upload asset to GitHub release
shell: bash
env:
APPLE_CERT_P12_BASE64: ${{ secrets.APPLE_CERT_P12_BASE64 }}
APPLE_CERT_PASSWORD: ${{ secrets.APPLE_CERT_PASSWORD }}
APPLE_API_KEY_P8: ${{ secrets.APPLE_API_KEY_P8 }}
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: |
write_github_env() {
local name="$1"
local value="$2"
local delimiter
delimiter="ARYX_ENV_$(uuidgen | tr '[:lower:]' '[:upper:]')"
{
printf '%s<<%s\n' "$name" "$delimiter"
printf '%s\n' "$value"
printf '%s\n' "$delimiter"
} >> "$GITHUB_ENV"
}
if [[ -z "$APPLE_CERT_P12_BASE64" ]]; then
echo "Missing required secret: APPLE_CERT_P12_BASE64" >&2
exit 1
fi
if [[ -z "$APPLE_CERT_PASSWORD" ]]; then
echo "Missing required secret: APPLE_CERT_PASSWORD" >&2
exit 1
fi
if [[ -z "$APPLE_API_KEY_P8" ]]; then
echo "Missing required secret: APPLE_API_KEY_P8" >&2
exit 1
fi
if [[ -z "$APPLE_API_KEY_ID" ]]; then
echo "Missing required secret: APPLE_API_KEY_ID" >&2
exit 1
fi
if [[ -z "$APPLE_API_ISSUER" ]]; then
echo "Missing required secret: APPLE_API_ISSUER" >&2
exit 1
fi
if [[ -z "$APPLE_TEAM_ID" ]]; then
echo "Missing required secret: APPLE_TEAM_ID" >&2
exit 1
fi
SOURCE_CERT_PATH="$RUNNER_TEMP/apple-signing-source.p12"
CERT_PATH="$RUNNER_TEMP/apple-signing.p12"
PEM_PATH="$RUNNER_TEMP/apple-signing.pem"
PRECHECK_KEYCHAIN_PATH="$RUNNER_TEMP/apple-signing-preflight.keychain-db"
PRECHECK_KEYCHAIN_PASSWORD="$(uuidgen)"
API_KEY_PATH="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"
cleanup_precheck_keychain() {
security delete-keychain "$PRECHECK_KEYCHAIN_PATH" >/dev/null 2>&1 || true
}
trap cleanup_precheck_keychain EXIT
CERT_PATH="$SOURCE_CERT_PATH" python3 - <<'PY'
import base64
import binascii
import os
from pathlib import Path
raw_value = os.environ["APPLE_CERT_P12_BASE64"]
normalized_value = "".join(raw_value.split())
if not normalized_value:
raise SystemExit("APPLE_CERT_P12_BASE64 is empty after whitespace normalization")
try:
decoded = base64.b64decode(normalized_value, validate=True)
except binascii.Error:
raise SystemExit("APPLE_CERT_P12_BASE64 is not valid base64")
if not decoded:
raise SystemExit("Decoded Apple signing certificate is empty")
Path(os.environ["CERT_PATH"]).write_bytes(decoded)
PY
printf '%s' "$APPLE_API_KEY_P8" > "$API_KEY_PATH"
if [[ ! -s "$SOURCE_CERT_PATH" ]]; then
echo "Decoded Apple signing certificate file is empty." >&2
exit 1
fi
if ! openssl pkcs12 -in "$SOURCE_CERT_PATH" -noout -passin env:APPLE_CERT_PASSWORD >/dev/null 2>&1; then
echo "Decoded Apple signing certificate could not be opened with APPLE_CERT_PASSWORD." >&2
exit 1
fi
if ! openssl pkcs12 -in "$SOURCE_CERT_PATH" -passin env:APPLE_CERT_PASSWORD -nodes -out "$PEM_PATH" >/dev/null 2>&1; then
echo "Decoded Apple signing certificate could not be converted to PEM." >&2
exit 1
fi
if ! openssl pkcs12 -export -out "$CERT_PATH" -in "$PEM_PATH" -passout env:APPLE_CERT_PASSWORD -macalg sha1 -keypbe PBE-SHA1-3DES -certpbe PBE-SHA1-3DES >/dev/null 2>&1; then
echo "Apple signing certificate could not be re-exported into a macOS-compatible PKCS#12." >&2
exit 1
fi
if [[ ! -s "$CERT_PATH" ]]; then
echo "Normalized Apple signing certificate file is empty." >&2
exit 1
fi
if ! security create-keychain -p "$PRECHECK_KEYCHAIN_PASSWORD" "$PRECHECK_KEYCHAIN_PATH" >/dev/null 2>&1; then
echo "Unable to create the macOS signing precheck keychain." >&2
exit 1
fi
if ! security unlock-keychain -p "$PRECHECK_KEYCHAIN_PASSWORD" "$PRECHECK_KEYCHAIN_PATH" >/dev/null 2>&1; then
echo "Unable to unlock the macOS signing precheck keychain." >&2
exit 1
fi
if ! security import "$CERT_PATH" -k "$PRECHECK_KEYCHAIN_PATH" -P "$APPLE_CERT_PASSWORD" -T /usr/bin/codesign -T /usr/bin/productsign >/dev/null 2>&1; then
echo "Normalized Apple signing certificate is still not importable by macOS security." >&2
exit 1
fi
rm -f "$SOURCE_CERT_PATH" "$PEM_PATH"
cleanup_precheck_keychain
trap - EXIT
write_github_env "CSC_LINK" "$CERT_PATH"
write_github_env "CSC_KEY_PASSWORD" "$APPLE_CERT_PASSWORD"
write_github_env "APPLE_API_KEY" "$API_KEY_PATH"
write_github_env "APPLE_API_KEY_ID" "$APPLE_API_KEY_ID"
write_github_env "APPLE_API_ISSUER" "$APPLE_API_ISSUER"
write_github_env "APPLE_TEAM_ID" "$APPLE_TEAM_ID"
- name: Build and publish release artifacts
env:
GH_TOKEN: ${{ github.token }}
TAG_NAME: ${{ github.ref_name }}
ASSET_PATH: ${{ matrix.asset_path }}
run: gh release upload "$TAG_NAME" "$ASSET_PATH" --clobber
run: bun run publish-release
+21 -4
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,21 @@ 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.
Tool-call activity records can also be enriched with a stable `toolCallId` and aggregated file-change preview payloads (`path`, unified diff, and optional new-file contents). The sidecar derives those previews from Copilot SDK write permission requests, and the main process merges repeated write events by `toolCallId` into the persisted run timeline so future UI surfaces can render file previews without reinterpreting approval payloads.
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 +284,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
@@ -331,9 +346,11 @@ The build pipeline is organized around three layers:
- building the Electron renderer and main process assets
- publishing the sidecar for the target runtime
- assembling a platform-specific release bundle
- packaging platform artifacts with electron-builder
Release automation validates the app across Windows, macOS, and Linux, and tag-based releases publish platform bundles directly to GitHub Releases, including both macOS x64 and arm64 artifacts.
electron-builder bundles the packaged Electron app, copies the published sidecar into `resources/sidecar`, produces Windows NSIS installers, macOS DMG + ZIP artifacts, and Linux AppImages, and uploads the release assets plus update metadata to GitHub Releases. Tagged macOS release jobs now materialize the certificate and App Store Connect key from repository secrets into temporary files on the runner, normalize the decoded PKCS#12 into a `security import`-compatible container, preflight that normalized certificate against a temporary keychain, export the standard `electron-builder` signing and notarization environment variables from those files, and package with checked-in hardened-runtime entitlements so native modules still run correctly under code signing. The main process consumes the published metadata through `electron-updater`, which checks GitHub Releases for packaged builds and can stage a restart-based update install.
Current Windows builds are unsigned, so the packaging config disables executable resource editing/signing and skips Windows update signature verification until a code-signing certificate is available. The packaging scripts also clear `release/` before each build so local packaging runs cannot accidentally mix stale artifacts with current ones.
This packaging model matches the runtime architecture: one desktop shell plus one dedicated AI execution process.
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+13 -1
View File
@@ -124,7 +124,19 @@ To package the current platform into `release/`, run:
- `bun run package`
GitHub Actions now runs validation on pushes and pull requests, and pushing a git tag creates a GitHub release with Windows, macOS (x64 and arm64), and Linux assets uploaded directly to the release.
To create the installable artifacts for the current platform, run:
- `bun run installer`
To publish packaged artifacts and update metadata to GitHub Releases, run:
- `bun run publish-release`
GitHub Actions runs validation on pushes and pull requests, and tagged releases now use `electron-builder` to publish Windows (NSIS), macOS (DMG + ZIP for updater metadata), and Linux (AppImage) artifacts directly to GitHub Releases. Packaged builds use `electron-updater` against those releases for in-app updates.
Tagged macOS release jobs now prepare signing assets from the GitHub secrets `APPLE_CERT_P12_BASE64`, `APPLE_CERT_PASSWORD`, `APPLE_API_KEY_P8`, `APPLE_API_KEY_ID`, `APPLE_API_ISSUER`, and `APPLE_TEAM_ID`, normalize the decoded PKCS#12 into a macOS-compatible container, preflight `security import` against a temporary keychain, and then export the standard `electron-builder` environment variables (`CSC_LINK`, `CSC_KEY_PASSWORD`, `APPLE_API_KEY`, `APPLE_API_KEY_ID`, `APPLE_API_ISSUER`, `APPLE_TEAM_ID`) before packaging. That same release path signs and notarizes the macOS artifacts as part of publication.
Windows builds are currently packaged without Authenticode signing, so Aryx disables `electron-updater`'s Windows signature verification until a signing certificate is configured. macOS auto-update metadata still requires a ZIP artifact alongside the DMG build.
## Current focus
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
</dict>
</plist>
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
</dict>
</plist>
-9
View File
@@ -1,9 +0,0 @@
[Desktop Entry]
Name=Aryx
Comment=Copilot-powered agent workflow orchestrator
Exec=/opt/aryx/Aryx %U
Icon=aryx
Terminal=false
Type=Application
Categories=Development;
StartupWMClass=Aryx
-86
View File
@@ -1,86 +0,0 @@
; Inno Setup script for Aryx
; Dynamic values are read from environment variables set by the build script.
#define PRODUCT_NAME "Aryx"
#define PRODUCT_PUBLISHER "David Kaya"
#define PRODUCT_VERSION GetEnv("ARYX_BUILD_VERSION")
#define SOURCE_DIR GetEnv("ARYX_BUILD_SOURCE_DIR")
#define OUTPUT_DIR GetEnv("ARYX_BUILD_OUTPUT_DIR")
#define OUTPUT_FILENAME GetEnv("ARYX_BUILD_OUTPUT_FILENAME")
#define ICON_PATH GetEnv("ARYX_BUILD_ICON_PATH")
#if PRODUCT_VERSION == ""
#error "ARYX_BUILD_VERSION environment variable must be set."
#endif
#if SOURCE_DIR == ""
#error "ARYX_BUILD_SOURCE_DIR environment variable must be set."
#endif
#if OUTPUT_DIR == ""
#error "ARYX_BUILD_OUTPUT_DIR environment variable must be set."
#endif
#if OUTPUT_FILENAME == ""
#error "ARYX_BUILD_OUTPUT_FILENAME environment variable must be set."
#endif
#if ICON_PATH == ""
#define ICON_PATH SOURCE_DIR + "\" + PRODUCT_NAME + ".exe"
#endif
[Setup]
AppId={{B8A3E7F1-4D2C-4A9B-8E6F-1C3D5A7B9E0F}
AppName={#PRODUCT_NAME}
AppVersion={#PRODUCT_VERSION}
AppPublisher={#PRODUCT_PUBLISHER}
AppSupportURL=https://github.com/davidkaya/aryx
DefaultDirName={localappdata}\Programs\{#PRODUCT_NAME}
DefaultGroupName={#PRODUCT_NAME}
PrivilegesRequired=lowest
OutputDir={#OUTPUT_DIR}
OutputBaseFilename={#OUTPUT_FILENAME}
Compression=lzma2/ultra64
SolidCompression=yes
SetupIconFile={#ICON_PATH}
UninstallDisplayIcon={app}\{#PRODUCT_NAME}.exe
WizardStyle=modern
DisableProgramGroupPage=yes
CloseApplications=force
RestartApplications=no
[Languages]
Name: "english"; MessagesFile: "compiler:Default.isl"
[Files]
Source: "{#SOURCE_DIR}\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
[Icons]
Name: "{group}\{#PRODUCT_NAME}"; Filename: "{app}\{#PRODUCT_NAME}.exe"
Name: "{autodesktop}\{#PRODUCT_NAME}"; Filename: "{app}\{#PRODUCT_NAME}.exe"; Tasks: desktopicon
[Tasks]
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked
[Run]
Filename: "{app}\{#PRODUCT_NAME}.exe"; Description: "{cm:LaunchProgram,{#PRODUCT_NAME}}"; Flags: nowait postinstall skipifsilent
[UninstallDelete]
Type: filesandordirs; Name: "{app}"
[Code]
procedure CurStepChanged(CurStep: TSetupStep);
var
ResultCode: Integer;
begin
if CurStep = ssInstall then
begin
Exec('taskkill', '/F /IM {#PRODUCT_NAME}.exe', '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
end;
end;
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
var
ResultCode: Integer;
begin
if CurUninstallStep = usUninstall then
begin
Exec('taskkill', '/F /IM {#PRODUCT_NAME}.exe', '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
end;
end;
+618 -128
View File
File diff suppressed because it is too large Load Diff
+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'),
+100 -8
View File
@@ -1,6 +1,6 @@
{
"name": "aryx",
"version": "1.0.0",
"version": "0.0.12",
"description": "Electron orchestrator for Copilot-powered agent workflows across multiple projects.",
"private": true,
"main": "dist-electron/main/index.js",
@@ -8,8 +8,9 @@
"dev": "electron-vite dev",
"build:electron": "electron-vite build",
"build": "bun run build:electron && bun run sidecar:build",
"package": "bun run build:electron && bun run sidecar:publish && bun run scripts/package-electron.ts",
"installer": "bun run package && bun run scripts/create-installer.ts",
"package": "bun run scripts/clean-release.ts && bun run build:electron && bun run sidecar:publish && electron-builder --dir --publish never",
"installer": "bun run scripts/clean-release.ts && bun run build:electron && bun run sidecar:publish && electron-builder --publish never",
"publish-release": "bun run scripts/clean-release.ts && bun run build:electron && bun run sidecar:publish && electron-builder --publish always",
"preview": "electron-vite preview",
"lsp:typescript": "typescript-language-server --stdio",
"typecheck": "tsc --noEmit -p tsconfig.json",
@@ -33,7 +34,6 @@
"packageManager": "bun@1.3.6",
"devDependencies": {
"@dagrejs/dagre": "^3.0.0",
"@electron/asar": "^4.1.1",
"@lexical/code": "0.42.0",
"@lexical/headless": "0.42.0",
"@lexical/link": "0.42.0",
@@ -41,20 +41,22 @@
"@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-builder": "^26.8.1",
"electron-vite": "^5.0.0",
"highlight.js": "^11.11.1",
"lexical": "0.42.0",
"lucide-react": "^0.577.0",
"rcedit": "^5.0.2",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"react-markdown": "^10.1.0",
@@ -62,9 +64,99 @@
"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"
"@fontsource-variable/dm-sans": "^5.2.8",
"@fontsource-variable/jetbrains-mono": "^5.2.8",
"@fontsource-variable/outfit": "^5.2.8",
"electron-updater": "^6.8.3",
"keytar": "^7.9.0",
"motion": "^12.38.0",
"node-pty": "^1.1.0"
},
"build": {
"appId": "com.davidkaya.aryx",
"productName": "Aryx",
"directories": {
"buildResources": "assets",
"output": "release"
},
"files": [
"package.json",
"dist-electron/**/*",
"dist/**/*",
"assets/**/*"
],
"extraResources": [
{
"from": "dist-sidecar",
"to": "sidecar",
"filter": [
"**/*"
]
}
],
"asar": true,
"asarUnpack": [
"**/*.node"
],
"electronLanguages": [
"en-US"
],
"electronUpdaterCompatibility": ">=2.16",
"npmRebuild": false,
"publish": {
"provider": "github",
"owner": "davidkaya",
"repo": "aryx",
"releaseType": "release"
},
"win": {
"target": [
"nsis"
],
"icon": "assets/icons/windows/icon.ico",
"artifactName": "Aryx-windows-${arch}.${ext}",
"signAndEditExecutable": false,
"verifyUpdateCodeSignature": false
},
"nsis": {
"oneClick": false,
"perMachine": false,
"allowToChangeInstallationDirectory": true,
"installerIcon": "assets/icons/windows/icon.ico",
"uninstallerIcon": "assets/icons/windows/icon.ico"
},
"mac": {
"target": [
"dmg",
"zip"
],
"icon": "assets/icons/macos/icon.icns",
"category": "public.app-category.developer-tools",
"hardenedRuntime": true,
"entitlements": "assets/entitlements.mac.plist",
"entitlementsInherit": "assets/entitlements.mac.inherit.plist",
"gatekeeperAssess": false,
"notarize": true,
"artifactName": "Aryx-macos-${arch}.${ext}"
},
"linux": {
"target": [
"AppImage"
],
"icon": "assets/icons/linux/icons",
"category": "Development",
"artifactName": "Aryx-linux-${arch}.${ext}",
"desktop": {
"entry": {
"Name": "Aryx",
"Comment": "Copilot-powered agent workflow orchestrator",
"StartupWMClass": "Aryx"
}
}
}
}
}
+9
View File
@@ -0,0 +1,9 @@
import { rm } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const scriptDirectory = dirname(fileURLToPath(import.meta.url));
const repositoryRoot = resolve(scriptDirectory, '..');
const releaseDirectory = resolve(repositoryRoot, 'release');
await rm(releaseDirectory, { recursive: true, force: true });
-233
View File
@@ -1,233 +0,0 @@
import { spawn } from 'node:child_process';
import { constants } from 'node:fs';
import {
access,
cp,
mkdir,
readFile,
rename,
symlink,
writeFile,
} from 'node:fs/promises';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { productName, resolveReleaseTarget } from './releaseTarget';
function runCommand(command: string, args: string[], cwd: string): Promise<void> {
return new Promise((resolvePromise, rejectPromise) => {
const child = spawn(command, args, {
cwd,
stdio: 'inherit',
});
child.on('error', rejectPromise);
child.on('exit', (code, signal) => {
if (code === 0) {
resolvePromise();
return;
}
if (signal) {
rejectPromise(new Error(`${command} exited because of signal ${signal}.`));
return;
}
rejectPromise(new Error(`${command} exited with code ${code ?? 'unknown'}.`));
});
});
}
async function pathExists(path: string): Promise<boolean> {
try {
await access(path, constants.F_OK);
return true;
} catch {
return false;
}
}
const scriptDirectory = dirname(fileURLToPath(import.meta.url));
const repositoryRoot = resolve(scriptDirectory, '..');
const releaseTarget = resolveReleaseTarget(process.platform, process.arch);
const releaseRootDirectory = join(repositoryRoot, 'release');
const packagedAppDirectory = join(releaseRootDirectory, releaseTarget.outputDirectoryName);
const installerOutputPath = join(releaseRootDirectory, releaseTarget.installerAssetName);
const installerAssetsDirectory = join(repositoryRoot, 'assets', 'installer');
async function readVersion(): Promise<string> {
const packageJson = JSON.parse(
await readFile(join(repositoryRoot, 'package.json'), 'utf8'),
) as { version: string };
return packageJson.version;
}
// --- Windows: Inno Setup installer ---
async function resolveInnoSetupCompilerPath(): Promise<string> {
const candidates = [
'C:\\Program Files (x86)\\Inno Setup 6\\ISCC.exe',
'C:\\Program Files\\Inno Setup 6\\ISCC.exe',
'iscc',
];
for (const candidate of candidates) {
if (candidate.includes('\\') && (await pathExists(candidate))) {
return candidate;
}
}
return 'iscc';
}
async function createWindowsInstaller(version: string): Promise<void> {
const issScript = join(installerAssetsDirectory, 'windows.iss');
const isccPath = await resolveInnoSetupCompilerPath();
const outputFilename = releaseTarget.installerAssetName.replace(/\.exe$/, '');
const iconPath = join(repositoryRoot, 'assets', 'icons', 'windows', 'icon.ico');
process.env.ARYX_BUILD_VERSION = version;
process.env.ARYX_BUILD_SOURCE_DIR = packagedAppDirectory;
process.env.ARYX_BUILD_OUTPUT_DIR = releaseRootDirectory;
process.env.ARYX_BUILD_OUTPUT_FILENAME = outputFilename;
process.env.ARYX_BUILD_ICON_PATH = iconPath;
await runCommand(isccPath, [issScript], repositoryRoot);
}
// --- macOS: DMG disk image ---
async function createMacInstaller(): Promise<void> {
const appBundleName = releaseTarget.appBundleName;
if (!appBundleName) {
throw new Error('macOS installer requires an app bundle name.');
}
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.
await runCommand(
createDmg,
[
'--overwrite',
'--no-version-in-filename',
'--no-code-sign',
appBundlePath,
releaseRootDirectory,
],
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 ---
const linuxIconSizes = ['16x16', '32x32', '48x48', '64x64', '128x128', '256x256', '512x512'];
async function createLinuxInstaller(version: string): Promise<void> {
const stagingDirectory = join(releaseRootDirectory, 'deb-staging');
const debianDirectory = join(stagingDirectory, 'DEBIAN');
const optDirectory = join(stagingDirectory, 'opt', 'aryx');
const binDirectory = join(stagingDirectory, 'usr', 'bin');
const applicationsDirectory = join(stagingDirectory, 'usr', 'share', 'applications');
await mkdir(debianDirectory, { recursive: true });
await mkdir(binDirectory, { recursive: true });
await mkdir(applicationsDirectory, { recursive: true });
// Copy packaged app into /opt/aryx/
await cp(packagedAppDirectory, optDirectory, { recursive: true });
// Create symlink /usr/bin/aryx -> /opt/aryx/Aryx
await symlink('/opt/aryx/Aryx', join(binDirectory, 'aryx'));
// Copy desktop entry
await cp(
join(installerAssetsDirectory, 'linux', 'aryx.desktop'),
join(applicationsDirectory, 'aryx.desktop'),
);
// Install icons into hicolor theme
const sourceIconsDirectory = join(repositoryRoot, 'assets', 'icons', 'linux', 'icons');
for (const size of linuxIconSizes) {
const sourceIcon = join(sourceIconsDirectory, `${size}.png`);
if (!(await pathExists(sourceIcon))) {
continue;
}
const targetIconDirectory = join(
stagingDirectory, 'usr', 'share', 'icons', 'hicolor', size, 'apps',
);
await mkdir(targetIconDirectory, { recursive: true });
await cp(sourceIcon, join(targetIconDirectory, 'aryx.png'));
}
// Determine installed size (in KB)
const { stdout } = await new Promise<{ stdout: string }>((resolvePromise, rejectPromise) => {
const child = spawn('du', ['-sk', optDirectory], { stdio: ['pipe', 'pipe', 'pipe'] });
let out = '';
child.stdout.on('data', (data: Buffer) => { out += data.toString(); });
child.on('error', rejectPromise);
child.on('exit', () => resolvePromise({ stdout: out }));
});
const installedSizeKb = parseInt(stdout.split('\t')[0] ?? '0', 10);
const debArch = releaseTarget.arch === 'x64' ? 'amd64' : 'arm64';
// Write DEBIAN/control
const controlContent = [
`Package: aryx`,
`Version: ${version}`,
`Section: devel`,
`Priority: optional`,
`Architecture: ${debArch}`,
`Installed-Size: ${installedSizeKb}`,
`Depends: libsecret-1-0`,
`Maintainer: David Kaya`,
`Description: ${productName} — Copilot-powered agent workflow orchestrator`,
` Electron desktop app for orchestrating Copilot-driven agent workflows`,
` across multiple projects.`,
'',
].join('\n');
await writeFile(join(debianDirectory, 'control'), controlContent);
// Build the .deb
await runCommand(
'dpkg-deb',
['--build', '--root-owner-group', stagingDirectory, installerOutputPath],
repositoryRoot,
);
}
// --- Entry point ---
if (!(await pathExists(packagedAppDirectory))) {
throw new Error(
`Packaged app not found at ${packagedAppDirectory}. Run "bun run package" first.`,
);
}
const version = await readVersion();
switch (releaseTarget.platform) {
case 'win32':
await createWindowsInstaller(version);
break;
case 'darwin':
await createMacInstaller();
break;
case 'linux':
await createLinuxInstaller(version);
break;
}
console.log(`Created installer: ${installerOutputPath}`);
-332
View File
@@ -1,332 +0,0 @@
import { constants } from 'node:fs';
import { access, chmod, cp, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createPackageWithOptions } from '@electron/asar';
import {
macBundleIdentifier,
productName,
resolveReleaseTarget,
type ReleaseTarget,
} from './releaseTarget';
interface PackageManifest {
readonly name: string;
readonly productName: string;
readonly version: string;
readonly description?: string;
readonly main: string;
readonly author?: string;
readonly license?: string;
}
interface RootPackageJson {
readonly name: string;
readonly version: string;
readonly description?: string;
readonly main: string;
readonly author?: string;
readonly license?: string;
readonly dependencies?: Record<string, string>;
}
const scriptDirectory = dirname(fileURLToPath(import.meta.url));
const repositoryRoot = resolve(scriptDirectory, '..');
const assetDirectory = join(repositoryRoot, 'assets');
const genericIconPath = join(assetDirectory, 'icons', 'icon.png');
const windowsIconPath = join(assetDirectory, 'icons', 'windows', 'icon.ico');
const macosIconPath = join(assetDirectory, 'icons', 'macos', 'icon.icns');
const rendererBuildDirectory = join(repositoryRoot, 'dist');
const electronBuildDirectory = join(repositoryRoot, 'dist-electron');
const releaseTarget = resolveReleaseTarget(process.platform, process.arch);
const releaseRootDirectory = join(repositoryRoot, 'release');
const outputDirectory = join(releaseRootDirectory, releaseTarget.outputDirectoryName);
const electronDistributionDirectory = releaseTarget.platform === 'darwin'
? join(repositoryRoot, 'node_modules', 'electron', 'dist', 'Electron.app')
: join(repositoryRoot, 'node_modules', 'electron', 'dist');
const publishedSidecarDirectory = join(repositoryRoot, 'dist-sidecar', releaseTarget.dotnetRuntime);
async function ensurePathExists(path: string, label: string): Promise<void> {
try {
await access(path, constants.F_OK);
} catch {
throw new Error(`${label} was not found at ${path}.`);
}
}
async function pathExists(path: string): Promise<boolean> {
try {
await access(path, constants.F_OK);
return true;
} catch {
return false;
}
}
async function readJson<T>(path: string): Promise<T> {
return JSON.parse(await readFile(path, 'utf8')) as T;
}
async function collectRuntimeDependencies(): Promise<string[]> {
const rootPackageJson = await readJson<RootPackageJson>(join(repositoryRoot, 'package.json'));
const dependencies = new Set(Object.keys(rootPackageJson.dependencies ?? {}));
const queue = [...dependencies];
while (queue.length > 0) {
const dependencyName = queue.shift();
if (!dependencyName) {
continue;
}
const dependencyPackageJsonPath = join(
repositoryRoot,
'node_modules',
...dependencyName.split('/'),
'package.json',
);
if (!(await pathExists(dependencyPackageJsonPath))) {
dependencies.delete(dependencyName);
continue;
}
const dependencyPackageJson = await readJson<{
readonly dependencies?: Record<string, string>;
readonly optionalDependencies?: Record<string, string>;
}>(dependencyPackageJsonPath);
for (const transitiveDependency of Object.keys({
...(dependencyPackageJson.dependencies ?? {}),
...(dependencyPackageJson.optionalDependencies ?? {}),
})) {
if (!dependencies.has(transitiveDependency)) {
dependencies.add(transitiveDependency);
queue.push(transitiveDependency);
}
}
}
return [...dependencies].sort();
}
async function copyRuntimeDependencies(
packagedAppDirectory: string,
dependencyNames: string[],
): Promise<void> {
const packagedNodeModulesDirectory = join(packagedAppDirectory, 'node_modules');
await mkdir(packagedNodeModulesDirectory, { recursive: true });
for (const dependencyName of dependencyNames) {
const dependencyPathParts = dependencyName.split('/');
const sourceDirectory = join(repositoryRoot, 'node_modules', ...dependencyPathParts);
const targetDirectory = join(packagedNodeModulesDirectory, ...dependencyPathParts);
await mkdir(dirname(targetDirectory), { recursive: true });
await cp(sourceDirectory, targetDirectory, { recursive: true });
}
}
async function writePackagedManifest(packagedAppDirectory: string): Promise<PackageManifest> {
const sourcePackageJson = await readJson<RootPackageJson>(join(repositoryRoot, 'package.json'));
const packagedManifest: PackageManifest = {
name: sourcePackageJson.name,
productName,
version: sourcePackageJson.version,
description: sourcePackageJson.description,
main: sourcePackageJson.main,
author: sourcePackageJson.author,
license: sourcePackageJson.license,
};
await writeFile(
join(packagedAppDirectory, 'package.json'),
`${JSON.stringify(packagedManifest, null, 2)}\n`,
);
return packagedManifest;
}
async function copyApplicationPayload(
packagedAppDirectory: string,
outputResourcesDirectory: string,
dependencyNames: string[],
): Promise<PackageManifest> {
await mkdir(packagedAppDirectory, { recursive: true });
const manifest = await writePackagedManifest(packagedAppDirectory);
await Promise.all([
cp(assetDirectory, join(packagedAppDirectory, 'assets'), { recursive: true }),
cp(rendererBuildDirectory, join(packagedAppDirectory, 'dist'), { recursive: true }),
cp(electronBuildDirectory, join(packagedAppDirectory, 'dist-electron'), { recursive: true }),
cp(publishedSidecarDirectory, join(outputResourcesDirectory, 'sidecar'), { recursive: true }),
]);
await copyRuntimeDependencies(packagedAppDirectory, dependencyNames);
const asarPath = join(outputResourcesDirectory, 'app.asar');
await createPackageWithOptions(packagedAppDirectory, asarPath, {
unpack: '**/*.node',
});
await rm(packagedAppDirectory, { recursive: true });
return manifest;
}
async function ensureExecutable(path: string, mode = 0o755): Promise<void> {
await chmod(path, mode);
}
function replacePlistValue(plistContents: string, key: string, value: string): string {
const pattern = new RegExp(`(<key>${key}</key>\\s*<string>)([^<]*)(</string>)`);
if (!pattern.test(plistContents)) {
throw new Error(`Could not find ${key} in macOS Info.plist.`);
}
return plistContents.replace(pattern, `$1${value}$3`);
}
async function applyMacMetadata(appBundleDirectory: string, version: string): Promise<void> {
const infoPlistPath = join(appBundleDirectory, 'Contents', 'Info.plist');
let infoPlistContents = await readFile(infoPlistPath, 'utf8');
infoPlistContents = replacePlistValue(infoPlistContents, 'CFBundleDisplayName', productName);
infoPlistContents = replacePlistValue(infoPlistContents, 'CFBundleExecutable', productName);
infoPlistContents = replacePlistValue(infoPlistContents, 'CFBundleIconFile', 'icon.icns');
infoPlistContents = replacePlistValue(infoPlistContents, 'CFBundleIdentifier', macBundleIdentifier);
infoPlistContents = replacePlistValue(infoPlistContents, 'CFBundleName', productName);
infoPlistContents = replacePlistValue(infoPlistContents, 'CFBundleShortVersionString', version);
infoPlistContents = replacePlistValue(infoPlistContents, 'CFBundleVersion', version);
await writeFile(infoPlistPath, infoPlistContents);
const sourceExecutablePath = join(appBundleDirectory, 'Contents', 'MacOS', 'Electron');
const targetExecutablePath = join(appBundleDirectory, 'Contents', 'MacOS', productName);
await rename(sourceExecutablePath, targetExecutablePath);
await ensureExecutable(targetExecutablePath);
await cp(macosIconPath, join(appBundleDirectory, 'Contents', 'Resources', 'icon.icns'));
}
async function stripUnneededElectronFiles(electronOutputDirectory: string): Promise<void> {
const filesToRemove = ['LICENSES.chromium.html', 'LICENSE'];
const resourcesToRemove = ['default_app.asar'];
await Promise.all([
...filesToRemove.map((file) => rm(join(electronOutputDirectory, file), { force: true })),
...resourcesToRemove.map((file) =>
rm(join(electronOutputDirectory, 'resources', file), { force: true }),
),
]);
const localesDirectory = join(electronOutputDirectory, 'locales');
if (await pathExists(localesDirectory)) {
const localeFiles = await readdir(localesDirectory);
await Promise.all(
localeFiles
.filter((file) => file !== 'en-US.pak')
.map((file) => rm(join(localesDirectory, file))),
);
}
}
async function stripMacElectronFiles(resourcesDirectory: string): Promise<void> {
await rm(join(resourcesDirectory, 'LICENSES.chromium.html'), { force: true });
const entries = await readdir(resourcesDirectory);
const unusedLproj = entries.filter(
(entry) => entry.endsWith('.lproj') && entry !== 'en.lproj',
);
await Promise.all(
unusedLproj.map((dir) => rm(join(resourcesDirectory, dir), { recursive: true })),
);
}
async function packageWindows(dependencyNames: string[]): Promise<void> {
const packagedExecutablePath = join(outputDirectory, `${productName}.exe`);
const packagedAppDirectory = join(outputDirectory, 'resources', 'app');
const outputResourcesDirectory = join(outputDirectory, 'resources');
await cp(electronDistributionDirectory, outputDirectory, { recursive: true });
await stripUnneededElectronFiles(outputDirectory);
await rename(join(outputDirectory, 'electron.exe'), packagedExecutablePath);
await copyApplicationPayload(packagedAppDirectory, outputResourcesDirectory, dependencyNames);
const { rcedit } = await import('rcedit');
await rcedit(packagedExecutablePath, { icon: windowsIconPath });
}
async function packageMac(dependencyNames: string[]): Promise<void> {
const appBundleName = releaseTarget.appBundleName;
if (!appBundleName) {
throw new Error('macOS packaging requires an app bundle name.');
}
const appBundleDirectory = join(outputDirectory, appBundleName);
const packagedAppDirectory = join(appBundleDirectory, 'Contents', 'Resources', 'app');
const outputResourcesDirectory = join(appBundleDirectory, 'Contents', 'Resources');
await cp(electronDistributionDirectory, appBundleDirectory, { recursive: true });
await stripMacElectronFiles(join(appBundleDirectory, 'Contents', 'Resources'));
const manifest = await copyApplicationPayload(packagedAppDirectory, outputResourcesDirectory, dependencyNames);
await applyMacMetadata(appBundleDirectory, manifest.version);
await ensureExecutable(join(outputResourcesDirectory, 'sidecar', releaseTarget.sidecarExecutableName));
}
async function packageLinux(dependencyNames: string[]): Promise<void> {
const packagedExecutableName = releaseTarget.packagedExecutableName;
if (!packagedExecutableName) {
throw new Error('Linux packaging requires a packaged executable name.');
}
const packagedExecutablePath = join(outputDirectory, packagedExecutableName);
const packagedAppDirectory = join(outputDirectory, 'resources', 'app');
const outputResourcesDirectory = join(outputDirectory, 'resources');
const chromeSandboxPath = join(outputDirectory, 'chrome-sandbox');
await cp(electronDistributionDirectory, outputDirectory, { recursive: true });
await stripUnneededElectronFiles(outputDirectory);
await rename(join(outputDirectory, 'electron'), packagedExecutablePath);
await ensureExecutable(packagedExecutablePath);
await copyApplicationPayload(packagedAppDirectory, outputResourcesDirectory, dependencyNames);
await ensureExecutable(join(outputResourcesDirectory, 'sidecar', releaseTarget.sidecarExecutableName));
if (await pathExists(chromeSandboxPath)) {
await chmod(chromeSandboxPath, 0o4755);
}
}
async function packageCurrentPlatform(target: ReleaseTarget, dependencyNames: string[]): Promise<void> {
switch (target.platform) {
case 'win32':
await packageWindows(dependencyNames);
return;
case 'darwin':
await packageMac(dependencyNames);
return;
case 'linux':
await packageLinux(dependencyNames);
return;
}
}
await Promise.all([
ensurePathExists(assetDirectory, 'Application assets'),
ensurePathExists(genericIconPath, 'Source application icon'),
ensurePathExists(electronDistributionDirectory, 'Electron runtime'),
ensurePathExists(rendererBuildDirectory, 'Renderer build output'),
ensurePathExists(electronBuildDirectory, 'Electron build output'),
ensurePathExists(publishedSidecarDirectory, 'Published sidecar output'),
]);
if (releaseTarget.platform === 'win32') {
await ensurePathExists(windowsIconPath, 'Windows application icon');
}
if (releaseTarget.platform === 'darwin') {
await ensurePathExists(macosIconPath, 'macOS application icon');
}
const runtimeDependencies = await collectRuntimeDependencies();
await rm(outputDirectory, { recursive: true, force: true });
await mkdir(releaseRootDirectory, { recursive: true });
await packageCurrentPlatform(releaseTarget, runtimeDependencies);
console.log(`Packaged ${productName} for ${releaseTarget.platformLabel} to ${outputDirectory}`);
console.log(`Bundled ${runtimeDependencies.length} runtime dependencies and the self-contained .NET sidecar.`);
+35 -6
View File
@@ -3,8 +3,6 @@ import { rm } from 'node:fs/promises';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { resolveReleaseTarget } from './releaseTarget';
function runCommand(command: string, args: string[], cwd: string): Promise<void> {
return new Promise((resolvePromise, rejectPromise) => {
const child = spawn(command, args, {
@@ -29,9 +27,40 @@ function runCommand(command: string, args: string[], cwd: string): Promise<void>
});
}
type SupportedPlatform = 'win32' | 'darwin' | 'linux';
type SupportedArch = 'x64' | 'arm64';
function resolveDotnetRuntime(platform: NodeJS.Platform, arch: NodeJS.Architecture): `${string}-${SupportedArch}` {
if (arch !== 'x64' && arch !== 'arm64') {
throw new Error(`Unsupported architecture for sidecar publish: ${arch}`);
}
switch (platform) {
case 'win32':
return `win-${arch}`;
case 'darwin':
return `osx-${arch}`;
case 'linux':
return `linux-${arch}`;
default:
throw new Error(`Unsupported platform for sidecar publish: ${platform}`);
}
}
function resolvePlatformLabel(platform: SupportedPlatform): 'windows' | 'macos' | 'linux' {
switch (platform) {
case 'win32':
return 'windows';
case 'darwin':
return 'macos';
case 'linux':
return 'linux';
}
}
const scriptDirectory = dirname(fileURLToPath(import.meta.url));
const repositoryRoot = resolve(scriptDirectory, '..');
const releaseTarget = resolveReleaseTarget(process.platform, process.arch);
const dotnetRuntime = resolveDotnetRuntime(process.platform, process.arch);
const sidecarProjectPath = join(
repositoryRoot,
'sidecar',
@@ -39,7 +68,7 @@ const sidecarProjectPath = join(
'Aryx.AgentHost',
'Aryx.AgentHost.csproj',
);
const outputDirectory = join(repositoryRoot, 'dist-sidecar', releaseTarget.dotnetRuntime);
const outputDirectory = join(repositoryRoot, 'dist-sidecar');
await rm(outputDirectory, { recursive: true, force: true });
@@ -51,7 +80,7 @@ await runCommand(
'-c',
'Release',
'-r',
releaseTarget.dotnetRuntime,
dotnetRuntime,
'--self-contained',
'true',
'-p:DebugType=None',
@@ -65,4 +94,4 @@ await runCommand(
repositoryRoot,
);
console.log(`Published sidecar for ${releaseTarget.platformLabel} (${releaseTarget.dotnetRuntime}) to ${outputDirectory}`);
console.log(`Published sidecar for ${resolvePlatformLabel(process.platform as SupportedPlatform)} (${dotnetRuntime}) to ${outputDirectory}`);
-87
View File
@@ -1,87 +0,0 @@
export const productName = 'Aryx';
export const macBundleIdentifier = 'com.davidkaya.aryx';
type SupportedPlatform = 'win32' | 'darwin' | 'linux';
type SupportedArch = 'x64' | 'arm64';
export interface ReleaseTarget {
readonly platform: SupportedPlatform;
readonly arch: SupportedArch;
readonly platformLabel: 'windows' | 'macos' | 'linux';
readonly dotnetRuntime: `${string}-${SupportedArch}`;
readonly outputDirectoryName: string;
readonly archiveBaseName: string;
readonly installerAssetName: string;
readonly sidecarExecutableName: string;
readonly packagedExecutableName?: string;
readonly appBundleName?: string;
}
function resolveSupportedArch(
platform: SupportedPlatform,
arch: NodeJS.Architecture,
): SupportedArch {
if (arch === 'x64' || arch === 'arm64') {
return arch;
}
throw new Error(`Unsupported architecture for ${platform}: ${arch}`);
}
export function resolveReleaseTarget(
platform: NodeJS.Platform,
arch: NodeJS.Architecture,
): ReleaseTarget {
switch (platform) {
case 'win32': {
const supportedArch = resolveSupportedArch(platform, arch);
const archiveBaseName = `${productName}-windows-${supportedArch}`;
return {
platform,
arch: supportedArch,
platformLabel: 'windows',
dotnetRuntime: `win-${supportedArch}`,
outputDirectoryName: archiveBaseName,
archiveBaseName,
installerAssetName: `${archiveBaseName}-setup.exe`,
sidecarExecutableName: 'Aryx.AgentHost.exe',
packagedExecutableName: `${productName}.exe`,
};
}
case 'darwin': {
const supportedArch = resolveSupportedArch(platform, arch);
const archiveBaseName = `${productName}-macos-${supportedArch}`;
return {
platform,
arch: supportedArch,
platformLabel: 'macos',
dotnetRuntime: `osx-${supportedArch}`,
outputDirectoryName: archiveBaseName,
archiveBaseName,
installerAssetName: `${archiveBaseName}.dmg`,
sidecarExecutableName: 'Aryx.AgentHost',
appBundleName: `${productName}.app`,
};
}
case 'linux': {
const supportedArch = resolveSupportedArch(platform, arch);
const archiveBaseName = `${productName}-linux-${supportedArch}`;
return {
platform,
arch: supportedArch,
platformLabel: 'linux',
dotnetRuntime: `linux-${supportedArch}`,
outputDirectoryName: archiveBaseName,
archiveBaseName,
installerAssetName: `aryx-linux-${supportedArch}.deb`,
sidecarExecutableName: 'Aryx.AgentHost',
packagedExecutableName: productName,
};
}
default:
throw new Error(`Unsupported release platform: ${platform}`);
}
}
@@ -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; } = [];
@@ -337,6 +340,8 @@ public sealed class AgentActivityEventDto : SidecarEventDto
public string? SourceAgentId { get; init; }
public string? SourceAgentName { get; init; }
public string? ToolName { get; init; }
public string? ToolCallId { get; init; }
public IReadOnlyList<ToolCallFileChangeDto>? FileChanges { get; init; }
}
public sealed class SubagentEventDto : SidecarEventDto
@@ -385,6 +390,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;
@@ -469,6 +505,13 @@ public sealed class PermissionDetailDto
public string? HookMessage { get; init; }
}
public sealed class ToolCallFileChangeDto
{
public string Path { get; init; } = string.Empty;
public string? Diff { get; init; }
public string? NewFileContents { get; init; }
}
public sealed class ApprovalRequestedEventDto : 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)
@@ -15,6 +15,7 @@ internal sealed class AryxCopilotAgent : AIAgent, IAsyncDisposable
private const string DefaultName = "GitHub Copilot Agent";
private const string DefaultDescription = "An AI agent powered by GitHub Copilot";
private const string HandoffToolPrefix = "handoff_to_";
private static readonly JsonSerializerOptions ToolArgumentJsonOptions = JsonSerialization.CreateWebOptions();
private readonly CopilotClient _copilotClient;
private readonly string? _id;
private readonly string _name;
@@ -473,11 +474,11 @@ internal sealed class AryxCopilotAgent : AIAgent, IAsyncDisposable
return null;
}
return JsonSerializer.Deserialize<Dictionary<string, object?>>(jsonElement.GetRawText());
return JsonSerializer.Deserialize<Dictionary<string, object?>>(jsonElement.GetRawText(), ToolArgumentJsonOptions);
}
string json = JsonSerializer.Serialize(arguments, arguments.GetType());
return JsonSerializer.Deserialize<Dictionary<string, object?>>(json);
string json = JsonSerializer.Serialize(arguments, arguments.GetType(), ToolArgumentJsonOptions);
return JsonSerializer.Deserialize<Dictionary<string, object?>>(json, ToolArgumentJsonOptions);
}
internal static async Task<(List<UserMessageDataAttachmentsItem>? Attachments, string? MessageMode, string? TempDir)> ProcessMessageAttachmentsAsync(
@@ -601,6 +602,8 @@ internal sealed class AryxCopilotAgent : AIAgent, IAsyncDisposable
internal sealed class AryxCopilotAgentSession : AgentSession
{
private static readonly JsonSerializerOptions DefaultJsonOptions = JsonSerialization.CreateWebOptions();
public AryxCopilotAgentSession()
{
}
@@ -617,7 +620,7 @@ internal sealed class AryxCopilotAgentSession : AgentSession
internal JsonElement Serialize(JsonSerializerOptions? jsonSerializerOptions = null)
{
JsonSerializerOptions options = jsonSerializerOptions ?? new JsonSerializerOptions(JsonSerializerDefaults.Web);
JsonSerializerOptions options = jsonSerializerOptions ?? DefaultJsonOptions;
return JsonSerializer.SerializeToElement(this, options);
}
@@ -630,7 +633,7 @@ internal sealed class AryxCopilotAgentSession : AgentSession
throw new ArgumentException("The serialized session state must be a JSON object.", nameof(serializedState));
}
JsonSerializerOptions options = jsonSerializerOptions ?? new JsonSerializerOptions(JsonSerializerDefaults.Web);
JsonSerializerOptions options = jsonSerializerOptions ?? DefaultJsonOptions;
return serializedState.Deserialize<AryxCopilotAgentSession>(options)
?? new AryxCopilotAgentSession();
}
@@ -103,7 +103,8 @@ internal sealed class CopilotAgentBundle : IAsyncDisposable
definition,
agentIndex,
command.WorkspaceKind,
command.Mode),
command.Mode,
command.ProjectInstructions),
},
WorkingDirectory = command.ProjectPath,
OnPermissionRequest = onPermissionRequest,
@@ -19,6 +19,7 @@ internal sealed class CopilotApprovalCoordinator
private const string MemoryPermissionKind = "memory";
private const string CustomToolPermissionKind = "custom-tool";
private const string HookPermissionKind = "hook";
private const string ToolCallingActivityType = "tool-calling";
private readonly ConcurrentDictionary<string, PendingApprovalRequest> _pendingApprovals = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, ConcurrentDictionary<string, byte>> _requestApprovedTools = new(StringComparer.Ordinal);
@@ -54,12 +55,42 @@ internal sealed class CopilotApprovalCoordinator
IReadOnlyDictionary<string, string> toolNamesByCallId,
Func<ApprovalRequestedEventDto, Task> onApproval,
CancellationToken cancellationToken)
{
return await RequestApprovalAsync(
command,
agent,
request,
invocation,
toolNamesByCallId,
onActivity: null,
onApproval,
cancellationToken)
.ConfigureAwait(false);
}
public async Task<PermissionRequestResult> RequestApprovalAsync(
RunTurnCommandDto command,
PatternAgentDefinitionDto agent,
PermissionRequest request,
PermissionInvocation invocation,
IReadOnlyDictionary<string, string> toolNamesByCallId,
Func<AgentActivityEventDto, Task>? onActivity,
Func<ApprovalRequestedEventDto, Task> onApproval,
CancellationToken cancellationToken)
{
string? toolName = ResolveApprovalToolName(request, toolNamesByCallId);
string? autoApprovedToolName = ResolveAutoApprovedToolName(request);
string? mcpServerApprovalKey = ResolveMcpServerApprovalKey(request);
string? approvalCacheKey = ResolveApprovalCacheKey(toolName, autoApprovedToolName);
AgentActivityEventDto? fileChangeActivity = BuildToolCallFileChangeActivity(command, agent, request, toolName);
if (fileChangeActivity is not null && onActivity is not null)
{
await onActivity(fileChangeActivity).ConfigureAwait(false);
}
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);
}
@@ -153,6 +184,46 @@ internal sealed class CopilotApprovalCoordinator
};
}
internal static AgentActivityEventDto? BuildToolCallFileChangeActivity(
RunTurnCommandDto command,
PatternAgentDefinitionDto agent,
PermissionRequest request,
string? toolName)
{
if (request is not PermissionRequestWrite write)
{
return null;
}
string? filePath = NormalizeOptionalString(write.FileName);
if (filePath is null)
{
return null;
}
string agentName = string.IsNullOrWhiteSpace(agent.Name) ? agent.Id : agent.Name;
return new AgentActivityEventDto
{
Type = "agent-activity",
RequestId = command.RequestId,
SessionId = command.SessionId,
ActivityType = ToolCallingActivityType,
AgentId = NormalizeOptionalString(agent.Id),
AgentName = NormalizeOptionalString(agentName),
ToolName = NormalizeOptionalString(toolName),
ToolCallId = NormalizeOptionalString(write.ToolCallId),
FileChanges =
[
new ToolCallFileChangeDto
{
Path = filePath,
Diff = NormalizeOptionalPreviewText(write.Diff),
NewFileContents = NormalizeOptionalPreviewText(write.NewFileContents),
},
],
};
}
internal static PermissionDetailDto BuildPermissionDetail(PermissionRequest request)
{
ArgumentNullException.ThrowIfNull(request);
@@ -227,7 +298,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 +317,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 +400,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)
@@ -479,6 +565,11 @@ internal sealed class CopilotApprovalCoordinator
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
private static string? NormalizeOptionalPreviewText(string? value)
{
return string.IsNullOrWhiteSpace(value) ? null : value;
}
private static IReadOnlyList<string>? NormalizeOptionalStringList(IEnumerable<string?> values)
{
List<string> normalized = values
@@ -7,13 +7,36 @@ namespace Aryx.AgentHost.Services;
internal static class CopilotSessionHooks
{
private const string AskUserToolName = "ask_user";
private const string AllowDecision = "allow";
private const string AskDecision = "ask";
private const string DenyDecision = "deny";
private static readonly JsonSerializerOptions HookJsonOptions = new(JsonSerializerDefaults.Web)
private const string ExitPlanModeToolName = "exit_plan_mode";
private const string FetchCopilotCliDocumentationToolName = "fetch_copilot_cli_documentation";
private const string HandoffToolPrefix = "handoff_to_";
private const string ListAgentsToolName = "list_agents";
private const string ReadAgentToolName = "read_agent";
private const string ReportIntentToolName = "report_intent";
private const string SkillToolName = "skill";
private const string SqlToolName = "sql";
private const string TaskToolName = "task";
private const string TaskCompleteToolName = "task_complete";
private const string UpdateTodoToolName = "update_todo";
private static readonly HashSet<string> AlwaysAllowedToolNames = new(StringComparer.OrdinalIgnoreCase)
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
AskUserToolName,
ExitPlanModeToolName,
FetchCopilotCliDocumentationToolName,
ListAgentsToolName,
ReadAgentToolName,
ReportIntentToolName,
SkillToolName,
SqlToolName,
TaskToolName,
TaskCompleteToolName,
UpdateTodoToolName,
};
private static readonly JsonSerializerOptions HookJsonOptions = CreateHookJsonOptions();
public static SessionHooks Create(
RunTurnCommandDto command,
@@ -216,11 +239,20 @@ internal static class CopilotSessionHooks
PatternAgentDefinitionDto agentDefinition,
PreToolUseHookInput input)
{
string? toolName = Normalize(input.ToolName);
if (IsAlwaysAllowedTool(toolName))
{
return new PreToolUseHookOutput
{
PermissionDecision = AllowDecision,
};
}
bool requiresApproval = CopilotApprovalCoordinator.RequiresToolCallApproval(
command.Pattern.ApprovalPolicy,
agentDefinition.Id,
Normalize(input.ToolName),
Normalize(input.ToolName));
toolName,
toolName);
return new PreToolUseHookOutput
{
@@ -262,6 +294,21 @@ internal static class CopilotSessionHooks
private static string SerializeHookValue(object? value)
=> JsonSerializer.Serialize(value, HookJsonOptions);
private static JsonSerializerOptions CreateHookJsonOptions()
{
JsonSerializerOptions options = JsonSerialization.CreateWebOptions();
options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
return options;
}
private static bool IsAlwaysAllowedTool(string? toolName)
{
string? normalizedToolName = Normalize(toolName);
return normalizedToolName is not null
&& (AlwaysAllowedToolNames.Contains(normalizedToolName)
|| normalizedToolName.StartsWith(HandoffToolPrefix, StringComparison.OrdinalIgnoreCase));
}
private static string? Normalize(string? value)
=> string.IsNullOrWhiteSpace(value) ? null : value.Trim();
@@ -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
@@ -50,6 +50,7 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner
request,
invocation,
state.ToolNamesByCallId,
activity => EmitActivityAsync(command, state, activity, onEvent),
onApproval,
runCancellation.Token),
(agent, request, invocation) => _userInputCoordinator.RequestUserInputAsync(
@@ -5,12 +5,7 @@ namespace Aryx.AgentHost.Services;
internal static class HookConfigLoader
{
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
{
AllowTrailingCommas = true,
PropertyNameCaseInsensitive = true,
ReadCommentHandling = JsonCommentHandling.Skip,
};
private static readonly JsonSerializerOptions JsonOptions = CreateJsonOptions();
public static async Task<ResolvedHookSet> LoadAsync(string projectPath, CancellationToken cancellationToken)
{
@@ -204,4 +199,13 @@ internal static class HookConfigLoader
private static string? NormalizeOptionalString(string? value)
=> string.IsNullOrWhiteSpace(value) ? null : value.Trim();
private static JsonSerializerOptions CreateJsonOptions()
{
JsonSerializerOptions options = JsonSerialization.CreateWebOptions();
options.AllowTrailingCommas = true;
options.PropertyNameCaseInsensitive = true;
options.ReadCommentHandling = JsonCommentHandling.Skip;
return options;
}
}
@@ -12,5 +12,8 @@ public interface ICopilotSessionManager
string? aryxSessionId,
string? copilotSessionId,
CancellationToken cancellationToken);
Task<IReadOnlyDictionary<string, QuotaSnapshotDto>> GetQuotaAsync(
CancellationToken cancellationToken);
}
@@ -0,0 +1,15 @@
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
namespace Aryx.AgentHost.Services;
internal static class JsonSerialization
{
public static JsonSerializerOptions CreateWebOptions()
{
return new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
TypeInfoResolver = new DefaultJsonTypeInfoResolver(),
};
}
}
@@ -0,0 +1,109 @@
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 = CreateJsonOptions();
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);
}
private static JsonSerializerOptions CreateJsonOptions()
{
JsonSerializerOptions options = JsonSerialization.CreateWebOptions();
options.PropertyNameCaseInsensitive = true;
return options;
}
}
@@ -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)
{
@@ -66,11 +67,9 @@ public sealed class SidecarProtocolHost
_workflowRunner = workflowRunner ?? new CopilotWorkflowRunner(_patternValidator);
_capabilitiesProvider = capabilitiesProvider ?? BuildCapabilitiesAsync;
_sessionManager = sessionManager ?? new CopilotSessionManager();
_jsonOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
PropertyNameCaseInsensitive = true,
};
_jsonOptions = JsonSerialization.CreateWebOptions();
_jsonOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
_jsonOptions.PropertyNameCaseInsensitive = true;
_commandHandlers = new Dictionary<string, Func<CommandContext, Task>>(StringComparer.Ordinal)
{
[DescribeCapabilitiesCommandType] = HandleDescribeCapabilitiesAsync,
@@ -82,6 +81,7 @@ public sealed class SidecarProtocolHost
[ListSessionsCommandType] = HandleListSessionsAsync,
[DeleteSessionCommandType] = HandleDeleteSessionAsync,
[DisconnectSessionCommandType] = HandleDisconnectSessionAsync,
[GetQuotaCommandType] = HandleGetQuotaAsync,
};
}
@@ -313,6 +313,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
{
@@ -12,6 +12,7 @@ internal static class WorkflowRequestInfoInterpreter
private const string ToolCallingActivityType = "tool-calling";
private const string CodeInterpreterToolName = "code interpreter";
private const string ImageGenerationToolName = "image generation";
private static readonly JsonSerializerOptions JsonOptions = JsonSerialization.CreateWebOptions();
public static AgentActivityEventDto? TryCreateActivityFromRequest(
RunTurnCommandDto command,
@@ -73,6 +74,7 @@ internal static class WorkflowRequestInfoInterpreter
AgentId = activeAgent.AgentId,
AgentName = activeAgent.AgentName,
ToolName = tool.ToolName,
ToolCallId = tool.ToolCallId,
};
}
@@ -193,8 +195,8 @@ internal static class WorkflowRequestInfoInterpreter
private static WorkflowRequestHandoffPayload? DeserializeHandoffPayload(object handoffValue)
{
string json = JsonSerializer.Serialize(handoffValue, handoffValue.GetType());
return JsonSerializer.Deserialize<WorkflowRequestHandoffPayload>(json);
string json = JsonSerializer.Serialize(handoffValue, handoffValue.GetType(), JsonOptions);
return JsonSerializer.Deserialize<WorkflowRequestHandoffPayload>(json, JsonOptions);
}
private abstract record RequestInterpretation;
@@ -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()
{
@@ -106,6 +106,51 @@ public sealed class CopilotSessionHooksTests
Assert.Single(runner.Invocations);
}
[Theory]
[InlineData("ask_user")]
[InlineData("exit_plan_mode")]
[InlineData("fetch_copilot_cli_documentation")]
[InlineData("list_agents")]
[InlineData("read_agent")]
[InlineData("report_intent")]
[InlineData("skill")]
[InlineData("sql")]
[InlineData("task")]
[InlineData("task_complete")]
[InlineData("update_todo")]
[InlineData("handoff_to_2")]
[InlineData("handoff_to_specialist")]
public async Task Create_PreToolUseAutoAllowsInternalOrchestrationTools(string toolName)
{
RunTurnCommandDto command = CreateCommandWithToolApproval();
SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], ResolvedHookSet.Empty, new RecordingHookCommandRunner());
PreToolUseHookOutput? decision = await hooks.OnPreToolUse!(
new PreToolUseHookInput
{
ToolName = toolName,
},
null!);
Assert.Equal("allow", decision?.PermissionDecision);
}
[Fact]
public async Task Create_PreToolUseKeepsStoreMemoryUnderApprovalPolicy()
{
RunTurnCommandDto command = CreateCommandWithToolApproval();
SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], ResolvedHookSet.Empty, new RecordingHookCommandRunner());
PreToolUseHookOutput? decision = await hooks.OnPreToolUse!(
new PreToolUseHookInput
{
ToolName = "store_memory",
},
null!);
Assert.Equal("ask", decision?.PermissionDecision);
}
[Fact]
public async Task Create_RunsConfiguredNonPreToolHooks()
{
@@ -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()
{
@@ -1338,6 +1368,70 @@ public sealed class CopilotWorkflowRunnerTests
Assert.Equal(PermissionRequestResultKind.Approved, result.Kind);
}
[Fact]
public async Task RequestApprovalAsync_EmitsFileChangeActivityForWriteRequests()
{
CopilotApprovalCoordinator coordinator = new();
AgentActivityEventDto? observedActivity = null;
ApprovalRequestedEventDto? observedApproval = null;
RunTurnCommandDto command = CreateApprovalCommand();
Task<PermissionRequestResult> pending = coordinator.RequestApprovalAsync(
command,
command.Pattern.Agents[0],
new PermissionRequestWrite
{
Kind = "write",
ToolCallId = "tool-call-write-1",
Intention = "Update the README",
FileName = "README.md",
Diff = "@@ -1 +1 @@",
NewFileContents = "# Aryx\n",
},
new PermissionInvocation
{
SessionId = "copilot-session-1",
},
new Dictionary<string, string>(StringComparer.Ordinal)
{
["tool-call-write-1"] = "apply_patch",
},
activity =>
{
observedActivity = activity;
return Task.CompletedTask;
},
approval =>
{
observedApproval = approval;
return Task.CompletedTask;
},
CancellationToken.None);
Assert.False(pending.IsCompleted);
Assert.NotNull(observedActivity);
Assert.NotNull(observedApproval);
Assert.Equal("tool-calling", observedActivity!.ActivityType);
Assert.Equal("apply_patch", observedActivity.ToolName);
Assert.Equal("tool-call-write-1", observedActivity.ToolCallId);
ToolCallFileChangeDto preview = Assert.Single(observedActivity.FileChanges!);
Assert.Equal("README.md", preview.Path);
Assert.Equal("@@ -1 +1 @@", preview.Diff);
Assert.Equal("# Aryx\n", preview.NewFileContents);
await coordinator.ResolveApprovalAsync(
new ResolveApprovalCommandDto
{
ApprovalId = observedApproval!.ApprovalId,
Decision = "approved",
},
CancellationToken.None);
PermissionRequestResult result = await pending;
Assert.Equal(PermissionRequestResultKind.Approved, result.Kind);
}
[Fact]
public async Task RequestApprovalAsync_AutoApprovesToolsThatDoNotRequireApproval()
{
@@ -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(
@@ -0,0 +1,41 @@
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using Aryx.AgentHost.Services;
namespace Aryx.AgentHost.Tests;
public sealed class JsonSerializationTests
{
[Fact]
public void CreateWebOptions_UsesDefaultJsonTypeInfoResolver()
{
JsonSerializerOptions options = JsonSerialization.CreateWebOptions();
Assert.IsType<DefaultJsonTypeInfoResolver>(options.TypeInfoResolver);
}
[Fact]
public void CreateWebOptions_RoundTripsRuntimeTypedPayloads()
{
JsonSerializerOptions options = JsonSerialization.CreateWebOptions();
object payload = new TestPayload
{
Type = "describe-capabilities",
RequestId = "req-1",
};
string json = JsonSerializer.Serialize(payload, payload.GetType(), options);
TestPayload? deserialized = JsonSerializer.Deserialize<TestPayload>(json, options);
Assert.NotNull(deserialized);
Assert.Equal("describe-capabilities", deserialized.Type);
Assert.Equal("req-1", deserialized.RequestId);
}
private sealed class TestPayload
{
public string? Type { get; init; }
public string? RequestId { get; init; }
}
}
@@ -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);
}
}
}
+886 -122
View File
File diff suppressed because it is too large Load Diff
+45 -4
View File
@@ -3,43 +3,84 @@ import type { BrowserWindow as BrowserWindowType } from 'electron';
import { registerIpcHandlers } from '@main/ipc/registerIpcHandlers';
import { AryxAppService } from '@main/AryxAppService';
import { AutoUpdateService } from '@main/services/autoUpdater';
import { createMainWindow } from '@main/windows/createMainWindow';
import { applyTitleBarTheme } from '@main/windows/titleBarTheme';
import { SystemTray, setupCloseToTray, showAndFocusWindow } from '@main/services/systemTray';
const { app, BrowserWindow } = electron;
let mainWindow: BrowserWindowType | undefined;
let appService: AryxAppService | undefined;
let systemTray: SystemTray | undefined;
let autoUpdateService: AutoUpdateService | undefined;
async function bootstrap(): Promise<void> {
appService = new AryxAppService();
autoUpdateService?.dispose();
autoUpdateService = new AutoUpdateService({ isPackaged: app.isPackaged });
mainWindow = createMainWindow();
registerIpcHandlers(mainWindow, appService);
registerIpcHandlers(mainWindow, appService, autoUpdateService);
// Apply persisted theme to the title bar overlay
const workspace = await appService.loadWorkspace();
applyTitleBarTheme(mainWindow, workspace.settings.theme);
// Set up system tray
systemTray = new SystemTray({
onShowWindow: showAndFocusWindow,
onCreateScratchpad: () => {
showAndFocusWindow();
mainWindow?.webContents.send('tray:create-scratchpad');
},
onQuit: () => app.quit(),
});
systemTray.create();
systemTray.updateRunningCount(workspace);
// Intercept close to hide to tray when the setting is enabled
setupCloseToTray(mainWindow, () => {
const currentWorkspace = appService?.getCachedWorkspace();
return currentWorkspace?.settings.minimizeToTray === true;
});
// Keep tray status in sync when workspace changes
appService.on('workspace-updated', (updatedWorkspace) => {
systemTray?.updateRunningCount(updatedWorkspace);
});
if (!app.isPackaged) {
mainWindow.webContents.openDevTools({ mode: 'detach' });
}
autoUpdateService.start();
}
app.whenReady().then(bootstrap);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
// When minimize-to-tray is enabled, don't quit on window close
if (process.platform === 'darwin') return;
const windows = BrowserWindow.getAllWindows();
const allHidden = windows.length > 0 && windows.every((w) => !w.isVisible());
if (allHidden) return;
app.quit();
});
app.on('activate', async () => {
if (BrowserWindow.getAllWindows().length === 0) {
await bootstrap();
} else {
showAndFocusWindow();
}
});
app.on('before-quit', async () => {
autoUpdateService?.dispose();
autoUpdateService = undefined;
systemTray?.dispose();
await appService?.dispose();
});
+96 -6
View File
@@ -3,40 +3,55 @@ import type { BrowserWindow } from 'electron';
import { ipcChannels } from '@shared/contracts/channels';
import type {
BranchSessionInput,
CancelSessionTurnInput,
CreateSessionInput,
ResolveProjectDiscoveredToolingInput,
ResolveWorkspaceDiscoveredToolingInput,
DismissSessionPlanReviewInput,
DismissSessionMcpAuthInput,
DismissSessionPlanReviewInput,
DeleteSessionInput,
EditAndResendSessionMessageInput,
RegenerateSessionMessageInput,
StartSessionMcpAuthInput,
DuplicateSessionInput,
RenameSessionInput,
RescanProjectConfigsInput,
RescanProjectCustomizationInput,
ResolveProjectDiscoveredToolingInput,
ResolveSessionApprovalInput,
ResolveSessionUserInputInput,
ResolveWorkspaceDiscoveredToolingInput,
SaveLspProfileInput,
SaveMcpServerInput,
SavePatternInput,
SendSessionMessageInput,
SetPatternFavoriteInput,
SetProjectAgentProfileEnabledInput,
SetSessionArchivedInput,
SetSessionInteractionModeInput,
SetSessionMessagePinnedInput,
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';
import { AryxAppService } from '@main/AryxAppService';
import { AutoUpdateService } from '@main/services/autoUpdater';
import { createDesktopNotificationHandler } from '@main/services/desktopNotifications';
import { applyTitleBarTheme } from '@main/windows/titleBarTheme';
import type { UpdateStatus } from '@shared/contracts/ipc';
const { ipcMain } = electron;
export function registerIpcHandlers(window: BrowserWindow, service: AryxAppService): void {
export function registerIpcHandlers(
window: BrowserWindow,
service: AryxAppService,
autoUpdateService: AutoUpdateService,
): void {
ipcMain.handle(ipcChannels.describeSidecarCapabilities, () => service.describeSidecarCapabilities());
ipcMain.handle(ipcChannels.refreshSidecarCapabilities, () => service.refreshSidecarCapabilities());
ipcMain.handle(ipcChannels.loadWorkspace, () => service.loadWorkspace());
@@ -53,11 +68,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 +93,22 @@ 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.setNotificationsEnabled,
(_event, enabled: boolean) => service.setNotificationsEnabled(enabled),
);
ipcMain.handle(
ipcChannels.setMinimizeToTray,
(_event, enabled: boolean) => service.setMinimizeToTray(enabled),
);
ipcMain.handle(ipcChannels.checkForUpdates, () => autoUpdateService.checkForUpdates());
ipcMain.handle(ipcChannels.installUpdate, () => {
autoUpdateService.installUpdate();
});
ipcMain.handle(ipcChannels.saveMcpServer, (_event, input: SaveMcpServerInput) =>
service.saveMcpServer(input.server),
);
@@ -80,6 +121,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,
@@ -98,6 +149,12 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
ipcMain.handle(ipcChannels.duplicateSession, (_event, input: DuplicateSessionInput) =>
service.duplicateSession(input.sessionId),
);
ipcMain.handle(ipcChannels.branchSession, (_event, input: BranchSessionInput) =>
service.branchSession(input.sessionId, input.messageId),
);
ipcMain.handle(ipcChannels.setSessionMessagePinned, (_event, input: SetSessionMessagePinnedInput) =>
service.setSessionMessagePinned(input.sessionId, input.messageId, input.isPinned),
);
ipcMain.handle(ipcChannels.renameSession, (_event, input: RenameSessionInput) =>
service.renameSession(input.sessionId, input.title),
);
@@ -110,6 +167,12 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
ipcMain.handle(ipcChannels.deleteSession, (_event, input: DeleteSessionInput) =>
service.deleteSession(input.sessionId),
);
ipcMain.handle(ipcChannels.regenerateSessionMessage, (_event, input: RegenerateSessionMessageInput) =>
service.regenerateSessionMessage(input.sessionId, input.messageId),
);
ipcMain.handle(ipcChannels.editAndResendSessionMessage, (_event, input: EditAndResendSessionMessageInput) =>
service.editAndResendSessionMessage(input.sessionId, input.messageId, input.content, input.attachments),
);
ipcMain.handle(ipcChannels.sendSessionMessage, (_event, input: SendSessionMessageInput) =>
service.sendSessionMessage(input.sessionId, input.content, input.attachments, input.messageMode),
);
@@ -145,6 +208,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 +217,30 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
service.on('session-event', (event) => {
window.webContents.send(ipcChannels.sessionEvent, event);
});
// Desktop notifications for run completion, failure, and approval requests
const handleNotification = createDesktopNotificationHandler(
() => window,
() => service.getCachedWorkspace(),
(sessionId) => service.selectSession(sessionId),
);
service.on('session-event', handleNotification);
const sendUpdateStatus = (status: UpdateStatus) => {
if (!window.isDestroyed()) {
window.webContents.send(ipcChannels.updateStatus, status);
}
};
autoUpdateService.onStatus(sendUpdateStatus);
window.webContents.on('did-finish-load', () => {
sendUpdateStatus(autoUpdateService.getStatus());
});
service.on('terminal-data', (data) => {
window.webContents.send(ipcChannels.terminalData, data);
});
service.on('terminal-exit', (info) => {
window.webContents.send(ipcChannels.terminalExit, info);
});
}
+6 -2
View File
@@ -4,8 +4,9 @@ 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 { normalizeSessionBranchOrigin, type SessionRecord } from '@shared/domain/session';
import {
normalizeSessionToolingSelection,
normalizeWorkspaceSettings,
@@ -73,12 +74,14 @@ export class WorkspaceRepository {
(stored.projects ?? []).map((project) => ({
...project,
discoveredTooling: normalizeDiscoveredToolingState(project.discoveredTooling),
customization: normalizeProjectCustomizationState(project.customization),
})),
this.scratchpadPath,
);
const sessions = await Promise.all((stored.sessions ?? []).map(async (session): Promise<SessionRecord> => {
const normalizedSession: SessionRecord = {
...session,
branchOrigin: normalizeSessionBranchOrigin(session.branchOrigin),
runs: normalizeSessionRunRecords(session.runs),
tooling: normalizeSessionToolingSelection(session.tooling),
approvalSettings: normalizeSessionApprovalSettings(session.approvalSettings),
@@ -121,8 +124,9 @@ export class WorkspaceRepository {
}
async save(workspace: WorkspaceState): Promise<void> {
const { mcpProbingServerIds: _mcpProbingServerIds, ...persistedWorkspace } = workspace;
await writeJsonFile(this.filePath, {
...workspace,
...persistedWorkspace,
lastUpdatedAt: nowIso(),
});
}
+281
View File
@@ -0,0 +1,281 @@
import electronUpdater from 'electron-updater';
import type {
UpdateDownloadProgress,
UpdateStatus,
} from '@shared/contracts/ipc';
interface AutoUpdateInfoLike {
version?: string | null;
releaseDate?: string | null;
releaseNotes?: unknown;
}
interface AutoUpdateProgressLike {
bytesPerSecond: number;
percent: number;
total: number;
transferred: number;
}
type AutoUpdateListener = (...args: any[]) => void;
interface AutoUpdaterLike {
autoDownload: boolean;
autoInstallOnAppQuit: boolean;
on(event: string, listener: AutoUpdateListener): this;
removeListener(event: string, listener: AutoUpdateListener): this;
checkForUpdates(): Promise<unknown>;
quitAndInstall(): void;
}
export interface AutoUpdateScheduler {
setTimeout(callback: () => void, delayMs: number): unknown;
clearTimeout(handle: unknown): void;
setInterval(callback: () => void, delayMs: number): unknown;
clearInterval(handle: unknown): void;
}
export interface AutoUpdateServiceOptions {
isPackaged: boolean;
startupDelayMs?: number;
recheckIntervalMs?: number;
updater?: AutoUpdaterLike;
scheduler?: AutoUpdateScheduler;
}
const DEFAULT_STARTUP_DELAY_MS = 10_000;
const DEFAULT_RECHECK_INTERVAL_MS = 4 * 60 * 60 * 1000;
const defaultScheduler: AutoUpdateScheduler = {
setTimeout: (callback, delayMs) => globalThis.setTimeout(callback, delayMs),
clearTimeout: (handle) => globalThis.clearTimeout(handle as ReturnType<typeof setTimeout>),
setInterval: (callback, delayMs) => globalThis.setInterval(callback, delayMs),
clearInterval: (handle) => globalThis.clearInterval(handle as ReturnType<typeof setInterval>),
};
function normalizeOptionalString(value: string | null | undefined): string | undefined {
const trimmed = value?.trim();
return trimmed ? trimmed : undefined;
}
function normalizeReleaseNotes(value: unknown): string | undefined {
if (typeof value === 'string') {
return normalizeOptionalString(value);
}
if (!Array.isArray(value)) {
return undefined;
}
const notes = value
.map((item) => {
if (typeof item === 'string') {
return normalizeOptionalString(item);
}
if (!item || typeof item !== 'object') {
return undefined;
}
const record = item as { note?: unknown; version?: unknown };
const version = typeof record.version === 'string' ? normalizeOptionalString(record.version) : undefined;
const note = typeof record.note === 'string' ? normalizeOptionalString(record.note) : undefined;
if (version && note) {
return `${version}\n${note}`;
}
return note ?? version;
})
.filter((entry): entry is string => Boolean(entry));
return notes.length > 0 ? notes.join('\n\n') : undefined;
}
function normalizeProgress(progress: AutoUpdateProgressLike): UpdateDownloadProgress {
return {
bytesPerSecond: progress.bytesPerSecond,
percent: progress.percent,
total: progress.total,
transferred: progress.transferred,
};
}
function createStatusFromInfo(
state: Extract<UpdateStatus['state'], 'available' | 'downloaded'>,
info: AutoUpdateInfoLike,
): UpdateStatus {
return {
state,
version: normalizeOptionalString(info.version),
releaseDate: normalizeOptionalString(info.releaseDate),
releaseNotes: normalizeReleaseNotes(info.releaseNotes),
};
}
function resolveErrorMessage(error: unknown): string {
if (error instanceof Error) {
return error.message;
}
if (typeof error === 'string') {
return error;
}
return 'Unknown update error.';
}
export class AutoUpdateService {
private readonly updater: AutoUpdaterLike;
private readonly scheduler: AutoUpdateScheduler;
private readonly listeners = new Set<(status: UpdateStatus) => void>();
private status: UpdateStatus = { state: 'idle' };
private started = false;
private initialCheckHandle?: unknown;
private periodicCheckHandle?: unknown;
private pendingCheck?: Promise<UpdateStatus>;
private readonly checkingListener = () => {
this.publishStatus({ state: 'checking' });
};
private readonly availableListener = (info: AutoUpdateInfoLike) => {
this.publishStatus(createStatusFromInfo('available', info));
};
private readonly notAvailableListener = () => {
this.publishStatus({ state: 'idle' });
};
private readonly progressListener = (progress: AutoUpdateProgressLike) => {
this.publishStatus({
...this.status,
state: 'downloading',
downloadProgress: normalizeProgress(progress),
});
};
private readonly downloadedListener = (info: AutoUpdateInfoLike) => {
this.publishStatus(createStatusFromInfo('downloaded', info));
};
private readonly errorListener = (error: unknown) => {
this.publishStatus({
...this.status,
state: 'error',
error: resolveErrorMessage(error),
});
};
constructor(private readonly options: AutoUpdateServiceOptions) {
this.updater = options.updater
?? (electronUpdater as { autoUpdater: AutoUpdaterLike }).autoUpdater;
this.scheduler = options.scheduler ?? defaultScheduler;
this.updater.autoDownload = true;
this.updater.autoInstallOnAppQuit = false;
this.updater.on('checking-for-update', this.checkingListener);
this.updater.on('update-available', this.availableListener);
this.updater.on('update-not-available', this.notAvailableListener);
this.updater.on('download-progress', this.progressListener);
this.updater.on('update-downloaded', this.downloadedListener);
this.updater.on('error', this.errorListener);
}
start(): void {
if (this.started || !this.options.isPackaged) {
return;
}
this.started = true;
this.initialCheckHandle = this.scheduler.setTimeout(() => {
void this.checkForUpdates();
}, this.options.startupDelayMs ?? DEFAULT_STARTUP_DELAY_MS);
this.periodicCheckHandle = this.scheduler.setInterval(() => {
void this.checkForUpdates();
}, this.options.recheckIntervalMs ?? DEFAULT_RECHECK_INTERVAL_MS);
}
getStatus(): UpdateStatus {
return this.cloneStatus(this.status);
}
onStatus(listener: (status: UpdateStatus) => void): () => void {
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
};
}
async checkForUpdates(): Promise<UpdateStatus> {
if (!this.options.isPackaged) {
return this.getStatus();
}
if (this.pendingCheck) {
return this.pendingCheck;
}
const request = this.updater.checkForUpdates()
.catch((error) => {
this.errorListener(error);
})
.then(() => this.getStatus())
.finally(() => {
if (this.pendingCheck === request) {
this.pendingCheck = undefined;
}
});
this.pendingCheck = request;
return request;
}
installUpdate(): void {
if (this.status.state !== 'downloaded') {
return;
}
this.updater.quitAndInstall();
}
dispose(): void {
if (this.initialCheckHandle !== undefined) {
this.scheduler.clearTimeout(this.initialCheckHandle);
this.initialCheckHandle = undefined;
}
if (this.periodicCheckHandle !== undefined) {
this.scheduler.clearInterval(this.periodicCheckHandle);
this.periodicCheckHandle = undefined;
}
this.updater.removeListener('checking-for-update', this.checkingListener);
this.updater.removeListener('update-available', this.availableListener);
this.updater.removeListener('update-not-available', this.notAvailableListener);
this.updater.removeListener('download-progress', this.progressListener);
this.updater.removeListener('update-downloaded', this.downloadedListener);
this.updater.removeListener('error', this.errorListener);
this.listeners.clear();
}
private publishStatus(status: UpdateStatus): void {
this.status = this.cloneStatus(status);
for (const listener of this.listeners) {
listener(this.cloneStatus(this.status));
}
}
private cloneStatus(status: UpdateStatus): UpdateStatus {
return status.downloadProgress
? { ...status, downloadProgress: { ...status.downloadProgress } }
: { ...status };
}
}
+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);
}
+86
View File
@@ -0,0 +1,86 @@
import electron from 'electron';
import type { BrowserWindow } from 'electron';
import type { SessionEventRecord } from '@shared/domain/event';
import type { WorkspaceState } from '@shared/domain/workspace';
const { Notification } = electron;
/**
* Creates a handler that shows native OS notifications for session run
* completions, failures, and approval requests when the window is unfocused.
*
* Clicking a notification focuses the window and selects the relevant session.
*/
export function createDesktopNotificationHandler(
getWindow: () => BrowserWindow | undefined,
getWorkspace: () => WorkspaceState | undefined,
selectSession: (sessionId: string) => Promise<WorkspaceState>,
): (event: SessionEventRecord) => void {
const runningSessions = new Set<string>();
const notifiedApprovals = new Set<string>();
return (event: SessionEventRecord) => {
const window = getWindow();
if (window?.isFocused()) return;
const workspace = getWorkspace();
if (workspace?.settings.notificationsEnabled === false) return;
if (!Notification.isSupported()) return;
const session = workspace?.sessions.find((s) => s.id === event.sessionId);
const sessionTitle = session?.title ?? 'Session';
// Track running sessions to detect completion/failure transitions
if (event.kind === 'status') {
if (event.status === 'running') {
runningSessions.add(event.sessionId);
return;
}
if (!runningSessions.has(event.sessionId)) return;
runningSessions.delete(event.sessionId);
if (event.status === 'idle') {
showNotification('Run completed', sessionTitle, event.sessionId, window, selectSession);
} else if (event.status === 'error') {
showNotification('Run failed', sessionTitle, event.sessionId, window, selectSession);
}
return;
}
// Detect new approval requests from run-updated events
if (event.kind === 'run-updated' && event.run) {
const approvalEvent = [...event.run.events]
.reverse()
.find((e) => e.kind === 'approval' && e.status === 'running');
if (approvalEvent?.approvalId && !notifiedApprovals.has(approvalEvent.approvalId)) {
notifiedApprovals.add(approvalEvent.approvalId);
const body = approvalEvent.approvalTitle
? `${sessionTitle}: ${approvalEvent.approvalTitle}`
: sessionTitle;
showNotification('Approval needed', body, event.sessionId, window, selectSession);
}
}
};
}
function showNotification(
title: string,
body: string,
sessionId: string,
window: BrowserWindow | undefined,
selectSession: (sessionId: string) => Promise<WorkspaceState>,
): void {
const notification = new Notification({ title, body, silent: false });
notification.on('click', () => {
window?.show();
window?.focus();
void selectSession(sessionId);
});
notification.show();
}
+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;
}
}
+142
View File
@@ -0,0 +1,142 @@
import electron from 'electron';
import { join } from 'node:path';
import type { WorkspaceState } from '@shared/domain/workspace';
const { app, Menu, Tray, nativeImage, BrowserWindow } = electron;
type TrayType = InstanceType<typeof Tray>;
type NativeImageType = ReturnType<typeof nativeImage.createFromPath>;
export interface SystemTrayOptions {
onShowWindow: () => void;
onCreateScratchpad: () => void;
onQuit: () => void;
}
function resolveTrayIcon(): NativeImageType {
const basePath = app.getAppPath();
if (process.platform === 'win32') {
return nativeImage.createFromPath(join(basePath, 'assets', 'icons', 'windows', 'icon.ico'));
}
// Use a smaller icon for tray on Linux/macOS — 32x32 for crispness
const pngPath =
process.platform === 'linux'
? join(basePath, 'assets', 'icons', 'linux', 'icons', '32x32.png')
: join(basePath, 'assets', 'icons', 'icon.png');
const image = nativeImage.createFromPath(pngPath);
// Resize to 16x16 for system tray standard size
return image.resize({ width: 16, height: 16 });
}
function buildContextMenu(options: SystemTrayOptions, runningCount: number): Electron.Menu {
const statusLabel =
runningCount > 0 ? `${runningCount} session${runningCount > 1 ? 's' : ''} running` : 'No active sessions';
return Menu.buildFromTemplate([
{ label: 'Open Aryx', click: options.onShowWindow, type: 'normal' },
{ type: 'separator' },
{ label: 'Quick Scratchpad', click: options.onCreateScratchpad, type: 'normal' },
{ type: 'separator' },
{ label: statusLabel, enabled: false, type: 'normal' },
{ type: 'separator' },
{ label: 'Quit', click: options.onQuit, type: 'normal' },
]);
}
export class SystemTray {
private tray: TrayType | null = null;
private options: SystemTrayOptions;
private runningCount = 0;
constructor(options: SystemTrayOptions) {
this.options = options;
}
create(): void {
if (this.tray) return;
const icon = resolveTrayIcon();
this.tray = new Tray(icon);
this.tray.setToolTip('Aryx');
this.tray.setContextMenu(buildContextMenu(this.options, this.runningCount));
this.tray.on('click', () => {
this.options.onShowWindow();
});
}
updateRunningCount(workspace: WorkspaceState): void {
const count = workspace.sessions.filter((s) => !s.isArchived && s.status === 'running').length;
if (count === this.runningCount) return;
this.runningCount = count;
this.tray?.setContextMenu(buildContextMenu(this.options, count));
const tooltip = count > 0 ? `Aryx — ${count} running` : 'Aryx';
this.tray?.setToolTip(tooltip);
}
isMinimizeToTrayEnabled(workspace: WorkspaceState): boolean {
return workspace.settings.minimizeToTray === true;
}
dispose(): void {
this.tray?.destroy();
this.tray = null;
}
}
/**
* Intercept window close to hide to tray instead of quitting, when the setting is enabled.
* Returns true if the close was intercepted (window hidden), false if it should proceed normally.
*/
export function setupCloseToTray(
window: Electron.BrowserWindow,
getMinimizeToTray: () => boolean,
): void {
let forceQuit = false;
// On macOS, Cmd+Q triggers before-quit before the close event
app.on('before-quit', () => {
forceQuit = true;
});
window.on('close', (event) => {
if (forceQuit) return;
if (getMinimizeToTray()) {
event.preventDefault();
window.hide();
// On macOS, also hide from the dock when minimized to tray
if (process.platform === 'darwin') {
app.dock?.hide();
}
}
});
}
/**
* Show and focus the main window, restoring from tray if hidden.
*/
export function showAndFocusWindow(): void {
const windows = BrowserWindow.getAllWindows();
const mainWindow = windows[0];
if (!mainWindow) return;
// On macOS, show the dock icon again
if (process.platform === 'darwin') {
app.dock?.show();
}
if (mainWindow.isMinimized()) {
mainWindow.restore();
}
mainWindow.show();
mainWindow.focus();
}
+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);
+51
View File
@@ -15,25 +15,48 @@ 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),
setNotificationsEnabled: (enabled) => ipcRenderer.invoke(ipcChannels.setNotificationsEnabled, enabled),
setMinimizeToTray: (enabled) => ipcRenderer.invoke(ipcChannels.setMinimizeToTray, enabled),
checkForUpdates: () => ipcRenderer.invoke(ipcChannels.checkForUpdates),
installUpdate: () => ipcRenderer.invoke(ipcChannels.installUpdate),
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),
createSession: (input) => ipcRenderer.invoke(ipcChannels.createSession, input),
duplicateSession: (input) => ipcRenderer.invoke(ipcChannels.duplicateSession, input),
branchSession: (input) => ipcRenderer.invoke(ipcChannels.branchSession, input),
setSessionMessagePinned: (input) => ipcRenderer.invoke(ipcChannels.setSessionMessagePinned, input),
renameSession: (input) => ipcRenderer.invoke(ipcChannels.renameSession, input),
setSessionPinned: (input) => ipcRenderer.invoke(ipcChannels.setSessionPinned, input),
setSessionArchived: (input) => ipcRenderer.invoke(ipcChannels.setSessionArchived, input),
deleteSession: (input) => ipcRenderer.invoke(ipcChannels.deleteSession, input),
regenerateSessionMessage: (input) => ipcRenderer.invoke(ipcChannels.regenerateSessionMessage, input),
editAndResendSessionMessage: (input) => ipcRenderer.invoke(ipcChannels.editAndResendSessionMessage, input),
sendSessionMessage: (input) => ipcRenderer.invoke(ipcChannels.sendSessionMessage, input),
cancelSessionTurn: (input) => ipcRenderer.invoke(ipcChannels.cancelSessionTurn, input),
resolveSessionApproval: (input) => ipcRenderer.invoke(ipcChannels.resolveSessionApproval, input),
@@ -50,6 +73,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);
@@ -64,6 +102,19 @@ const api: ElectronApi = {
ipcRenderer.on(ipcChannels.sessionEvent, handler);
return () => ipcRenderer.off(ipcChannels.sessionEvent, handler);
},
onUpdateStatus: (listener) => {
const handler = (_event: Electron.IpcRendererEvent, status: Parameters<typeof listener>[0]) =>
listener(status);
ipcRenderer.on(ipcChannels.updateStatus, handler);
return () => ipcRenderer.off(ipcChannels.updateStatus, handler);
},
onTrayCreateScratchpad: (listener) => {
const handler = () => listener();
ipcRenderer.on(ipcChannels.trayCreateScratchpad, handler);
return () => ipcRenderer.off(ipcChannels.trayCreateScratchpad, handler);
},
};
contextBridge.exposeInMainWorld('aryxApi', api);
+363 -7
View File
@@ -1,24 +1,33 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { AppShell } from '@renderer/components/AppShell';
import { ActivityPanel } from '@renderer/components/ActivityPanel';
import { ChatPane } from '@renderer/components/ChatPane';
import { CommandPalette } from '@renderer/components/CommandPalette';
import { DiscoveredToolingModal } from '@renderer/components/DiscoveredToolingModal';
import { KeyboardShortcutsPanel } from '@renderer/components/KeyboardShortcutsPanel';
import { NewSessionModal } from '@renderer/components/NewSessionModal';
import { ProjectSettingsPanel } from '@renderer/components/ProjectSettingsPanel';
import { SessionSearchPanel } from '@renderer/components/SessionSearchPanel';
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,11 +107,24 @@ 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);
const [commandPaletteOpen, setCommandPaletteOpen] = useState(false);
const [showShortcuts, setShowShortcuts] = useState(false);
const [showSearch, setShowSearch] = 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(() => {
@@ -128,19 +150,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 +231,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 +270,196 @@ export default function App() {
if (hasPendingDiscoveries) setShowDiscoveryModal(true);
}, [hasPendingDiscoveries]);
// Keep refs for values the keyboard handler reads — avoids re-registering on every render.
const workspaceRef = useRef(workspace);
workspaceRef.current = workspace;
const showSettingsRef = useRef(showSettings);
showSettingsRef.current = showSettings;
const showShortcutsRef = useRef(showShortcuts);
showShortcutsRef.current = showShortcuts;
const commandPaletteOpenRef = useRef(commandPaletteOpen);
commandPaletteOpenRef.current = commandPaletteOpen;
const projectSettingsIdRef = useRef(projectSettingsId);
projectSettingsIdRef.current = projectSettingsId;
const newSessionProjectIdRef = useRef(newSessionProjectId);
newSessionProjectIdRef.current = newSessionProjectId;
// ── Global keyboard shortcuts ──
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
const mod = e.ctrlKey || e.metaKey;
const ws = workspaceRef.current;
// Ignore keyboard shortcuts while typing in inputs (except our global combos)
const target = e.target as HTMLElement;
const isInput = target.tagName === 'INPUT'
|| target.tagName === 'TEXTAREA'
|| target.isContentEditable;
// ── Ctrl+` — Toggle terminal ──
if (e.ctrlKey && e.key === '`') {
e.preventDefault();
setTerminalOpen((prev) => !prev);
return;
}
// ── Ctrl/Cmd+K — Command palette ──
if (mod && e.key === 'k') {
e.preventDefault();
setCommandPaletteOpen((prev) => !prev);
return;
}
// ── Ctrl/Cmd+/ — Keyboard shortcuts cheat sheet ──
if (mod && e.key === '/') {
e.preventDefault();
setShowShortcuts((prev) => !prev);
return;
}
// ── Ctrl/Cmd+Shift+F — Search sessions ──
if (mod && e.shiftKey && e.key === 'F') {
e.preventDefault();
setShowSearch((prev) => !prev);
return;
}
// ── Ctrl/Cmd+, — Open settings ──
if (mod && e.key === ',') {
e.preventDefault();
setShowSettings(true);
return;
}
// ── Escape — Close overlays or cancel running turn ──
if (e.key === 'Escape') {
// Close overlays in priority order (command palette and shortcuts use their own capture listeners)
if (projectSettingsIdRef.current) {
e.preventDefault();
setProjectSettingsId(undefined);
return;
}
if (showSettingsRef.current) {
e.preventDefault();
setShowSettings(false);
return;
}
if (newSessionProjectIdRef.current) {
e.preventDefault();
setNewSessionProjectId(undefined);
return;
}
// If nothing is open, cancel a running turn on the selected session
if (ws) {
const session = ws.sessions.find((s) => s.id === ws.selectedSessionId);
if (session?.status === 'running' && !isInput) {
e.preventDefault();
void api.cancelSessionTurn({ sessionId: session.id });
return;
}
}
return;
}
// Skip remaining shortcuts when focus is in an input field
if (isInput) return;
// ── Ctrl/Cmd+N — New session ──
if (mod && e.key === 'n') {
e.preventDefault();
if (ws) {
const defaultProjectId =
ws.selectedProjectId ??
ws.projects.find((p) => !isScratchpadProject(p))?.id;
if (defaultProjectId) {
setNewSessionProjectId(defaultProjectId);
}
}
return;
}
// ── Ctrl/Cmd+W — Archive / close current session ──
if (mod && e.key === 'w') {
e.preventDefault();
if (ws?.selectedSessionId) {
void api.setSessionArchived({ sessionId: ws.selectedSessionId, isArchived: true });
}
return;
}
// ── Ctrl+Tab / Ctrl+Shift+Tab — Cycle sessions ──
if (e.ctrlKey && e.key === 'Tab') {
e.preventDefault();
if (ws) {
const activeSessions = ws.sessions.filter((s) => !s.isArchived);
if (activeSessions.length > 1) {
const currentIdx = activeSessions.findIndex((s) => s.id === ws.selectedSessionId);
const direction = e.shiftKey ? -1 : 1;
const nextIdx = (currentIdx + direction + activeSessions.length) % activeSessions.length;
void api.selectSession(activeSessions[nextIdx].id);
}
}
return;
}
// ── Ctrl/Cmd+. — Quick approve pending tool call ──
if (mod && e.key === '.') {
e.preventDefault();
if (ws?.selectedSessionId) {
const session = ws.sessions.find((s) => s.id === ws.selectedSessionId);
if (session?.pendingApproval?.status === 'pending') {
void api.resolveSessionApproval({
sessionId: session.id,
approvalId: session.pendingApproval.id,
decision: 'approved',
});
}
}
return;
}
// ── Ctrl/Cmd+L — Focus the composer ──
if (mod && e.key === 'l') {
e.preventDefault();
const editor = document.querySelector<HTMLElement>('.markdown-composer-editable');
editor?.focus();
return;
}
};
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 +485,23 @@ export default function App() {
}
}, [api, workspace]);
// Listen for tray "Quick Scratchpad" action
const scratchpadRef = useRef(handleCreateScratchpad);
scratchpadRef.current = handleCreateScratchpad;
useEffect(() => {
return api.onTrayCreateScratchpad(() => scratchpadRef.current());
}, [api]);
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 (
@@ -320,12 +571,34 @@ export default function App() {
autoApprovedToolNames: settings.autoApprovedToolNames,
});
}}
onBranchFromMessage={(messageId) => {
void api.branchSession({ sessionId: selectedSession.id, messageId });
}}
onPinMessage={(messageId, isPinned) => {
void api.setSessionMessagePinned({ sessionId: selectedSession.id, messageId, isPinned });
}}
onRegenerateMessage={(messageId) => {
void api.regenerateSessionMessage({ sessionId: selectedSession.id, messageId });
}}
onEditAndResendMessage={(messageId, content) => {
void api.editAndResendSessionMessage({ sessionId: selectedSession.id, messageId, content });
}}
branchOriginLabel={
selectedSession.branchOrigin
? workspace.sessions.find((s) => s.id === selectedSession.branchOrigin!.sourceSessionId)?.title
: undefined
}
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 +608,7 @@ export default function App() {
onJumpToMessage={jumpToMessage}
pattern={patternForSession}
session={selectedSession}
sessionRequestUsage={requestUsageForSession}
turnEvents={turnEventsForSession}
/>
);
@@ -342,6 +616,7 @@ export default function App() {
content = (
<WelcomePane
hasProjects={hasUserProjects}
connectionStatus={sidecarCapabilities?.connection.status}
onAddProject={() => void api.addProject()}
onNewScratchpad={() => handleCreateScratchpad()}
onOpenSettings={() => setShowSettings(true)}
@@ -385,6 +660,10 @@ export default function App() {
await api.savePattern({ pattern });
}}
onSetTheme={(theme) => void api.setTheme(theme)}
notificationsEnabled={workspace.settings.notificationsEnabled !== false}
onSetNotificationsEnabled={(enabled) => void api.setNotificationsEnabled(enabled)}
minimizeToTray={workspace.settings.minimizeToTray === true}
onSetMinimizeToTray={(enabled) => void api.setMinimizeToTray(enabled)}
onOpenAppDataFolder={() => void api.openAppDataFolder()}
onResetLocalWorkspace={async () => {
const fresh = await api.resetLocalWorkspace();
@@ -397,15 +676,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 +689,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 +707,7 @@ export default function App() {
setNewSessionProjectId(projectId);
}}
onOpenSettings={() => setShowSettings(true)}
onOpenProjectSettings={(projectId) => setProjectSettingsId(projectId)}
onProjectSelect={(projectId) => {
void api.selectProject(projectId);
}}
@@ -484,6 +769,77 @@ 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);
}}
/>
)}
{commandPaletteOpen && workspace && (
<CommandPalette
workspace={workspace}
onClose={() => setCommandPaletteOpen(false)}
onSelectSession={(sessionId) => {
void api.selectSession(sessionId);
}}
onSelectProject={(projectId) => {
void api.selectProject(projectId);
}}
onNewSession={(projectId) => {
setNewSessionProjectId(projectId);
}}
onCreateScratchpad={handleCreateScratchpad}
onOpenSettings={() => setShowSettings(true)}
onOpenProjectSettings={(projectId) => setProjectSettingsId(projectId)}
onToggleTerminal={handleTerminalToggle}
onSetTheme={(theme) => void api.setTheme(theme)}
onDuplicateSession={(sessionId) => {
void api.duplicateSession({ sessionId });
}}
onPinSession={(sessionId, isPinned) => {
void api.setSessionPinned({ sessionId, isPinned });
}}
onArchiveSession={(sessionId, isArchived) => {
void api.setSessionArchived({ sessionId, isArchived });
}}
onAddProject={() => void api.addProject()}
onOpenAppDataFolder={() => void api.openAppDataFolder()}
onShowShortcuts={() => setShowShortcuts(true)}
onShowSearch={() => setShowSearch(true)}
/>
)}
{showShortcuts && (
<KeyboardShortcutsPanel onClose={() => setShowShortcuts(false)} />
)}
{showSearch && workspace && (
<SessionSearchPanel
workspace={workspace}
onClose={() => setShowSearch(false)}
onSelectSession={(sessionId) => {
void api.selectSession(sessionId);
}}
/>
)}
</>
);
}
+124 -47
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';
@@ -19,12 +24,12 @@ import { ProviderIcon } from './ProviderIcons';
/* ── Mode accent colours ───────────────────────────────────── */
const modeAccent: Record<OrchestrationMode, { dot: string; bar: string; label: string }> = {
single: { dot: 'bg-indigo-400', bar: 'bg-indigo-500/60', label: 'text-indigo-400' },
sequential: { dot: 'bg-amber-400', bar: 'bg-amber-500/60', label: 'text-amber-400' },
concurrent: { dot: 'bg-emerald-400', bar: 'bg-emerald-500/60', label: 'text-emerald-400' },
handoff: { dot: 'bg-sky-400', bar: 'bg-sky-500/60', label: 'text-sky-400' },
'group-chat': { dot: 'bg-violet-400', bar: 'bg-violet-500/60', label: 'text-violet-400' },
magentic: { dot: 'bg-zinc-500', bar: 'bg-zinc-600/60', label: 'text-zinc-500' },
single: { dot: 'bg-[#245CF9]', bar: 'bg-[#245CF9] opacity-60', label: 'text-[#245CF9]' },
sequential: { dot: 'bg-[var(--color-status-warning)]', bar: 'bg-[var(--color-status-warning)] opacity-60', label: 'text-[var(--color-status-warning)]' },
concurrent: { dot: 'bg-[var(--color-status-success)]', bar: 'bg-[var(--color-status-success)] opacity-60', label: 'text-[var(--color-status-success)]' },
handoff: { dot: 'bg-[var(--color-accent-sky)]', bar: 'bg-[var(--color-accent-sky)] opacity-60', label: 'text-[var(--color-accent-sky)]' },
'group-chat': { dot: 'bg-[var(--color-accent-purple)]', bar: 'bg-[var(--color-accent-purple)] opacity-60', label: 'text-[var(--color-accent-purple)]' },
magentic: { dot: 'bg-[var(--color-text-muted)]', bar: 'bg-[var(--color-text-muted)] opacity-60', label: 'text-[var(--color-text-muted)]' },
};
/* ── Helpers ───────────────────────────────────────────────── */
@@ -57,7 +62,7 @@ const modeLabels: Record<OrchestrationMode, string> = {
function SectionHeader({ children }: { children: ReactNode }) {
return (
<h3 className="mb-2 flex items-center gap-2 text-[10px] font-semibold uppercase tracking-wider text-zinc-600">
<h3 className="font-display mb-2 flex items-center gap-2 text-[10px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
{children}
</h3>
);
@@ -70,17 +75,19 @@ 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);
return (
<div className={`relative flex gap-2.5 py-2.5 ${isLast ? '' : 'border-b border-zinc-800/50'}`}>
<div className={`relative flex gap-2.5 py-2.5 ${isLast ? '' : 'border-b border-[var(--color-border-subtle)]'}`}>
{/* Left accent bar — visible only when this agent is actively working */}
{isActive && (
<div className={`absolute -left-3 bottom-2 top-2 w-[3px] rounded-full ${accent.bar}`} />
@@ -89,12 +96,12 @@ function AgentRow({
{/* Status dot */}
<div className="flex shrink-0 pt-0.5">
<span
className={`size-2 rounded-full ${
className={`size-2 rounded-full transition-all duration-200 ${
isActive
? `animate-pulse ${accent.dot}`
? `animate-pulse ${accent.dot} ring-2 ring-[var(--color-border-glow)]`
: isCompleted
? 'bg-emerald-400'
: 'bg-zinc-700'
? 'bg-[var(--color-status-success)]'
: 'bg-[var(--color-surface-3)]'
}`}
/>
</div>
@@ -102,13 +109,13 @@ function AgentRow({
{/* Content */}
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<span className="truncate text-[12px] font-medium text-zinc-200">{row.agentName}</span>
<span className="truncate text-[12px] font-medium text-[var(--color-text-primary)]">{row.agentName}</span>
</div>
{/* Model + effort inline */}
{agent && (
<div className="mt-1 flex flex-wrap items-center gap-1">
<span className="inline-flex items-center gap-1 text-[10px] text-zinc-500">
<span className="inline-flex items-center gap-1 text-[10px] text-[var(--color-text-muted)]">
{(() => {
const prov = inferProvider(agent.model);
return prov ? <ProviderIcon provider={prov} className="size-2.5" /> : null;
@@ -117,8 +124,8 @@ function AgentRow({
</span>
{agent.reasoningEffort && (
<>
<span className="text-[10px] text-zinc-700">·</span>
<span className="inline-flex items-center gap-0.5 text-[10px] text-zinc-500">
<span className="text-[10px] text-[var(--color-text-muted)]">·</span>
<span className="inline-flex items-center gap-0.5 text-[10px] text-[var(--color-text-muted)]">
<Sparkles className="size-2" />
{formatEffort(agent.reasoningEffort)}
</span>
@@ -134,13 +141,34 @@ function AgentRow({
isActive
? accent.label
: isCompleted
? 'text-emerald-400'
: 'text-zinc-600'
? 'text-[var(--color-status-success)]'
: 'text-[var(--color-text-muted)]'
}`}
>
{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-[var(--color-text-muted)]">
<span className="font-mono tabular-nums">{formatTokenCount(agentUsage.inputTokens)} in</span>
<span className="text-[var(--color-text-muted)]">·</span>
<span className="font-mono tabular-nums">{formatTokenCount(agentUsage.outputTokens)} out</span>
{agentUsage.cost > 0 && (
<>
<span className="text-[var(--color-text-muted)]">·</span>
<span className="font-mono tabular-nums">{agentUsage.cost.toFixed(2)} cost</span>
</>
)}
{agentUsage.durationMs > 0 && (
<>
<span className="text-[var(--color-text-muted)]">·</span>
<span className="font-mono tabular-nums">{formatDuration(agentUsage.durationMs)}</span>
</>
)}
</div>
)}
</div>
</div>
);
@@ -154,15 +182,15 @@ function TurnEventIcon({ kind, phase, success }: { kind: SessionEventKind; phase
const base = 'size-3';
switch (kind) {
case 'subagent':
return <ArrowRight className={`${base} ${success === false ? 'text-red-400' : 'text-sky-400'}`} />;
return <ArrowRight className={`${base} ${success === false ? 'text-[var(--color-status-error)]' : 'text-[var(--color-accent-sky)]'}`} />;
case 'hook-lifecycle':
return <Cog className={`${base} ${phase === 'start' ? 'animate-spin text-amber-400' : success === false ? 'text-red-400' : 'text-emerald-400'}`} />;
return <Cog className={`${base} ${phase === 'start' ? 'animate-spin text-[var(--color-status-warning)]' : success === false ? 'text-[var(--color-status-error)]' : 'text-[var(--color-status-success)]'}`} />;
case 'skill-invoked':
return <Sparkles className={`${base} text-violet-400`} />;
return <Sparkles className={`${base} text-[var(--color-accent-purple)]`} />;
case 'session-compaction':
return <CheckCircle2 className={`${base} ${phase === 'start' ? 'animate-pulse text-amber-400' : 'text-emerald-400'}`} />;
return <CheckCircle2 className={`${base} ${phase === 'start' ? 'animate-pulse text-[var(--color-status-warning)]' : 'text-[var(--color-status-success)]'}`} />;
default:
return <Zap className={`${base} text-zinc-500`} />;
return <Zap className={`${base} text-[var(--color-text-muted)]`} />;
}
}
@@ -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(
@@ -208,19 +238,19 @@ export function ActivityPanel({
{/* Header — top padding clears the title bar overlay zone */}
<div className="drag-region border-b border-[var(--color-border)] px-4 pb-3 pt-3">
<div className="flex min-h-8 items-center gap-2">
<Activity className="size-4 text-zinc-500" />
<span className="text-[12px] font-semibold uppercase tracking-[0.12em] text-zinc-400">
<Activity className="size-4 text-[var(--color-text-muted)]" />
<span className="font-display text-[12px] font-semibold uppercase tracking-[0.12em] text-[var(--color-text-secondary)]">
Activity
</span>
{hasPendingApproval ? (
<span className="flex items-center gap-1">
<ShieldAlert className="size-3 text-amber-400" />
<span className="text-[9px] font-semibold uppercase tracking-wider text-amber-400">
<ShieldAlert className="size-3 text-[var(--color-status-warning)]" />
<span className="text-[9px] font-semibold uppercase tracking-wider text-[var(--color-status-warning)]">
Approval{totalApprovalCount > 1 ? `s (${totalApprovalCount})` : ''}
</span>
</span>
) : isBusy ? (
<span className="size-1.5 animate-pulse rounded-full bg-blue-400" />
<span className="size-1.5 animate-pulse rounded-full bg-[var(--color-status-info)]" />
) : null}
</div>
</div>
@@ -231,7 +261,7 @@ export function ActivityPanel({
<SectionHeader>
<Users className="size-3" />
<span>Agents</span>
<span className="rounded-full bg-zinc-800 px-1.5 py-0.5 text-[9px] tabular-nums text-zinc-500">
<span className="font-mono rounded-full bg-[var(--color-surface-2)] px-1.5 py-0.5 text-[9px] tabular-nums text-[var(--color-text-muted)]">
{activityRows.length}
</span>
<span className={`ml-auto text-[9px] font-medium normal-case tracking-normal ${accent.label}`}>
@@ -240,29 +270,76 @@ export function ActivityPanel({
</SectionHeader>
{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}
/>
))}
<div className="glass-surface rounded-lg px-3">
{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>
<p className="py-4 text-center text-[11px] text-[var(--color-text-muted)]">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="glass-surface rounded-lg px-3 py-2.5">
<div className="flex flex-wrap items-center gap-1.5 text-[11px] text-[var(--color-text-secondary)]">
<span className="font-mono font-medium tabular-nums">
{sessionRequestUsage.requestCount} premium request{sessionRequestUsage.requestCount === 1 ? '' : 's'}
</span>
{sessionRequestUsage.totalNanoAiu > 0 && (
<>
<span className="text-[var(--color-text-muted)]">·</span>
<span className="font-mono tabular-nums">{formatNanoAiu(sessionRequestUsage.totalNanoAiu)} AIU</span>
</>
)}
</div>
<div className="mt-1 flex flex-wrap items-center gap-1.5 text-[10px] text-[var(--color-text-muted)]">
<span className="font-mono tabular-nums">{formatTokenCount(sessionRequestUsage.totalInputTokens)} in</span>
<span className="text-[var(--color-text-muted)]">·</span>
<span className="font-mono tabular-nums">{formatTokenCount(sessionRequestUsage.totalOutputTokens)} out</span>
{sessionRequestUsage.totalCost > 0 && (
<>
<span className="text-[var(--color-text-muted)]">·</span>
<span className="font-mono tabular-nums">{sessionRequestUsage.totalCost.toFixed(2)} cost</span>
</>
)}
{sessionRequestUsage.totalDurationMs > 0 && (
<>
<span className="text-[var(--color-text-muted)]">·</span>
<span className="font-mono tabular-nums">{formatDuration(sessionRequestUsage.totalDurationMs)} total</span>
</>
)}
</div>
</div>
</div>
)}
{/* ── Run timeline section ─────────────────────────── */}
<div className="mb-4">
<SectionHeader>
<Clock className="size-3" />
<span>Timeline</span>
{session.runs.length > 0 && (
<span className="rounded-full bg-zinc-800 px-1.5 py-0.5 text-[9px] tabular-nums text-zinc-500">
<span className="font-mono rounded-full bg-[var(--color-surface-2)] px-1.5 py-0.5 text-[9px] tabular-nums text-[var(--color-text-muted)]">
{session.runs.length}
</span>
)}
@@ -277,12 +354,12 @@ export function ActivityPanel({
<SectionHeader>
<Zap className="size-3" />
<span>Events</span>
<span className="rounded-full bg-zinc-800 px-1.5 py-0.5 text-[9px] tabular-nums text-zinc-500">
<span className="font-mono rounded-full bg-[var(--color-surface-2)] px-1.5 py-0.5 text-[9px] tabular-nums text-[var(--color-text-muted)]">
{turnEvents.length}
</span>
</SectionHeader>
<div className="space-y-0.5 rounded-lg border border-zinc-800 bg-zinc-900/40 px-3 py-2">
<div className="glass-surface space-y-0.5 rounded-lg px-3 py-2">
{turnEvents.slice().reverse().map((entry, index) => (
<div key={index} className="flex items-start gap-2 py-1">
<div className="mt-0.5 shrink-0">
@@ -290,13 +367,13 @@ export function ActivityPanel({
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<span className="text-[11px] font-medium text-zinc-300">{entry.label}</span>
<span className="ml-auto shrink-0 text-[9px] tabular-nums text-zinc-700">
<span className="text-[11px] font-medium text-[var(--color-text-secondary)]">{entry.label}</span>
<span className="font-mono ml-auto shrink-0 text-[9px] tabular-nums text-[var(--color-text-muted)]">
{formatTurnEventTimestamp(entry.occurredAt)}
</span>
</div>
{entry.detail && (
<p className="text-[10px] leading-snug text-zinc-600">{entry.detail}</p>
<p className="text-[10px] leading-snug text-[var(--color-text-muted)]">{entry.detail}</p>
)}
</div>
</div>
+19 -19
View File
@@ -18,9 +18,9 @@ function TierBadge({ tier }: { tier: ModelDefinition['tier'] }) {
}
const styles = {
premium: 'bg-amber-500/10 text-amber-400',
standard: 'bg-zinc-700/50 text-zinc-500',
fast: 'bg-emerald-500/10 text-emerald-400',
premium: 'bg-[var(--color-status-warning)]/10 text-[var(--color-status-warning)]',
standard: 'bg-[var(--color-surface-3)]/50 text-[var(--color-text-muted)]',
fast: 'bg-[var(--color-status-success)]/10 text-[var(--color-status-success)]',
};
return (
@@ -75,10 +75,10 @@ export function ModelSelect({
return (
<label className="block space-y-1.5">
<span className="text-[12px] font-medium text-zinc-400">{label}</span>
<span className="text-[12px] font-medium text-[var(--color-text-secondary)]">{label}</span>
<div className="relative" ref={containerRef}>
<button
className="flex w-full items-center gap-2 rounded-lg border border-zinc-700 bg-zinc-900 px-3 py-2 text-left text-[13px] text-zinc-100 outline-none transition hover:border-zinc-600 focus:border-indigo-500/50 disabled:cursor-not-allowed disabled:opacity-60"
className="flex w-full items-center gap-2 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] px-3 py-2 text-left text-[13px] text-[var(--color-text-primary)] outline-none transition-all duration-200 hover:border-[var(--color-border)] focus:border-[var(--color-accent)]/50 disabled:cursor-not-allowed disabled:opacity-60"
disabled={disabled}
onClick={() => setOpen((current) => !current)}
type="button"
@@ -86,25 +86,25 @@ export function ModelSelect({
{provider && <ProviderIcon provider={provider} />}
<span className="flex-1 truncate">{selected?.name ?? (value || 'Select model')}</span>
<ChevronDown
className={`size-3.5 text-zinc-500 transition ${open ? 'rotate-180' : ''}`}
className={`size-3.5 text-[var(--color-text-muted)] transition ${open ? 'rotate-180' : ''}`}
/>
</button>
{open && !disabled && (
<div className="absolute z-30 mt-1 max-h-72 w-full overflow-y-auto rounded-lg border border-zinc-700 bg-zinc-900 py-1 shadow-2xl">
<div className="absolute z-30 mt-1 max-h-72 w-full overflow-y-auto rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] py-1 shadow-[0_16px_64px_rgba(0,0,0,0.5)]">
{groupedModels.map((providerGroup) => {
return (
<div key={providerGroup.id}>
<div className="flex items-center gap-2 px-3 pb-1 pt-2.5">
<ProviderIcon provider={providerGroup.id} />
<span className="text-[10px] font-semibold uppercase tracking-wider text-zinc-500">
<span className="text-[10px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
{providerGroup.label}
</span>
</div>
{providerGroup.models.map((model) => (
<button
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-[13px] transition hover:bg-zinc-800 ${
model.id === value ? 'bg-indigo-500/10 text-indigo-200' : 'text-zinc-300'
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-[13px] transition-all duration-200 hover:bg-[var(--color-surface-3)] ${
model.id === value ? 'bg-[var(--color-accent-muted)] text-[var(--color-text-accent)]' : 'text-[var(--color-text-secondary)]'
}`}
key={model.id}
onClick={() => {
@@ -122,13 +122,13 @@ export function ModelSelect({
})}
{otherModels.length > 0 && (
<div>
<div className="px-3 pb-1 pt-2.5 text-[10px] font-semibold uppercase tracking-wider text-zinc-500">
<div className="px-3 pb-1 pt-2.5 text-[10px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
Other
</div>
{otherModels.map((model) => (
<button
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-[13px] transition hover:bg-zinc-800 ${
model.id === value ? 'bg-indigo-500/10 text-indigo-200' : 'text-zinc-300'
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-[13px] transition-all duration-200 hover:bg-[var(--color-surface-3)] ${
model.id === value ? 'bg-[var(--color-accent-muted)] text-[var(--color-text-accent)]' : 'text-[var(--color-text-secondary)]'
}`}
key={model.id}
onClick={() => {
@@ -173,15 +173,15 @@ export function ReasoningEffortSelect({
if (supportedEfforts && supportedEfforts.length === 0) {
return (
<label className="block space-y-1.5">
<span className="text-[12px] font-medium text-zinc-400">{label}</span>
<span className="text-[12px] font-medium text-[var(--color-text-secondary)]">{label}</span>
<div className="relative">
<input
className="w-full rounded-lg border border-zinc-700 bg-zinc-900 px-3 py-2 pr-9 text-[13px] text-zinc-500 outline-none"
className="w-full rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] px-3 py-2 pr-9 text-[13px] text-[var(--color-text-muted)] outline-none"
disabled
readOnly
value="Not supported for this model"
/>
<Sparkles className="pointer-events-none absolute right-3 top-1/2 size-3.5 -translate-y-1/2 text-zinc-600" />
<Sparkles className="pointer-events-none absolute right-3 top-1/2 size-3.5 -translate-y-1/2 text-[var(--color-text-muted)]" />
</div>
</label>
);
@@ -189,10 +189,10 @@ export function ReasoningEffortSelect({
return (
<label className="block space-y-1.5">
<span className="text-[12px] font-medium text-zinc-400">{label}</span>
<span className="text-[12px] font-medium text-[var(--color-text-secondary)]">{label}</span>
<div className="relative">
<select
className="w-full rounded-lg border border-zinc-700 bg-zinc-900 px-3 py-2 pr-9 text-[13px] text-zinc-100 outline-none transition focus:border-indigo-500/50 disabled:cursor-not-allowed disabled:opacity-60"
className="w-full rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] px-3 py-2 pr-9 text-[13px] text-[var(--color-text-primary)] outline-none transition focus:border-[var(--color-accent)]/50 disabled:cursor-not-allowed disabled:opacity-60"
disabled={disabled || !selectedValue}
onChange={(event) => onChange(event.target.value as ReasoningEffort)}
value={selectedValue}
@@ -203,7 +203,7 @@ export function ReasoningEffortSelect({
</option>
))}
</select>
<Sparkles className="pointer-events-none absolute right-3 top-1/2 size-3.5 -translate-y-1/2 text-zinc-500" />
<Sparkles className="pointer-events-none absolute right-3 top-1/2 size-3.5 -translate-y-1/2 text-[var(--color-text-muted)]" />
</div>
</label>
);
+20 -5
View File
@@ -4,24 +4,39 @@ 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">
<div className="relative flex h-screen bg-[var(--color-surface-0)] text-[var(--color-text-primary)]">
{/* Full-width drag region matching the title bar overlay height */}
<div className="drag-region absolute inset-x-0 top-0 z-10 h-3" />
<aside className="flex w-72 shrink-0 flex-col border-r border-[var(--color-border)] bg-[var(--color-surface-1)]">
{/* Sidebar */}
<aside className="flex w-72 shrink-0 flex-col border-r border-[var(--color-border-subtle)] bg-[var(--color-surface-1)]">
{sidebar}
</aside>
<main className="relative min-w-0 flex-1">{content}</main>
{/* Main content + terminal */}
<main className="relative flex min-w-0 flex-1 flex-col">
{/* Ambient glow behind active content area */}
<div
className="pointer-events-none absolute inset-0 opacity-30"
style={{ background: 'var(--gradient-glow)' }}
/>
<div className="relative min-h-0 flex-1">{content}</div>
{terminalPanel}
</main>
{/* Detail panel */}
{detailPanel && (
<aside className="flex w-64 shrink-0 flex-col border-l border-[var(--color-border)] bg-[var(--color-surface-1)]">
<aside className="flex w-64 shrink-0 flex-col border-l border-[var(--color-border-subtle)] bg-[var(--color-surface-1)]">
{detailPanel}
</aside>
)}
{overlay}
</div>
);
+261 -106
View File
@@ -1,20 +1,25 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { AlertCircle, ArrowUp, Bot, Circle, ClipboardList, GitBranch, Loader2, MessageCircleQuestion, Paperclip, ShieldAlert, Square, User, X } from 'lucide-react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { AlertCircle, ArrowUp, Bookmark, Bot, Circle, ClipboardList, GitBranch, Loader2, MessageCircleQuestion, Paperclip, RefreshCw, ShieldAlert, Square, User, X } from 'lucide-react';
import { MarkdownContent } from '@renderer/components/MarkdownContent';
import { MarkdownComposer, type MarkdownComposerHandle } from '@renderer/components/MarkdownComposer';
import { ApprovalBanner, QueuedApprovalsList } from '@renderer/components/chat/ApprovalBanner';
import { MessageActions } from '@renderer/components/chat/MessageActions';
import { MessageEditComposer } from '@renderer/components/chat/MessageEditComposer';
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,
@@ -23,8 +28,9 @@ import {
} from '@shared/domain/models';
import { type PatternDefinition, type ReasoningEffort } from '@shared/domain/pattern';
import { isScratchpadProject, type ProjectRecord } from '@shared/domain/project';
import { resolveSessionToolingSelection, type SessionRecord } from '@shared/domain/session';
import { resolveSessionToolingSelection, type SessionBranchOriginAction, type SessionRecord } from '@shared/domain/session';
import {
groupApprovalToolsByProvider,
listApprovalToolDefinitions,
type RuntimeToolDefinition,
type SessionToolingSelection,
@@ -39,8 +45,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,12 +59,18 @@ interface ChatPaneProps {
onDismissPlanReview?: () => void;
onDismissMcpAuth?: () => void;
onAuthenticateMcp?: () => void;
onTerminalToggle?: () => void;
onUpdateSessionModelConfig?: (config: {
model: string;
reasoningEffort?: ReasoningEffort;
}) => Promise<unknown>;
onUpdateSessionTooling?: (selection: SessionToolingSelection) => void;
onUpdateSessionApprovalSettings?: (settings: { autoApprovedToolNames?: string[] }) => void;
onBranchFromMessage?: (messageId: string) => void;
onPinMessage?: (messageId: string, isPinned: boolean) => void;
onRegenerateMessage?: (messageId: string) => void;
onEditAndResendMessage?: (messageId: string, content: string) => void;
branchOriginLabel?: string;
}
export function ChatPane({
@@ -63,8 +79,12 @@ export function ChatPane({
session,
availableModels,
toolingSettings,
mcpProbingServerIds,
runtimeTools,
sessionUsage,
activeSubagents,
terminalOpen,
terminalRunning,
onSend,
onCancelTurn,
onResolveApproval,
@@ -73,9 +93,15 @@ export function ChatPane({
onDismissPlanReview,
onDismissMcpAuth,
onAuthenticateMcp,
onTerminalToggle,
onUpdateSessionModelConfig,
onUpdateSessionTooling,
onUpdateSessionApprovalSettings,
onBranchFromMessage,
onPinMessage,
onRegenerateMessage,
onEditAndResendMessage,
branchOriginLabel,
}: ChatPaneProps) {
const [hasComposerContent, setHasComposerContent] = useState(false);
const [configError, setConfigError] = useState<string>();
@@ -83,10 +109,17 @@ export function ChatPane({
const [isResolvingApproval, setIsResolvingApproval] = useState(false);
const [isSubmittingUserInput, setIsSubmittingUserInput] = useState(false);
const [isUpdatingSessionModelConfig, setIsUpdatingSessionModelConfig] = useState(false);
const [editingMessageId, setEditingMessageId] = useState<string>();
const transcriptRef = useRef<HTMLDivElement>(null);
const composerRef = useRef<MarkdownComposerHandle>(null);
const isSessionBusy = session.status === 'running';
const lastAssistantIndex = useMemo(() => {
for (let i = session.messages.length - 1; i >= 0; i--) {
if (session.messages[i].role === 'assistant') return i;
}
return -1;
}, [session.messages]);
const pendingApproval = session.pendingApproval?.status === 'pending' ? session.pendingApproval : undefined;
const queuedApprovals = (session.pendingApprovalQueue ?? []).filter((a) => a.status === 'pending');
const totalPendingCount = (pendingApproval ? 1 : 0) + queuedApprovals.length;
@@ -107,6 +140,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 +160,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({
@@ -143,6 +189,7 @@ export function ChatPane({
setApprovalError(undefined);
setIsResolvingApproval(false);
setIsUpdatingSessionModelConfig(false);
setEditingMessageId(undefined);
}, [session.id]);
function handleComposerSubmit(content: string) {
@@ -152,6 +199,18 @@ export function ChatPane({
void onSend(content, attachments, messageMode);
}
const handleCopyMessage = useCallback((content: string) => {
void navigator.clipboard.writeText(content);
}, []);
const handleEditSave = useCallback(
(messageId: string, content: string) => {
setEditingMessageId(undefined);
onEditAndResendMessage?.(messageId, content);
},
[onEditAndResendMessage],
);
function handleDismissPlan() {
onDismissPlanReview?.();
}
@@ -223,16 +282,16 @@ export function ChatPane({
return (
<div className="flex h-full flex-col">
{/* Header — extra top padding clears the title bar overlay zone */}
<header className="drag-region border-b border-[var(--color-border)] px-6 pb-3 pt-3">
<header className="drag-region border-b border-[var(--color-border-subtle)] px-6 pb-3 pt-3">
<div className="flex min-h-8 items-center justify-between">
<div className="min-w-0">
<h2 className="truncate text-[13px] font-semibold leading-tight text-zinc-100">{session.title}</h2>
<p className="truncate text-[11px] leading-tight text-zinc-500">
<h2 className="font-display truncate text-[13px] font-semibold leading-tight text-[var(--color-text-primary)]">{session.title}</h2>
<p className="truncate text-[11px] leading-tight text-[var(--color-text-muted)]">
{isScratchpad
? `Scratchpad · ${pattern.name}`
: `${project.name} · ${pattern.name} · ${pattern.mode}`}
{!isScratchpad && project.git?.status === 'ready' && (
<span className="ml-2 inline-flex items-center gap-1 text-zinc-600">
<span className="ml-2 inline-flex items-center gap-1 text-[var(--color-text-muted)]">
<GitBranch className="inline size-2.5" />
{project.git.branch ?? project.git.head?.shortHash ?? 'HEAD'}
{project.git.isDirty && (
@@ -246,31 +305,31 @@ export function ChatPane({
</div>
<div className="flex items-center gap-2">
{pendingApproval && (
<div className="flex items-center gap-1.5 text-[12px] font-medium text-amber-400">
<div className="flex items-center gap-1.5 text-[12px] font-medium text-[var(--color-status-warning)]">
<ShieldAlert className="size-3.5" />
Awaiting approval
{queuedApprovals.length > 0 && (
<span className="rounded-full bg-amber-500/15 px-1.5 py-0.5 text-[10px] tabular-nums">
<span className="rounded-full bg-[var(--color-status-warning)]/15 px-1.5 py-0.5 text-[10px] tabular-nums">
+{queuedApprovals.length} queued
</span>
)}
</div>
)}
{pendingUserInput && !pendingApproval && (
<div className="flex items-center gap-1.5 text-[12px] font-medium text-blue-400">
<div className="flex items-center gap-1.5 text-[12px] font-medium text-[var(--color-accent-sky)]">
<MessageCircleQuestion className="size-3.5" />
Awaiting your input
</div>
)}
{isSessionBusy && !pendingApproval && !pendingUserInput && <span className="size-2 animate-pulse rounded-full bg-blue-400" />}
{isSessionBusy && !pendingApproval && !pendingUserInput && <span className="size-2 animate-pulse rounded-full bg-[var(--color-accent-sky)]" />}
{session.status === 'error' && (
<div className="flex items-center gap-1.5 text-[12px] text-red-400">
<div className="flex items-center gap-1.5 text-[12px] text-[var(--color-status-error)]">
<AlertCircle className="size-3.5" />
Error
</div>
)}
{session.status === 'idle' && !pendingApproval && !pendingUserInput && session.messages.length > 0 && (
<span className="text-[12px] text-zinc-600">
<span className="text-[12px] text-[var(--color-text-muted)]">
{session.messages.length} message{session.messages.length === 1 ? '' : 's'}
</span>
)}
@@ -282,54 +341,67 @@ export function ChatPane({
<div className="flex-1 overflow-y-auto" ref={transcriptRef}>
{session.messages.length === 0 ? (
<div className="flex h-full flex-col items-center justify-center gap-2 px-6 text-center">
<Bot className="size-10 text-zinc-800" />
<p className="text-[13px] text-zinc-500">Send a message to start the conversation</p>
<p className="text-[12px] text-zinc-700">
<Bot className="size-10 text-[var(--color-surface-3)]" />
<p className="text-[13px] text-[var(--color-text-muted)]">Send a message to start the conversation</p>
<p className="text-[12px] text-[var(--color-text-muted)]">
{isScratchpad ? (
<>
Scratchpad is ready for ad-hoc questions using{' '}
<span className="text-zinc-500">{pattern.name}</span>
<span className="text-[var(--color-text-secondary)]">{pattern.name}</span>
</>
) : (
<>
Using <span className="text-zinc-500">{pattern.name}</span> in{' '}
<span className="text-zinc-500">{project.name}</span>
Using <span className="text-[var(--color-text-secondary)]">{pattern.name}</span> in{' '}
<span className="text-[var(--color-text-secondary)]">{project.name}</span>
</>
)}
</p>
</div>
) : (
<div className="mx-auto max-w-3xl px-6 py-4">
{/* Branch origin banner */}
{session.branchOrigin && (
<BranchOriginBanner
action={session.branchOrigin.action}
label={branchOriginLabel}
/>
)}
<div className="space-y-1">
{session.messages.map((message, index) => {
const isUser = message.role === 'user';
const isEditing = editingMessageId === message.id;
const isLastAssistant = index === lastAssistantIndex;
const phase = getAssistantMessagePhase(session, message, index);
const assistantContainerClass =
phase === 'thinking'
? 'border-sky-500/20 bg-sky-500/5'
? 'border-[var(--color-accent-sky)]/20 bg-[var(--color-accent-sky)]/5'
: phase === 'final'
? 'border-emerald-500/20 bg-emerald-500/5'
: 'border-zinc-800 bg-zinc-900/40';
? 'border-[var(--color-status-success)]/20 bg-[var(--color-status-success)]/5'
: 'border-[var(--color-border)] bg-[var(--color-surface-1)]/40';
const assistantBadgeClass =
phase === 'thinking'
? 'border-sky-400/20 bg-sky-400/10 text-sky-300'
: 'border-emerald-400/20 bg-emerald-400/10 text-emerald-300';
? 'border-[var(--color-accent-sky)]/20 bg-[var(--color-accent-sky)]/10 text-[var(--color-accent-sky)]'
: 'border-[var(--color-status-success)]/20 bg-[var(--color-status-success)]/10 text-[var(--color-status-success)]';
const phaseLabel =
phase === 'thinking' ? 'Thinking' : phase === 'final' ? 'Final' : undefined;
const showActions = !isSessionBusy && !message.pending;
return (
<div className="group py-3" data-message-id={message.id} key={message.id}>
<div className="message-enter group py-3" data-message-id={message.id} key={message.id}>
<div className="flex gap-3">
<div
className={`mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-full ${
isUser ? 'bg-indigo-600 text-white' : 'bg-zinc-800 text-zinc-400'
isUser ? 'brand-gradient-bg text-white' : 'bg-[var(--color-surface-2)] text-[var(--color-text-secondary)]'
}`}
>
{isUser ? <User className="size-3.5" /> : <Bot className="size-3.5" />}
</div>
<div className="min-w-0 flex-1">
<div className="mb-1 flex items-center gap-2 text-[12px] font-medium text-zinc-400">
<div className="mb-1 flex items-center gap-2 text-[12px] font-medium text-[var(--color-text-secondary)]">
<span>{message.authorName}</span>
{message.isPinned && (
<Bookmark className="size-3 fill-[var(--color-accent-sky)] text-[var(--color-accent-sky)]" />
)}
{!isUser && phaseLabel && (
<span
className={`inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.08em] ${assistantBadgeClass}`}
@@ -337,48 +409,71 @@ export function ChatPane({
{phaseLabel}
</span>
)}
</div>
<div
className={
isUser
? 'text-[14px] leading-relaxed text-zinc-200'
: `rounded-xl border px-4 py-3 text-[14px] leading-relaxed text-zinc-200 ${assistantContainerClass}`
}
>
{/* Attachment thumbnails */}
{isUser && message.attachments && message.attachments.length > 0 && (
<div className="mb-2 flex flex-wrap gap-2">
{message.attachments.map((att, attIdx) =>
isImageAttachment(att) ? (
<img
key={attIdx}
alt={getAttachmentDisplayName(att)}
className="max-h-48 max-w-xs rounded-lg border border-zinc-700 object-cover"
src={`data:${att.mimeType};base64,${att.data}`}
/>
) : (
<div
key={attIdx}
className="flex items-center gap-1.5 rounded-lg border border-zinc-700 bg-zinc-800 px-2 py-1 text-[11px] text-zinc-400"
>
<Paperclip className="size-3" />
{getAttachmentDisplayName(att)}
</div>
),
)}
{showActions && (
<div className="ml-auto">
<MessageActions
message={message}
isLastAssistant={isLastAssistant}
onCopy={() => handleCopyMessage(message.content)}
onPin={() => onPinMessage?.(message.id, !message.isPinned)}
onBranch={() => onBranchFromMessage?.(message.id)}
onRegenerate={onRegenerateMessage ? () => onRegenerateMessage(message.id) : undefined}
onEdit={onEditAndResendMessage && isUser ? () => setEditingMessageId(message.id) : undefined}
/>
</div>
)}
{!isUser && message.pending ? (
<div className="whitespace-pre-wrap break-words text-[14px] leading-relaxed text-zinc-200">
{message.content}
</div>
) : (
<MarkdownContent content={message.content} />
)}
{message.pending && message.content && (
<span className="mt-1 inline-block h-4 w-[2px] animate-pulse rounded-sm bg-zinc-400" />
)}
</div>
{/* Edit mode */}
{isEditing ? (
<MessageEditComposer
initialContent={message.content}
onSave={(content) => handleEditSave(message.id, content)}
onCancel={() => setEditingMessageId(undefined)}
/>
) : (
<div
className={
isUser
? 'text-[14px] leading-relaxed text-[var(--color-text-primary)]'
: `rounded-xl border px-4 py-3 text-[14px] leading-relaxed text-[var(--color-text-primary)] ${assistantContainerClass}`
}
>
{/* Attachment thumbnails */}
{isUser && message.attachments && message.attachments.length > 0 && (
<div className="mb-2 flex flex-wrap gap-2">
{message.attachments.map((att, attIdx) =>
isImageAttachment(att) ? (
<img
key={attIdx}
alt={getAttachmentDisplayName(att)}
className="max-h-48 max-w-xs rounded-lg border border-[var(--color-border)] object-cover"
src={`data:${att.mimeType};base64,${att.data}`}
/>
) : (
<div
key={attIdx}
className="flex items-center gap-1.5 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-2)] px-2 py-1 text-[11px] text-[var(--color-text-secondary)]"
>
<Paperclip className="size-3" />
{getAttachmentDisplayName(att)}
</div>
),
)}
</div>
)}
{!isUser && message.pending ? (
<div className="whitespace-pre-wrap break-words text-[14px] leading-relaxed text-[var(--color-text-primary)]">
{message.content}
</div>
) : (
<MarkdownContent content={message.content} />
)}
{message.pending && message.content && (
<span className="mt-1 inline-block h-4 w-[2px] animate-pulse rounded-sm bg-[var(--color-accent)]" />
)}
</div>
)}
{message.pending && !message.content && <ThinkingDots />}
</div>
</div>
@@ -386,29 +481,34 @@ export function ChatPane({
);
})}
</div>
{activeSubagents && activeSubagents.length > 0 && (
<div className="px-6 py-1">
<SubagentActivityList subagents={activeSubagents} />
</div>
)}
</div>
)}
</div>
{/* Input area */}
<div className="border-t border-[var(--color-border)] px-6 py-4">
<div className="border-t border-[var(--color-border-subtle)] px-6 py-4">
{session.lastError && (
<div className="mb-3 flex items-start gap-2 rounded-lg bg-red-500/10 px-3 py-2 text-[13px] text-red-300">
<AlertCircle className="mt-0.5 size-4 shrink-0 text-red-400" />
<div className="mb-3 flex items-start gap-2 rounded-lg bg-[var(--color-status-error)]/10 px-3 py-2 text-[13px] text-[var(--color-status-error)]">
<AlertCircle className="mt-0.5 size-4 shrink-0 text-[var(--color-status-error)]" />
<span>{session.lastError}</span>
</div>
)}
{configError && (
<div className="mb-3 flex items-start gap-2 rounded-lg bg-red-500/10 px-3 py-2 text-[13px] text-red-300">
<AlertCircle className="mt-0.5 size-4 shrink-0 text-red-400" />
<div className="mb-3 flex items-start gap-2 rounded-lg bg-[var(--color-status-error)]/10 px-3 py-2 text-[13px] text-[var(--color-status-error)]">
<AlertCircle className="mt-0.5 size-4 shrink-0 text-[var(--color-status-error)]" />
<span>{configError}</span>
</div>
)}
{approvalError && (
<div className="mb-3 flex items-start gap-2 rounded-lg bg-red-500/10 px-3 py-2 text-[13px] text-red-300">
<AlertCircle className="mt-0.5 size-4 shrink-0 text-red-400" />
<div className="mb-3 flex items-start gap-2 rounded-lg bg-[var(--color-status-error)]/10 px-3 py-2 text-[13px] text-[var(--color-status-error)]">
<AlertCircle className="mt-0.5 size-4 shrink-0 text-[var(--color-status-error)]" />
<span>{approvalError}</span>
</div>
)}
@@ -416,7 +516,7 @@ export function ChatPane({
<div className="mx-auto max-w-3xl">
{/* Pending approval banner */}
{pendingApproval && (
<div className="mb-3 space-y-2">
<div className="banner-slide-enter mb-3 space-y-2">
<ApprovalBanner
approval={pendingApproval}
isResolving={isResolvingApproval}
@@ -474,14 +574,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 && (
@@ -510,7 +612,7 @@ export function ChatPane({
value={sessionReasoningEffort}
/>
{isUpdatingSessionModelConfig && (
<Loader2 className="size-3 animate-spin text-zinc-500" />
<Loader2 className="size-3 animate-spin text-[var(--color-text-muted)]" />
)}
</div>
)}
@@ -529,14 +631,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>
@@ -548,13 +652,13 @@ export function ChatPane({
{pendingAttachments.map((attachment, index) => (
<div
key={index}
className="flex items-center gap-1.5 rounded-lg border border-zinc-700 bg-zinc-800 px-2.5 py-1.5 text-[11px] text-zinc-300"
className="flex items-center gap-1.5 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-2)] px-2.5 py-1.5 text-[11px] text-[var(--color-text-secondary)]"
>
<Paperclip className="size-3 text-zinc-500" />
<Paperclip className="size-3 text-[var(--color-text-muted)]" />
<span className="max-w-[160px] truncate">{getAttachmentDisplayName(attachment)}</span>
<button
aria-label="Remove attachment"
className="ml-1 rounded p-0.5 text-zinc-500 hover:bg-zinc-700 hover:text-zinc-300"
className="ml-1 rounded p-0.5 text-[var(--color-text-muted)] hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]"
onClick={() => setPendingAttachments((prev) => prev.filter((_, i) => i !== index))}
type="button"
>
@@ -565,7 +669,7 @@ export function ChatPane({
</div>
)}
<div className="rounded-xl border border-zinc-700 bg-zinc-900 transition-colors focus-within:border-indigo-500/50">
<div className="rounded-2xl border border-[var(--color-border)] bg-[var(--color-surface-1)] transition-all duration-200 focus-within:border-[var(--color-border-glow)] focus-within:shadow-[0_0_16px_rgba(36,92,249,0.06)]">
<MarkdownComposer
ref={composerRef}
disabled={isComposerDisabled}
@@ -589,11 +693,33 @@ 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"
className="flex size-8 items-center justify-center rounded-lg text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300"
className="flex size-8 items-center justify-center rounded-lg text-[var(--color-text-muted)] transition-all duration-150 hover:bg-[var(--color-surface-2)] hover:text-[var(--color-text-primary)]"
disabled={isComposerDisabled}
onClick={() => {
const input = document.createElement('input');
@@ -627,10 +753,10 @@ export function ChatPane({
<button
aria-label={isPlanMode ? 'Switch to interactive mode' : 'Switch to plan mode'}
aria-pressed={isPlanMode}
className={`flex size-8 items-center justify-center rounded-lg transition ${
className={`flex size-8 items-center justify-center rounded-lg transition-all duration-150 ${
isPlanMode
? 'bg-emerald-600/20 text-emerald-400 hover:bg-emerald-600/30'
: 'text-zinc-500 hover:bg-zinc-800 hover:text-zinc-300'
? 'bg-[var(--color-status-success)]/20 text-[var(--color-status-success)] hover:bg-[var(--color-status-success)]/30'
: 'text-[var(--color-text-muted)] hover:bg-[var(--color-surface-2)] hover:text-[var(--color-text-primary)]'
}`}
disabled={isComposerDisabled}
onClick={() => onSetInteractionMode(isPlanMode ? 'interactive' : 'plan')}
@@ -642,16 +768,16 @@ export function ChatPane({
{/* Send / Stop / Steer button */}
<button
className={`flex size-8 items-center justify-center rounded-lg transition ${
className={`flex size-8 items-center justify-center rounded-lg transition-all duration-150 ${
isSessionBusy && !hasComposerContent && pendingAttachments.length === 0
? 'bg-red-600/80 text-white hover:bg-red-500'
? 'bg-[var(--color-status-error)]/80 text-white hover:bg-[var(--color-status-error)]'
: canSubmitInput || pendingAttachments.length > 0
? isSessionBusy
? 'bg-amber-600 text-white hover:bg-amber-500'
? 'bg-[var(--color-status-warning)] text-white hover:brightness-110'
: isPlanMode
? 'bg-emerald-600 text-white hover:bg-emerald-500'
: 'bg-indigo-600 text-white hover:bg-indigo-500'
: 'bg-zinc-800 text-zinc-600'
? 'bg-[var(--color-status-success)] text-white hover:brightness-110'
: 'brand-gradient-bg text-white shadow-[0_2px_12px_rgba(36,92,249,0.25)] hover:shadow-[0_4px_20px_rgba(36,92,249,0.35)]'
: 'bg-[var(--color-surface-2)] text-[var(--color-text-muted)]'
}`}
disabled={!canSubmitInput && !isSessionBusy && pendingAttachments.length === 0}
onClick={() => {
@@ -678,20 +804,21 @@ export function ChatPane({
<ArrowUp className="size-4" />
)}
</button>
</div>
</div>
</MarkdownComposer>
{isPlanMode && !isSessionBusy && (
<div className="flex items-center gap-1.5 px-3 pb-1.5 pt-0.5">
<div className="size-1.5 rounded-full bg-emerald-500" />
<span className="text-[10px] font-medium text-emerald-400/80">
<div className="size-1.5 rounded-full bg-[var(--color-status-success)]" />
<span className="text-[10px] font-medium text-[var(--color-status-success)]/80">
Plan mode the agent will propose a plan instead of implementing
</span>
</div>
)}
{isSessionBusy && (hasComposerContent || pendingAttachments.length > 0) && (
<div className="flex items-center gap-1.5 px-3 pb-1.5 pt-0.5">
<div className="size-1.5 rounded-full bg-amber-500" />
<span className="text-[10px] font-medium text-amber-400/80">
<div className="size-1.5 rounded-full bg-[var(--color-status-warning)]" />
<span className="text-[10px] font-medium text-[var(--color-status-warning)]/80">
Steering your message will be injected into the current turn
</span>
</div>
@@ -701,15 +828,15 @@ export function ChatPane({
{/* Session usage bar */}
{sessionUsage && sessionUsage.tokenLimit > 0 && (
<div className="px-1 pt-1.5">
<div className="flex items-center gap-2 text-[10px] text-zinc-500">
<div className="h-1 flex-1 overflow-hidden rounded-full bg-zinc-800">
<div className="flex items-center gap-2 text-[10px] text-[var(--color-text-muted)]">
<div className="h-1 flex-1 overflow-hidden rounded-full bg-[var(--color-surface-2)]">
<div
className={`h-full rounded-full transition-all ${
sessionUsage.currentTokens / sessionUsage.tokenLimit > 0.9
? 'bg-red-500'
? 'bg-[var(--color-status-error)]'
: sessionUsage.currentTokens / sessionUsage.tokenLimit > 0.7
? 'bg-amber-500'
: 'bg-indigo-500/60'
? 'bg-[var(--color-status-warning)]'
: 'bg-[var(--color-accent)]/60'
}`}
style={{ width: `${Math.min(100, (sessionUsage.currentTokens / sessionUsage.tokenLimit) * 100)}%` }}
/>
@@ -725,3 +852,31 @@ export function ChatPane({
</div>
);
}
/* ── Branch origin banner ───────────────────────────────────── */
function BranchOriginBanner({ action, label }: { action?: SessionBranchOriginAction; label?: string }) {
const icon =
action === 'regenerate'
? <RefreshCw className="size-3.5 shrink-0 text-[var(--color-accent-sky)]" />
: <GitBranch className="size-3.5 shrink-0 text-[var(--color-accent)]" />;
const verb =
action === 'regenerate'
? 'Regenerated from'
: action === 'edit-and-resend'
? 'Edited & resent from'
: 'Branched from';
return (
<div className="mb-4 flex items-center gap-2.5 rounded-lg border border-[var(--color-border-subtle)] bg-[var(--color-surface-1)]/60 px-3.5 py-2.5 text-[12px] text-[var(--color-text-secondary)]">
{icon}
<span>
{verb}{' '}
<span className="font-medium text-[var(--color-text-primary)]">
{label ?? 'a previous session'}
</span>
</span>
</div>
);
}
+497
View File
@@ -0,0 +1,497 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
Archive,
Copy,
FolderOpen,
FolderPlus,
Keyboard,
MessageSquare,
Monitor,
Moon,
Pin,
PinOff,
Plus,
Search,
Settings,
Sparkles,
Sun,
Terminal,
} from 'lucide-react';
import type { AppearanceTheme } from '@shared/domain/tooling';
import { isScratchpadProject } from '@shared/domain/project';
import type { WorkspaceState } from '@shared/domain/workspace';
import { shortcutKeys } from '@renderer/lib/keyboardShortcuts';
interface PaletteCommand {
id: string;
label: string;
category: string;
keywords?: string;
shortcut?: string;
icon: React.ReactNode;
action: () => void;
}
export interface CommandPaletteProps {
workspace: WorkspaceState;
onClose: () => void;
onSelectSession: (sessionId: string) => void;
onSelectProject: (projectId: string) => void;
onNewSession: (projectId: string) => void;
onCreateScratchpad: () => void;
onOpenSettings: () => void;
onOpenProjectSettings: (projectId: string) => void;
onToggleTerminal: () => void;
onSetTheme: (theme: AppearanceTheme) => void;
onDuplicateSession: (sessionId: string) => void;
onPinSession: (sessionId: string, isPinned: boolean) => void;
onArchiveSession: (sessionId: string, isArchived: boolean) => void;
onAddProject: () => void;
onOpenAppDataFolder: () => void;
onShowShortcuts: () => void;
onShowSearch: () => void;
}
/** Score how well `query` matches `text` (and optional `keywords`). 0 = no match. */
function matchScore(query: string, text: string, keywords?: string): number {
if (!query) return 1;
const q = query.toLowerCase();
const t = text.toLowerCase();
if (t.startsWith(q)) return 4;
if (t.split(/\s+/).some((w) => w.startsWith(q))) return 3;
if (t.includes(q)) return 2;
if (keywords?.toLowerCase().includes(q)) return 1.5;
const tokens = q.split(/\s+/).filter(Boolean);
if (tokens.length > 1) {
const combined = `${t} ${keywords?.toLowerCase() ?? ''}`;
if (tokens.every((tok) => combined.includes(tok))) return 1;
}
return 0;
}
const ICON = 'size-4';
export function CommandPalette({
workspace,
onClose,
onSelectSession,
onSelectProject,
onNewSession,
onCreateScratchpad,
onOpenSettings,
onOpenProjectSettings,
onToggleTerminal,
onSetTheme,
onDuplicateSession,
onPinSession,
onArchiveSession,
onAddProject,
onOpenAppDataFolder,
onShowShortcuts,
onShowSearch,
}: CommandPaletteProps) {
const [query, setQuery] = useState('');
const [selectedIndex, setSelectedIndex] = useState(0);
const inputRef = useRef<HTMLInputElement>(null);
const listRef = useRef<HTMLDivElement>(null);
useEffect(() => {
inputRef.current?.focus();
}, []);
// Intercept Escape in capture phase so it doesn't leak to other overlays
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
e.preventDefault();
e.stopImmediatePropagation();
onClose();
}
};
document.addEventListener('keydown', handleEscape, true);
return () => document.removeEventListener('keydown', handleEscape, true);
}, [onClose]);
const selectedSession = useMemo(() => {
const id = workspace.selectedSessionId;
return id ? workspace.sessions.find((s) => s.id === id) : undefined;
}, [workspace.sessions, workspace.selectedSessionId]);
const selectedProject = useMemo(() => {
const id = workspace.selectedProjectId;
return id ? workspace.projects.find((p) => p.id === id) : undefined;
}, [workspace.projects, workspace.selectedProjectId]);
const commands = useMemo<PaletteCommand[]>(() => {
const cmds: PaletteCommand[] = [];
// ── Sessions ──
const sessions = workspace.sessions
.filter((s) => !s.isArchived)
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
for (const s of sessions) {
const project = workspace.projects.find((p) => p.id === s.projectId);
const isCurrent = s.id === workspace.selectedSessionId;
cmds.push({
id: `session-${s.id}`,
label: `${s.title}${isCurrent ? ' (current)' : ''}`,
category: 'Sessions',
keywords: `switch ${project?.name ?? ''} ${s.status}`,
icon: <MessageSquare className={ICON} />,
action: () => onSelectSession(s.id),
});
}
// ── Actions ──
const defaultProjectId =
workspace.selectedProjectId ??
workspace.projects.find((p) => !isScratchpadProject(p))?.id;
if (defaultProjectId) {
cmds.push({
id: 'new-session',
label: 'New Session',
category: 'Actions',
keywords: 'create start',
shortcut: shortcutKeys('new-session'),
icon: <Plus className={ICON} />,
action: () => onNewSession(defaultProjectId),
});
}
cmds.push({
id: 'new-scratchpad',
label: 'Quick Scratchpad',
category: 'Actions',
keywords: 'create new scratch quick note',
icon: <Sparkles className={ICON} />,
action: onCreateScratchpad,
});
// ── Current session ──
if (selectedSession) {
cmds.push({
id: 'duplicate-session',
label: 'Duplicate Session',
category: 'Session',
keywords: 'copy clone',
icon: <Copy className={ICON} />,
action: () => onDuplicateSession(selectedSession.id),
});
cmds.push({
id: 'pin-session',
label: selectedSession.isPinned ? 'Unpin Session' : 'Pin Session',
category: 'Session',
keywords: 'pin unpin sticky',
icon: selectedSession.isPinned ? <PinOff className={ICON} /> : <Pin className={ICON} />,
action: () => onPinSession(selectedSession.id, !selectedSession.isPinned),
});
cmds.push({
id: 'archive-session',
label: 'Archive Session',
category: 'Session',
keywords: 'archive hide remove close',
shortcut: shortcutKeys('close-session'),
icon: <Archive className={ICON} />,
action: () => onArchiveSession(selectedSession.id, true),
});
}
// ── Projects ──
const userProjects = workspace.projects.filter((p) => !isScratchpadProject(p));
for (const p of userProjects) {
const isCurrent = p.id === workspace.selectedProjectId;
cmds.push({
id: `project-${p.id}`,
label: `${p.name}${isCurrent ? ' (current)' : ''}`,
category: 'Projects',
keywords: `switch folder ${p.path}`,
icon: <FolderOpen className={ICON} />,
action: () => onSelectProject(p.id),
});
}
cmds.push({
id: 'add-project',
label: 'Add Project',
category: 'Projects',
keywords: 'folder new open browse',
icon: <FolderPlus className={ICON} />,
action: onAddProject,
});
// ── General ──
cmds.push({
id: 'search-sessions',
label: 'Search Sessions',
category: 'General',
keywords: 'find search messages content text',
shortcut: shortcutKeys('search-sessions'),
icon: <Search className={ICON} />,
action: onShowSearch,
});
cmds.push({
id: 'settings',
label: 'Open Settings',
category: 'General',
keywords: 'preferences config options',
shortcut: shortcutKeys('settings'),
icon: <Settings className={ICON} />,
action: onOpenSettings,
});
if (selectedProject && !isScratchpadProject(selectedProject)) {
cmds.push({
id: 'project-settings',
label: `Project Settings — ${selectedProject.name}`,
category: 'General',
keywords: 'project config options customization',
icon: <Settings className={ICON} />,
action: () => onOpenProjectSettings(selectedProject.id),
});
}
cmds.push({
id: 'toggle-terminal',
label: 'Toggle Terminal',
category: 'General',
keywords: 'terminal console shell command',
shortcut: shortcutKeys('toggle-terminal'),
icon: <Terminal className={ICON} />,
action: onToggleTerminal,
});
cmds.push({
id: 'app-data',
label: 'Open App Data Folder',
category: 'General',
keywords: 'data storage files folder workspace',
icon: <FolderOpen className={ICON} />,
action: onOpenAppDataFolder,
});
cmds.push({
id: 'keyboard-shortcuts',
label: 'Keyboard Shortcuts',
category: 'General',
keywords: 'keys keybindings hotkeys help cheatsheet',
shortcut: shortcutKeys('shortcut-help'),
icon: <Keyboard className={ICON} />,
action: onShowShortcuts,
});
// ── Theme ──
cmds.push({
id: 'theme-dark',
label: 'Dark Theme',
category: 'Theme',
keywords: 'appearance dark mode night',
icon: <Moon className={ICON} />,
action: () => onSetTheme('dark'),
});
cmds.push({
id: 'theme-light',
label: 'Light Theme',
category: 'Theme',
keywords: 'appearance light mode day',
icon: <Sun className={ICON} />,
action: () => onSetTheme('light'),
});
cmds.push({
id: 'theme-system',
label: 'System Theme',
category: 'Theme',
keywords: 'appearance auto system follow',
icon: <Monitor className={ICON} />,
action: () => onSetTheme('system'),
});
return cmds;
}, [
workspace, selectedSession, selectedProject,
onSelectSession, onSelectProject, onNewSession, onCreateScratchpad,
onOpenSettings, onOpenProjectSettings, onToggleTerminal, onSetTheme,
onDuplicateSession, onPinSession, onArchiveSession, onAddProject,
onOpenAppDataFolder, onShowShortcuts, onShowSearch,
]);
const filteredCommands = useMemo(() => {
if (!query.trim()) return commands;
return commands
.map((cmd) => ({ cmd, score: matchScore(query, cmd.label, cmd.keywords) }))
.filter(({ score }) => score > 0)
.sort((a, b) => b.score - a.score)
.map(({ cmd }) => cmd);
}, [commands, query]);
const groupedCommands = useMemo(() => {
const groups: { category: string; commands: PaletteCommand[] }[] = [];
const seen = new Set<string>();
for (const cmd of filteredCommands) {
if (!seen.has(cmd.category)) {
seen.add(cmd.category);
groups.push({ category: cmd.category, commands: [] });
}
groups.find((g) => g.category === cmd.category)!.commands.push(cmd);
}
return groups;
}, [filteredCommands]);
useEffect(() => {
setSelectedIndex(0);
}, [query]);
const executeCommand = useCallback(
(cmd: PaletteCommand) => {
onClose();
cmd.action();
},
[onClose],
);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (e.key === 'ArrowDown') {
e.preventDefault();
if (filteredCommands.length > 0) {
setSelectedIndex((i) => Math.min(i + 1, filteredCommands.length - 1));
}
} else if (e.key === 'ArrowUp') {
e.preventDefault();
setSelectedIndex((i) => Math.max(i - 1, 0));
} else if (e.key === 'Enter') {
e.preventDefault();
const cmd = filteredCommands[selectedIndex];
if (cmd) executeCommand(cmd);
}
},
[filteredCommands, selectedIndex, executeCommand],
);
useEffect(() => {
const item = listRef.current?.querySelector(`[data-palette-index="${selectedIndex}"]`);
item?.scrollIntoView({ block: 'nearest' });
}, [selectedIndex]);
let flatIndex = 0;
return (
<div
className="palette-backdrop-enter fixed inset-0 z-[60] flex justify-center bg-[#07080e]/80 pt-[18vh] backdrop-blur-sm"
onClick={onClose}
role="dialog"
aria-modal="true"
aria-label="Command palette"
>
<div
className="palette-enter glow-border flex h-fit max-h-[min(420px,60vh)] w-full max-w-xl flex-col overflow-hidden rounded-xl bg-[var(--color-surface-1)] shadow-[0_16px_64px_rgba(0,0,0,0.5)]"
onClick={(e) => e.stopPropagation()}
onKeyDown={handleKeyDown}
>
{/* Search input */}
<div className="flex items-center gap-3 border-b border-[var(--color-border)] px-4">
<Search className="size-4 shrink-0 text-[var(--color-text-muted)]" />
<input
ref={inputRef}
type="text"
className="flex-1 bg-transparent py-3.5 text-[14px] text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-muted)]"
placeholder="Type a command…"
value={query}
onChange={(e) => setQuery(e.target.value)}
aria-label="Search commands"
autoComplete="off"
spellCheck={false}
/>
{query && (
<button
className="shrink-0 rounded px-1.5 py-0.5 text-[11px] text-[var(--color-text-muted)] transition hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]"
onClick={() => setQuery('')}
type="button"
>
Clear
</button>
)}
</div>
{/* Results */}
<div ref={listRef} className="flex-1 overflow-y-auto py-1.5" role="listbox">
{groupedCommands.length === 0 ? (
<div className="px-4 py-8 text-center text-[13px] text-[var(--color-text-muted)]">
No matching commands
</div>
) : (
groupedCommands.map((group) => (
<div key={group.category}>
<div className="px-4 pb-1 pt-2.5 text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-muted)]">
{group.category}
</div>
{group.commands.map((cmd) => {
const index = flatIndex++;
const isSelected = index === selectedIndex;
return (
<button
key={cmd.id}
data-palette-index={index}
className={`flex w-full items-center gap-3 px-4 py-2 text-left text-[13px] transition-colors ${
isSelected
? 'bg-[var(--color-accent-muted)] text-[var(--color-text-primary)]'
: 'text-[var(--color-text-secondary)] hover:bg-[var(--color-glass-hover)] hover:text-[var(--color-text-primary)]'
}`}
onClick={() => executeCommand(cmd)}
onMouseEnter={() => setSelectedIndex(index)}
role="option"
aria-selected={isSelected}
type="button"
>
<span
className={
isSelected
? 'text-[var(--color-text-accent)]'
: 'text-[var(--color-text-muted)]'
}
>
{cmd.icon}
</span>
<span className="flex-1 truncate">{cmd.label}</span>
{cmd.shortcut && (
<kbd className="rounded border border-[var(--color-border)] bg-[var(--color-surface-0)] px-1.5 py-0.5 font-mono text-[10px] text-[var(--color-text-muted)]">
{cmd.shortcut}
</kbd>
)}
</button>
);
})}
</div>
))
)}
</div>
{/* Footer hints */}
<div className="flex items-center gap-4 border-t border-[var(--color-border)] px-4 py-2 text-[11px] text-[var(--color-text-muted)]">
<span className="flex items-center gap-1">
<kbd className="rounded border border-[var(--color-border-subtle)] px-1 font-mono text-[10px]">
</kbd>
navigate
</span>
<span className="flex items-center gap-1">
<kbd className="rounded border border-[var(--color-border-subtle)] px-1 font-mono text-[10px]">
</kbd>
select
</span>
<span className="flex items-center gap-1">
<kbd className="rounded border border-[var(--color-border-subtle)] px-1 font-mono text-[10px]">
esc
</kbd>
close
</span>
</div>
</div>
</div>
);
}
+197 -48
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 {
@@ -40,35 +44,35 @@ function getStatusConfig(status: SidecarConnectionStatus): StatusConfig {
switch (status) {
case 'ready':
return {
icon: <CheckCircle2 className="size-4 text-emerald-400" />,
icon: <CheckCircle2 className="size-4 text-[var(--color-status-success)]" />,
label: 'Connected to GitHub Copilot',
accentClasses: 'text-emerald-400',
dotClasses: 'bg-emerald-400',
accentClasses: 'text-[var(--color-status-success)]',
dotClasses: 'bg-[var(--color-status-success)]',
};
case 'copilot-cli-missing':
return {
icon: <Download className="size-4 text-amber-400" />,
icon: <Download className="size-4 text-[var(--color-status-warning)]" />,
label: 'Copilot CLI not found',
accentClasses: 'text-amber-400',
dotClasses: 'bg-amber-400',
accentClasses: 'text-[var(--color-status-warning)]',
dotClasses: 'bg-[var(--color-status-warning)]',
actionIcon: <Terminal className="size-3" />,
actionLabel: 'Install the copilot CLI and ensure it is on your PATH',
};
case 'copilot-auth-required':
return {
icon: <LogIn className="size-4 text-blue-400" />,
icon: <LogIn className="size-4 text-[var(--color-status-info)]" />,
label: 'Sign-in required',
accentClasses: 'text-blue-400',
dotClasses: 'bg-blue-400',
accentClasses: 'text-[var(--color-status-info)]',
dotClasses: 'bg-[var(--color-status-info)]',
actionIcon: <Terminal className="size-3" />,
actionLabel: 'Run copilot auth login in your terminal, then refresh',
};
case 'copilot-error':
return {
icon: <XCircle className="size-4 text-red-400" />,
icon: <XCircle className="size-4 text-[var(--color-status-error)]" />,
label: 'Connection error',
accentClasses: 'text-red-400',
dotClasses: 'bg-red-400',
accentClasses: 'text-[var(--color-status-error)]',
dotClasses: 'bg-[var(--color-status-error)]',
};
}
}
@@ -104,27 +108,158 @@ function VersionBadge({ status, installedVersion }: { status: SidecarCopilotCliV
switch (status) {
case 'latest':
return (
<span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2 py-0.5 text-[10px] font-medium text-emerald-400">
<span className="inline-flex items-center gap-1 rounded-full bg-[var(--color-status-success)]/10 px-2 py-0.5 text-[10px] font-medium text-[var(--color-status-success)]">
<CheckCircle2 className="size-2.5" />
{versionLabel ?? 'Up to date'}
</span>
);
case 'outdated':
return (
<span className="inline-flex items-center gap-1 rounded-full bg-amber-500/10 px-2 py-0.5 text-[10px] font-medium text-amber-400">
<span className="inline-flex items-center gap-1 rounded-full bg-[var(--color-status-warning)]/10 px-2 py-0.5 text-[10px] font-medium text-[var(--color-status-warning)]">
<ArrowUpCircle className="size-2.5" />
Update available
</span>
);
case 'unknown':
return (
<span className="inline-flex items-center gap-1 rounded-full bg-zinc-800 px-2 py-0.5 text-[10px] font-medium text-zinc-500">
<span className="inline-flex items-center gap-1 rounded-full bg-[var(--color-surface-3)] px-2 py-0.5 text-[10px] font-medium text-[var(--color-text-muted)]">
{versionLabel ?? 'Version unknown'}
</span>
);
}
}
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-[var(--color-text-muted)]" />
<span className="text-[12px] text-[var(--color-text-muted)]">Loading quota</span>
</div>
);
}
if (error) {
return (
<div className="flex items-center gap-2 py-2">
<XCircle className="size-3.5 text-[var(--color-status-error)]" />
<span className="text-[12px] text-[var(--color-text-muted)]">Could not load quota</span>
</div>
);
}
if (!quotaData || Object.keys(quotaData).length === 0) {
return (
<div className="py-2">
<span className="text-[12px] text-[var(--color-text-muted)]">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-[var(--color-status-error)]'
: usedPct > 70
? 'bg-[var(--color-status-warning)]'
: 'bg-[var(--color-accent)]/60';
return (
<div key={key} className="space-y-1.5">
<div className="flex items-center justify-between">
<span className="text-[12px] font-medium text-[var(--color-text-secondary)]">
{formatQuotaTypeLabel(key)}
</span>
<span className="text-[11px] tabular-nums text-[var(--color-text-muted)]">
{Math.round(snapshot.remainingPercentage)}% remaining
</span>
</div>
<div className="h-1.5 overflow-hidden rounded-full bg-[var(--color-surface-3)]">
<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-[var(--color-text-muted)]">
<span className="tabular-nums">
{Math.round(snapshot.usedRequests)} of {Math.round(snapshot.entitlementRequests)} used
</span>
{snapshot.overage > 0 && (
<>
<span className="text-[var(--color-text-muted)]">·</span>
<span className="tabular-nums text-[var(--color-status-warning)]">
{Math.round(snapshot.overage)} overage
</span>
</>
)}
{snapshot.resetDate && (
<>
<span className="text-[var(--color-text-muted)]">·</span>
<span>Resets {formatResetDate(snapshot.resetDate)}</span>
</>
)}
</div>
</div>
);
})}
</div>
);
}
function AccountSection({ connection }: { connection: SidecarConnectionDiagnostics }) {
const { account } = connection;
if (!account) return null;
@@ -141,34 +276,34 @@ function AccountSection({ connection }: { connection: SidecarConnectionDiagnosti
<div className="space-y-2.5">
{/* Identity row */}
<div className="flex items-center gap-2">
<User className="size-3.5 text-zinc-500" />
<User className="size-3.5 text-[var(--color-text-muted)]" />
{hasLogin ? (
<div className="flex items-center gap-1.5 text-[12px]">
<span className="font-medium text-zinc-200">{account.login}</span>
<span className="font-medium text-[var(--color-text-primary)]">{account.login}</span>
{account.host && (
<span className="text-zinc-500">· {account.host}</span>
<span className="text-[var(--color-text-muted)]">· {account.host}</span>
)}
</div>
) : (
<span className="text-[12px] text-zinc-500">{account.statusMessage}</span>
<span className="text-[12px] text-[var(--color-text-muted)]">{account.statusMessage}</span>
)}
</div>
{/* Organizations */}
{hasOrgs && (
<div className="flex items-start gap-2">
<Building2 className="mt-0.5 size-3.5 shrink-0 text-zinc-500" />
<Building2 className="mt-0.5 size-3.5 shrink-0 text-[var(--color-text-muted)]" />
<div className="flex flex-wrap items-center gap-1">
{visibleOrgs.map((org) => (
<span
className="rounded-md bg-zinc-800 px-1.5 py-0.5 text-[10px] font-medium text-zinc-400"
className="rounded-md bg-[var(--color-surface-3)] px-1.5 py-0.5 text-[10px] font-medium text-[var(--color-text-secondary)]"
key={org}
>
{org}
</span>
))}
{remainingOrgs > 0 && (
<span className="text-[10px] text-zinc-600">+{remainingOrgs} more</span>
<span className="text-[10px] text-[var(--color-text-muted)]">+{remainingOrgs} more</span>
)}
</div>
</div>
@@ -182,15 +317,16 @@ export function CopilotStatusCard({
modelCount,
isRefreshing,
onRefresh,
onGetQuota,
}: CopilotStatusCardProps) {
const [showDetails, setShowDetails] = useState(false);
if (!connection) {
return (
<div className="flex items-center gap-3 rounded-xl border border-[var(--color-border)] bg-zinc-900/40 px-4 py-3">
<Cpu className="size-4 text-zinc-600" />
<span className="text-[13px] text-zinc-500">Checking connection</span>
<RefreshCw className="ml-auto size-3.5 animate-spin text-zinc-600" />
<div className="flex items-center gap-3 rounded-xl border border-[var(--color-border)] bg-[var(--color-glass)] px-4 py-3">
<Cpu className="size-4 text-[var(--color-text-muted)]" />
<span className="text-[13px] text-[var(--color-text-muted)]">Checking connection</span>
<RefreshCw className="ml-auto size-3.5 animate-spin text-[var(--color-text-muted)]" />
</div>
);
}
@@ -211,7 +347,7 @@ export function CopilotStatusCard({
{config.label}
</span>
{isHealthy && (
<span className="text-[12px] text-zinc-500">
<span className="text-[12px] text-[var(--color-text-muted)]">
· {modelCount} model{modelCount === 1 ? '' : 's'} available
</span>
)}
@@ -223,10 +359,10 @@ export function CopilotStatusCard({
/>
)}
{checkedLabel && (
<span className="text-[11px] text-zinc-600">{checkedLabel}</span>
<span className="text-[11px] text-[var(--color-text-muted)]">{checkedLabel}</span>
)}
<button
className="flex size-6 items-center justify-center rounded-md text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300 disabled:opacity-50"
className="flex size-6 items-center justify-center rounded-md text-[var(--color-text-muted)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)] disabled:opacity-50"
disabled={isRefreshing}
onClick={onRefresh}
title="Refresh connection status"
@@ -242,11 +378,24 @@ 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-[var(--color-text-secondary)]">
<BarChart3 className="size-3" />
<span>Usage &amp; Quota</span>
</div>
<div className="rounded-lg border border-[var(--color-border-subtle)] bg-[var(--color-glass)] 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">
<div className="flex items-start gap-2 rounded-lg border border-[var(--color-border)] bg-[var(--color-glass)] px-3 py-2.5">
<div className="mt-0.5 shrink-0">{config.actionIcon}</div>
<p className="text-[12px] leading-relaxed text-zinc-400">{config.actionLabel}</p>
<p className="text-[12px] leading-relaxed text-[var(--color-text-secondary)]">{config.actionLabel}</p>
</div>
)}
@@ -254,7 +403,7 @@ export function CopilotStatusCard({
{isHealthy && hasDetail && (
<div className="space-y-2">
<button
className="flex w-full items-center gap-1.5 text-[11px] text-zinc-600 transition hover:text-zinc-400"
className="flex w-full items-center gap-1.5 text-[11px] text-[var(--color-text-muted)] transition-all duration-200 hover:text-[var(--color-text-secondary)]"
onClick={() => setShowDetails((prev) => !prev)}
type="button"
>
@@ -263,26 +412,26 @@ export function CopilotStatusCard({
</button>
{showDetails && (
<div className="overflow-hidden rounded-lg border border-zinc-800/60 bg-zinc-900/40">
<div className="overflow-hidden rounded-lg border border-[var(--color-border-subtle)] bg-[var(--color-glass)]">
{connection.copilotCliPath && (
<div className="border-b border-zinc-800/40 px-3 py-2">
<span className="text-[10px] font-medium uppercase tracking-wider text-zinc-600">CLI path</span>
<p className="mt-0.5 break-all font-mono text-[11px] text-zinc-400" title={connection.copilotCliPath}>
<div className="border-b border-[var(--color-border-subtle)] px-3 py-2">
<span className="text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-muted)]">CLI path</span>
<p className="mt-0.5 break-all font-mono text-[11px] text-[var(--color-text-secondary)]" title={connection.copilotCliPath}>
{connection.copilotCliPath}
</p>
</div>
)}
{hasVersionInfo && connection.copilotCliVersion!.status === 'outdated' && connection.copilotCliVersion!.latestVersion && (
<div className="border-b border-zinc-800/40 px-3 py-2">
<span className="text-[10px] font-medium uppercase tracking-wider text-zinc-600">Latest version</span>
<p className="mt-0.5 font-mono text-[11px] text-zinc-400">
<div className="border-b border-[var(--color-border-subtle)] px-3 py-2">
<span className="text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-muted)]">Latest version</span>
<p className="mt-0.5 font-mono text-[11px] text-[var(--color-text-secondary)]">
{connection.copilotCliVersion!.latestVersion}
</p>
</div>
)}
<div className="px-3 py-2">
<span className="text-[10px] font-medium uppercase tracking-wider text-zinc-600">Last checked</span>
<p className="mt-0.5 text-[11px] text-zinc-400">
<span className="text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-muted)]">Last checked</span>
<p className="mt-0.5 text-[11px] text-[var(--color-text-secondary)]">
{new Date(connection.checkedAt).toLocaleString()}
</p>
</div>
@@ -293,17 +442,17 @@ export function CopilotStatusCard({
{/* Error detail for non-ready states */}
{!isHealthy && hasDetail && (
<div className="overflow-hidden rounded-lg border border-zinc-800/60 bg-zinc-900/40">
<div className="border-b border-zinc-800/40 px-3 py-2">
<span className="text-[10px] font-medium uppercase tracking-wider text-zinc-600">CLI path</span>
<p className="mt-0.5 break-all font-mono text-[11px] text-zinc-400" title={connection.copilotCliPath}>
<div className="overflow-hidden rounded-lg border border-[var(--color-border-subtle)] bg-[var(--color-glass)]">
<div className="border-b border-[var(--color-border-subtle)] px-3 py-2">
<span className="text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-muted)]">CLI path</span>
<p className="mt-0.5 break-all font-mono text-[11px] text-[var(--color-text-secondary)]" title={connection.copilotCliPath}>
{shortenPath(connection.copilotCliPath!)}
</p>
</div>
{connection.detail && (
<div className="px-3 py-2">
<span className="text-[10px] font-medium uppercase tracking-wider text-zinc-600">Error detail</span>
<p className="mt-0.5 break-words text-[11px] text-zinc-400">{connection.detail}</p>
<span className="text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-muted)]">Error detail</span>
<p className="mt-0.5 break-words text-[11px] text-[var(--color-text-secondary)]">{connection.detail}</p>
</div>
)}
</div>
@@ -81,20 +81,20 @@ export function DiscoveredToolingModal({
<div
aria-labelledby="discovered-tooling-title"
aria-modal="true"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm"
className="overlay-backdrop-enter fixed inset-0 z-50 flex items-center justify-center bg-[#07080e]/90 backdrop-blur-sm"
role="dialog"
>
<div className="flex max-h-[80vh] w-full max-w-lg flex-col rounded-xl border border-zinc-800 bg-zinc-900 shadow-2xl">
<div className="overlay-panel-enter flex max-h-[80vh] w-full max-w-lg flex-col rounded-xl border border-[var(--color-border)] bg-[var(--color-surface-1)] shadow-[0_16px_64px_rgba(0,0,0,0.5)]">
{/* Header */}
<div className="flex items-center justify-between border-b border-zinc-800 px-5 py-4">
<div className="flex items-center justify-between border-b border-[var(--color-border)] px-5 py-4">
<div className="flex items-center gap-2.5">
<FileSearch className="size-4 text-indigo-400" />
<h2 id="discovered-tooling-title" className="text-[13px] font-semibold text-zinc-100">
<FileSearch className="size-4 text-[var(--color-text-accent)]" />
<h2 id="discovered-tooling-title" className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">
MCP servers found in config files
</h2>
</div>
<button
className="flex size-7 items-center justify-center rounded-lg text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300"
className="flex size-7 items-center justify-center rounded-lg text-[var(--color-text-muted)] transition hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]"
onClick={onClose}
type="button"
>
@@ -104,7 +104,7 @@ export function DiscoveredToolingModal({
{/* Body */}
<div className="flex-1 overflow-y-auto px-5 py-4">
<p className="mb-4 text-[12px] leading-relaxed text-zinc-500">
<p className="mb-4 text-[12px] leading-relaxed text-[var(--color-text-muted)]">
The following MCP servers were found in your config files. Accept the ones you want to
use, or dismiss those you don&apos;t need. Accepted servers become available for session tooling.
</p>
@@ -127,20 +127,20 @@ export function DiscoveredToolingModal({
</div>
{/* Footer */}
<div className="flex items-center justify-between border-t border-zinc-800 px-5 py-3">
<span className="text-[12px] text-zinc-600">
<div className="flex items-center justify-between border-t border-[var(--color-border)] px-5 py-3">
<span className="text-[12px] text-[var(--color-text-muted)]">
{totalPending} server{totalPending === 1 ? '' : 's'} pending review
</span>
<div className="flex items-center gap-2">
<button
className="rounded-lg px-3 py-1.5 text-[13px] text-zinc-400 transition hover:bg-zinc-800 hover:text-zinc-200"
className="rounded-lg px-3 py-1.5 text-[13px] text-[var(--color-text-secondary)] transition hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]"
onClick={handleDismissAll}
type="button"
>
Dismiss All
</button>
<button
className="rounded-lg bg-indigo-600 px-3 py-1.5 text-[13px] font-medium text-white transition hover:bg-indigo-500"
className="rounded-lg bg-[var(--color-accent)] px-3 py-1.5 text-[13px] font-medium text-white transition hover:bg-[var(--color-accent-sky)]"
onClick={handleAcceptAll}
type="button"
>
@@ -166,15 +166,15 @@ function DiscoveredGroup({
}) {
return (
<div className="mb-4">
<div className="mb-2 text-[10px] font-semibold uppercase tracking-wider text-zinc-600">
<div className="mb-2 text-[10px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
{scopeLabel}
</div>
{groups.map((group) => (
<div className="mb-3" key={group.sourceLabel}>
<div className="mb-1.5 flex items-center gap-1.5 text-[11px] text-zinc-500">
<div className="mb-1.5 flex items-center gap-1.5 text-[11px] text-[var(--color-text-muted)]">
<span className="truncate font-medium">{group.sourceLabel}</span>
<span className="text-zinc-700">·</span>
<span className="text-zinc-600">
<span className="text-[var(--color-text-muted)]">·</span>
<span className="text-[var(--color-text-muted)]">
{group.servers.length} server{group.servers.length === 1 ? '' : 's'}
</span>
</div>
@@ -211,22 +211,22 @@ function ServerRow({
: server.url || 'No URL';
return (
<div className="group flex items-center gap-3 rounded-lg border border-zinc-800/60 bg-zinc-800/20 px-3 py-2.5">
<Server className="size-3.5 shrink-0 text-zinc-600" />
<div className="group flex items-center gap-3 rounded-lg border border-[var(--color-border-subtle)] bg-[var(--color-glass)] px-3 py-2.5">
<Server className="size-3.5 shrink-0 text-[var(--color-text-muted)]" />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate text-[13px] font-medium text-zinc-200">
<span className="truncate text-[13px] font-medium text-[var(--color-text-primary)]">
{server.name}
</span>
<span className="rounded-full bg-zinc-800 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-zinc-500">
<span className="rounded-full bg-[var(--color-surface-3)] px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-[var(--color-text-muted)]">
{server.transport}
</span>
</div>
<p className="mt-0.5 truncate text-[12px] text-zinc-500">{detail}</p>
<p className="mt-0.5 truncate text-[12px] text-[var(--color-text-muted)]">{detail}</p>
</div>
<div className="flex items-center gap-1">
<button
className="flex size-7 items-center justify-center rounded-md text-zinc-600 transition hover:bg-red-500/10 hover:text-red-400"
className="flex size-7 items-center justify-center rounded-md text-[var(--color-text-muted)] transition hover:bg-[var(--color-status-error)]/10 hover:text-[var(--color-status-error)]"
onClick={onDismiss}
title="Dismiss"
type="button"
@@ -234,7 +234,7 @@ function ServerRow({
<XCircle className="size-3.5" />
</button>
<button
className="flex size-7 items-center justify-center rounded-md text-zinc-600 transition hover:bg-emerald-500/10 hover:text-emerald-400"
className="flex size-7 items-center justify-center rounded-md text-[var(--color-text-muted)] transition hover:bg-[var(--color-status-success)]/10 hover:text-[var(--color-status-success)]"
onClick={onAccept}
title="Accept"
type="button"
@@ -0,0 +1,120 @@
import { useEffect } from 'react';
import { Keyboard } from 'lucide-react';
import { shortcuts, type ShortcutDefinition } from '@renderer/lib/keyboardShortcuts';
interface KeyboardShortcutsPanelProps {
onClose: () => void;
}
const categoryOrder = ['Navigation', 'Sessions', 'Workspace', 'General'] as const;
function groupByCategory(defs: ShortcutDefinition[]): Map<string, ShortcutDefinition[]> {
const groups = new Map<string, ShortcutDefinition[]>();
for (const def of defs) {
const list = groups.get(def.category) ?? [];
list.push(def);
groups.set(def.category, list);
}
return groups;
}
export function KeyboardShortcutsPanel({ onClose }: KeyboardShortcutsPanelProps) {
// Escape to close — capture phase so it doesn't propagate
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
e.preventDefault();
e.stopImmediatePropagation();
onClose();
}
};
document.addEventListener('keydown', handleEscape, true);
return () => document.removeEventListener('keydown', handleEscape, true);
}, [onClose]);
const grouped = groupByCategory(shortcuts);
return (
<div
className="palette-backdrop-enter fixed inset-0 z-[70] flex items-center justify-center bg-[#07080e]/80 backdrop-blur-sm"
onClick={onClose}
role="dialog"
aria-modal="true"
aria-labelledby="shortcuts-title"
>
<div
className="palette-enter w-full max-w-lg overflow-hidden rounded-xl border border-[var(--color-border)] bg-[var(--color-surface-1)] shadow-[0_24px_80px_rgba(0,0,0,0.55)]"
onClick={(e) => e.stopPropagation()}
>
{/* Header */}
<div className="flex items-center gap-3 border-b border-[var(--color-border)] px-5 py-3.5">
<Keyboard className="size-4 text-[var(--color-text-accent)]" />
<h2
id="shortcuts-title"
className="font-display text-[14px] font-semibold text-[var(--color-text-primary)]"
>
Keyboard Shortcuts
</h2>
<span className="ml-auto text-[11px] text-[var(--color-text-muted)]">
Press <Kbd>Esc</Kbd> to close
</span>
</div>
{/* Body — two-column grid of categories */}
<div className="grid grid-cols-2 gap-x-6 gap-y-5 px-5 py-4">
{categoryOrder.map((cat) => {
const items = grouped.get(cat);
if (!items?.length) return null;
return (
<div key={cat}>
<h3 className="mb-2 text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-muted)]">
{cat}
</h3>
<ul className="space-y-1.5">
{items.map((item) => (
<li
key={item.id}
className="flex items-center justify-between gap-3 text-[12.5px]"
>
<span className="truncate text-[var(--color-text-secondary)]">
{item.label}
</span>
<ShortcutBadge keys={item.keys} />
</li>
))}
</ul>
</div>
);
})}
</div>
{/* Footer */}
<div className="border-t border-[var(--color-border)] px-5 py-2.5 text-[11px] text-[var(--color-text-muted)]">
Tip: Use the command palette for even more actions
</div>
</div>
</div>
);
}
/** Inline keyboard key cap. */
function Kbd({ children }: { children: React.ReactNode }) {
return (
<kbd className="rounded border border-[var(--color-border)] bg-[var(--color-surface-0)] px-1.5 py-0.5 font-mono text-[10px] text-[var(--color-text-muted)]">
{children}
</kbd>
);
}
/** Renders a compound shortcut like "Ctrl+Shift+Tab" as joined key caps. */
function ShortcutBadge({ keys }: { keys: string }) {
const parts = keys.split('+');
return (
<span className="flex shrink-0 items-center gap-0.5">
{parts.map((part, i) => (
<Kbd key={i}>{part}</Kbd>
))}
</span>
);
}
+9 -59
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));
@@ -727,11 +677,11 @@ function ToolbarPlugin({ disabled }: { disabled: boolean }) {
}, [editor]);
return (
<div className="flex items-center gap-0.5 border-b border-zinc-700/50 px-2 py-1">
<div className="flex items-center gap-0.5 border-b border-[var(--color-border)]/50 px-2 py-1">
<ToolbarButton active={state.isBold} disabled={disabled} icon={<Bold className="size-3.5" />} onClick={formatBold} onMouseDown={preventFocus} title="Bold (Ctrl+B)" />
<ToolbarButton active={state.isItalic} disabled={disabled} icon={<Italic className="size-3.5" />} onClick={formatItalic} onMouseDown={preventFocus} title="Italic (Ctrl+I)" />
<ToolbarButton active={state.isCode} disabled={disabled} icon={<Code className="size-3.5" />} onClick={formatInlineCode} onMouseDown={preventFocus} title="Inline Code" />
<div className="mx-1 h-4 w-px bg-zinc-700/50" />
<div className="mx-1 h-4 w-px bg-[var(--color-border)]/50" />
<ToolbarButton active={state.blockType === 'ul'} disabled={disabled} icon={<List className="size-3.5" />} onClick={toggleBulletList} onMouseDown={preventFocus} title="Bullet List" />
<ToolbarButton active={state.blockType === 'ol'} disabled={disabled} icon={<ListOrdered className="size-3.5" />} onClick={toggleNumberedList} onMouseDown={preventFocus} title="Numbered List" />
<ToolbarButton active={state.blockType === 'code'} disabled={disabled} icon={<Braces className="size-3.5" />} onClick={toggleCodeBlock} onMouseDown={preventFocus} title="Code Block" />
@@ -759,8 +709,8 @@ function ToolbarButton({
aria-pressed={active}
className={`flex size-7 items-center justify-center rounded transition ${
active
? 'bg-indigo-600/30 text-indigo-300'
: 'text-zinc-500 hover:bg-zinc-800 hover:text-zinc-300'
? 'bg-[var(--color-accent)]/30 text-[var(--color-accent-sky)]'
: 'text-[var(--color-text-muted)] hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]'
} ${disabled ? 'pointer-events-none opacity-50' : ''}`}
disabled={disabled}
onClick={onClick}
+18 -18
View File
@@ -57,13 +57,13 @@ export function NewSessionModal({
const canCreate = projectId && patternId;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm" role="dialog" aria-modal="true" aria-labelledby="new-session-title">
<div className="w-full max-w-md rounded-xl border border-zinc-800 bg-zinc-900 shadow-2xl">
<div className="overlay-backdrop-enter fixed inset-0 z-50 flex items-center justify-center bg-[#07080e]/90 backdrop-blur-sm" role="dialog" aria-modal="true" aria-labelledby="new-session-title">
<div className="overlay-panel-enter w-full max-w-md rounded-xl border border-[var(--color-border)] bg-[var(--color-surface-1)] shadow-[0_16px_64px_rgba(0,0,0,0.5)]">
{/* Header */}
<div className="flex items-center justify-between border-b border-zinc-800 px-5 py-4">
<h2 id="new-session-title" className="text-[13px] font-semibold text-zinc-100">New Session</h2>
<div className="flex items-center justify-between border-b border-[var(--color-border)] px-5 py-4">
<h2 id="new-session-title" className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">New Session</h2>
<button
className="flex size-7 items-center justify-center rounded-lg text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300"
className="flex size-7 items-center justify-center rounded-lg text-[var(--color-text-muted)] transition hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]"
onClick={onClose}
type="button"
>
@@ -74,9 +74,9 @@ export function NewSessionModal({
{/* Body */}
<div className="space-y-4 px-5 py-5">
<label className="block space-y-1.5">
<span className="text-[12px] font-medium text-zinc-400">Project</span>
<span className="text-[12px] font-medium text-[var(--color-text-secondary)]">Project</span>
<select
className="w-full rounded-lg border border-zinc-700 bg-zinc-950 px-3 py-2 text-[13px] text-zinc-100 outline-none transition focus:border-indigo-500/50"
className="w-full rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-0)] px-3 py-2 text-[13px] text-[var(--color-text-primary)] outline-none transition focus:border-[var(--color-accent)]/50"
onChange={(e) => setProjectId(e.target.value)}
value={projectId}
>
@@ -89,28 +89,28 @@ export function NewSessionModal({
</label>
<label className="block space-y-1.5">
<span className="text-[12px] font-medium text-zinc-400">Pattern</span>
<div className="space-y-1 rounded-lg border border-zinc-700 bg-zinc-950 p-1.5">
<span className="text-[12px] font-medium text-[var(--color-text-secondary)]">Pattern</span>
<div className="space-y-1 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-0)] p-1.5">
{availablePatterns.map((p) => (
<div
key={p.id}
className={`flex cursor-pointer items-center gap-2 rounded-md px-2.5 py-1.5 text-[13px] transition ${
patternId === p.id
? 'bg-indigo-500/15 text-zinc-100 ring-1 ring-indigo-500/25'
: 'text-zinc-300 hover:bg-zinc-800/60'
? 'bg-[var(--color-accent-muted)] text-[var(--color-text-primary)] ring-1 ring-[var(--color-border-glow)]'
: 'text-[var(--color-text-secondary)] hover:bg-[var(--color-glass-hover)]'
}`}
onClick={() => setPatternId(p.id)}
>
<span className="flex-1 truncate">
{p.name}
<span className="ml-1.5 text-[11px] text-zinc-500">({p.mode})</span>
<span className="ml-1.5 text-[11px] text-[var(--color-text-muted)]">({p.mode})</span>
</span>
{onTogglePatternFavorite && (
<button
className={`shrink-0 transition ${
p.isFavorite
? 'text-amber-400 hover:text-amber-300'
: 'text-zinc-700 hover:text-zinc-400'
? 'text-[var(--color-status-warning)] hover:text-[var(--color-status-warning)]'
: 'text-[var(--color-text-muted)] hover:text-[var(--color-text-secondary)]'
}`}
onClick={(e) => {
e.stopPropagation();
@@ -126,7 +126,7 @@ export function NewSessionModal({
))}
</div>
{patternId && (
<p className="text-[12px] text-zinc-600">
<p className="text-[12px] text-[var(--color-text-muted)]">
{availablePatterns.find((p) => p.id === patternId)?.description}
</p>
)}
@@ -134,16 +134,16 @@ export function NewSessionModal({
</div>
{/* Footer */}
<div className="flex items-center justify-end gap-2 border-t border-zinc-800 px-5 py-3">
<div className="flex items-center justify-end gap-2 border-t border-[var(--color-border)] px-5 py-3">
<button
className="rounded-lg px-4 py-1.5 text-[13px] text-zinc-400 transition hover:bg-zinc-800 hover:text-zinc-200"
className="rounded-lg px-4 py-1.5 text-[13px] text-[var(--color-text-secondary)] transition hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]"
onClick={onClose}
type="button"
>
Cancel
</button>
<button
className="rounded-lg bg-indigo-600 px-4 py-1.5 text-[13px] font-medium text-white transition hover:bg-indigo-500 disabled:cursor-not-allowed disabled:opacity-40"
className="rounded-lg bg-[var(--color-accent)] px-4 py-1.5 text-[13px] font-medium text-white transition hover:bg-[var(--color-accent-sky)] disabled:cursor-not-allowed disabled:opacity-40"
disabled={!canCreate}
onClick={() => canCreate && onCreate(projectId, patternId)}
type="button"
+50 -51
View File
@@ -105,10 +105,10 @@ function InputField({
placeholder?: string;
}) {
const baseClasses =
'w-full rounded-lg border border-zinc-700 bg-zinc-900 px-3 py-2 text-[13px] text-zinc-100 placeholder-zinc-600 outline-none transition focus:border-indigo-500/50';
'w-full rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] px-3 py-2 text-[13px] text-[var(--color-text-primary)] placeholder-[var(--color-text-muted)] outline-none transition-all duration-200 focus:border-[var(--color-accent)]/50';
return (
<label className="block space-y-1.5">
<span className="text-[12px] font-medium text-zinc-400">{label}</span>
<span className="text-[12px] font-medium text-[var(--color-text-secondary)]">{label}</span>
{multiline ? (
<textarea
className={`${baseClasses} min-h-20 resize-y`}
@@ -242,17 +242,17 @@ export function PatternEditor({
<div className="drag-region flex items-center justify-between border-b border-[var(--color-border)] pb-3 pl-5 pr-36 pt-3">
<div className="flex items-center gap-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"
className="no-drag flex size-8 items-center justify-center rounded-lg text-[var(--color-text-secondary)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]"
onClick={onBack}
type="button"
>
<ChevronLeft className="size-4" />
</button>
<div>
<h3 className="text-[13px] font-semibold text-zinc-100">
<h3 className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">
{pattern.name || 'Untitled pattern'}
</h3>
<p className="text-[12px] text-zinc-500">
<p className="text-[12px] text-[var(--color-text-muted)]">
{isBuiltin ? 'Built-in pattern' : 'Custom pattern'}
</p>
</div>
@@ -260,7 +260,7 @@ export function PatternEditor({
<div className="no-drag flex items-center gap-2">
{!isBuiltin && onDelete && (
<button
className="flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] text-red-400 transition hover:bg-red-500/10"
className="flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] text-[var(--color-status-error)] transition-all duration-200 hover:bg-[var(--color-status-error)]/10"
onClick={onDelete}
type="button"
>
@@ -269,7 +269,7 @@ export function PatternEditor({
</button>
)}
<button
className="rounded-lg bg-indigo-600 px-4 py-1.5 text-[13px] font-medium text-white transition hover:bg-indigo-500"
className="rounded-lg bg-[var(--color-accent)] px-4 py-1.5 text-[13px] font-medium text-white transition-all duration-200 hover:bg-[var(--color-accent-sky)]"
onClick={onSave}
type="button"
>
@@ -290,8 +290,8 @@ export function PatternEditor({
<div
className={`flex items-start gap-2 rounded-lg px-3 py-2 text-[12px] ${
issue.level === 'error'
? 'bg-red-500/10 text-red-300'
: 'bg-amber-500/10 text-amber-300'
? 'bg-[var(--color-status-error)]/10 text-[var(--color-status-error)]'
: 'bg-[var(--color-status-warning)]/10 text-[var(--color-status-warning)]'
}`}
key={`${issue.field ?? 'v'}-${i}`}
>
@@ -301,7 +301,7 @@ export function PatternEditor({
))}
</div>
) : (
<div className="flex items-center gap-2 rounded-lg bg-emerald-500/10 px-3 py-2 text-[12px] text-emerald-300">
<div className="flex items-center gap-2 rounded-lg bg-[var(--color-status-success)]/10 px-3 py-2 text-[12px] text-[var(--color-status-success)]">
<CheckCircle className="size-3.5" />
Pattern is valid
</div>
@@ -310,11 +310,11 @@ export function PatternEditor({
{/* Graph canvas */}
<div className="flex items-center justify-between px-5 pt-4">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-zinc-500">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
Topology
</h4>
<button
className="flex items-center gap-1.5 rounded-lg px-2.5 py-1 text-[12px] font-medium text-zinc-400 transition hover:bg-zinc-800 hover:text-zinc-200"
className="flex items-center gap-1.5 rounded-lg px-2.5 py-1 text-[12px] font-medium text-[var(--color-text-secondary)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]"
onClick={addAgent}
type="button"
>
@@ -335,11 +335,11 @@ export function PatternEditor({
</div>
{/* Scrollable settings below graph */}
<div className="max-h-[45%] overflow-y-auto border-t border-zinc-800/50 px-5 py-5">
<div className="max-h-[45%] overflow-y-auto border-t border-[var(--color-border-subtle)] px-5 py-5">
<div className="space-y-8">
{/* General */}
<section className="space-y-4">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-zinc-500">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
General
</h4>
<div className="grid gap-3 sm:grid-cols-2">
@@ -360,7 +360,7 @@ export function PatternEditor({
{/* Mode selector */}
<section className="space-y-4">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-zinc-500">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
Orchestration Mode
</h4>
<div className="grid grid-cols-3 gap-2">
@@ -372,12 +372,12 @@ export function PatternEditor({
return (
<button
className={`flex flex-col rounded-xl border p-2.5 text-left transition ${
className={`flex flex-col rounded-xl border p-2.5 text-left transition-all duration-200 ${
selected
? 'border-indigo-500/40 bg-indigo-500/5 ring-1 ring-indigo-500/20'
? 'border-[var(--color-border-glow)] bg-[var(--color-accent-muted)] ring-1 ring-[var(--color-border-glow)]'
: disabled
? 'cursor-not-allowed border-zinc-800/50 opacity-40'
: 'border-zinc-800 hover:border-zinc-700 hover:bg-zinc-900/60'
? 'cursor-not-allowed border-[var(--color-border-subtle)] opacity-40'
: 'border-[var(--color-border)] hover:border-[var(--color-border)] hover:bg-[var(--color-glass)]'
}`}
disabled={disabled}
key={mode}
@@ -386,17 +386,17 @@ export function PatternEditor({
>
<div className="flex items-center gap-1.5">
<Icon
className={`size-3.5 ${selected ? 'text-indigo-400' : 'text-zinc-500'}`}
className={`size-3.5 ${selected ? 'text-[var(--color-text-accent)]' : 'text-[var(--color-text-muted)]'}`}
/>
<span
className={`text-[11px] font-semibold ${
selected ? 'text-indigo-200' : 'text-zinc-300'
selected ? 'text-[var(--color-text-accent)]' : 'text-[var(--color-text-secondary)]'
}`}
>
{info.label}
</span>
</div>
<p className="mt-1 text-[10px] leading-snug text-zinc-500">
<p className="mt-1 text-[10px] leading-snug text-[var(--color-text-muted)]">
{info.description}
</p>
</button>
@@ -407,12 +407,11 @@ export function PatternEditor({
{/* Approval checkpoints */}
<section className="space-y-4">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-zinc-500">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
Approval Checkpoints
</h4>
<p className="text-[11px] leading-relaxed text-zinc-600">
Pause the run for human review before risky actions or publishing responses.
<p className="text-[11px] leading-relaxed text-[var(--color-text-muted)]">
</p>
<div className="space-y-3">
@@ -426,15 +425,15 @@ export function PatternEditor({
scopedAgentIds={checkpointAgentIds('tool-call')}
onScopeChange={(agentIds) => setCheckpointAgentScope('tool-call', agentIds)}
>
<div className="mb-1.5 text-[11px] font-semibold uppercase tracking-wider text-zinc-500">
<div className="mb-1.5 text-[11px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
Auto-approved tools
</div>
<p className="mb-3 text-[11px] leading-relaxed text-zinc-600">
<p className="mb-3 text-[11px] leading-relaxed text-[var(--color-text-muted)]">
Tools marked as auto-approved will skip manual review.
Sessions can override these defaults from the Activity panel.
</p>
{approvalTools.length === 0 ? (
<p className="py-2 text-center text-[11px] text-zinc-600">
<p className="py-2 text-center text-[11px] text-[var(--color-text-muted)]">
No tools available yet. Connect MCP servers or wait for runtime capabilities to load.
</p>
) : (
@@ -462,9 +461,9 @@ export function PatternEditor({
</div>
{/* Right column: node inspector */}
<div className="w-[320px] shrink-0 overflow-y-auto border-l border-zinc-800/50 bg-zinc-900/30">
<div className="border-b border-zinc-800/50 px-4 py-3">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-zinc-500">
<div className="w-[320px] shrink-0 overflow-y-auto border-l border-[var(--color-border-subtle)] bg-[var(--color-glass)]">
<div className="border-b border-[var(--color-border-subtle)] px-4 py-3">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
Inspector
</h4>
</div>
@@ -518,26 +517,26 @@ function ApprovalCheckpointRow({
}
return (
<div className="rounded-xl border border-zinc-800 bg-zinc-900/50 p-4">
<div className="rounded-xl border border-[var(--color-border)] bg-[var(--color-glass)] p-4">
<button className="flex w-full items-center gap-3 text-left" onClick={() => onToggle(!enabled)} type="button">
<ShieldCheck className={`size-4 shrink-0 ${enabled ? 'text-indigo-400' : 'text-zinc-600'}`} />
<ShieldCheck className={`size-4 shrink-0 ${enabled ? 'text-[var(--color-text-accent)]' : 'text-[var(--color-text-muted)]'}`} />
<div className="min-w-0 flex-1">
<span className="text-[12px] font-medium text-zinc-200">{label}</span>
<p className="text-[11px] text-zinc-500">{description}</p>
<span className="text-[12px] font-medium text-[var(--color-text-primary)]">{label}</span>
<p className="text-[11px] text-[var(--color-text-muted)]">{description}</p>
</div>
<ToggleSwitch enabled={enabled} />
</button>
{/* Agent scope selector */}
{enabled && agents.length > 1 && (
<div className="mt-3 border-t border-zinc-800/50 pt-3">
<div className="mt-3 border-t border-[var(--color-border-subtle)] pt-3">
<div className="mb-2 flex items-center gap-2">
<span className="text-[11px] font-medium text-zinc-400">Scope</span>
<span className="text-[11px] font-medium text-[var(--color-text-secondary)]">Scope</span>
<button
className={`rounded-full px-2 py-0.5 text-[10px] font-medium transition ${
className={`rounded-full px-2 py-0.5 text-[10px] font-medium transition-all duration-200 ${
isAllAgents
? 'bg-indigo-500/15 text-indigo-300'
: 'bg-zinc-800 text-zinc-500 hover:text-zinc-400'
? 'bg-[var(--color-accent-muted)] text-[var(--color-text-accent)]'
: 'bg-[var(--color-surface-3)] text-[var(--color-text-muted)] hover:text-[var(--color-text-secondary)]'
}`}
onClick={() => onScopeChange(undefined)}
type="button"
@@ -545,10 +544,10 @@ function ApprovalCheckpointRow({
All agents
</button>
<button
className={`rounded-full px-2 py-0.5 text-[10px] font-medium transition ${
className={`rounded-full px-2 py-0.5 text-[10px] font-medium transition-all duration-200 ${
!isAllAgents
? 'bg-indigo-500/15 text-indigo-300'
: 'bg-zinc-800 text-zinc-500 hover:text-zinc-400'
? 'bg-[var(--color-accent-muted)] text-[var(--color-text-accent)]'
: 'bg-[var(--color-surface-3)] text-[var(--color-text-muted)] hover:text-[var(--color-text-secondary)]'
}`}
onClick={() => onScopeChange([])}
type="button"
@@ -563,10 +562,10 @@ function ApprovalCheckpointRow({
const isSelected = scopedAgentIds?.includes(agent.id) ?? false;
return (
<button
className={`rounded-full px-2.5 py-1 text-[11px] font-medium transition ${
className={`rounded-full px-2.5 py-1 text-[11px] font-medium transition-all duration-200 ${
isSelected
? 'bg-indigo-500/20 text-indigo-300 ring-1 ring-indigo-500/30'
: 'bg-zinc-800 text-zinc-500 hover:bg-zinc-700 hover:text-zinc-400'
? 'bg-[var(--color-accent-muted)] text-[var(--color-text-accent)] ring-1 ring-[var(--color-border-glow)]'
: 'bg-[var(--color-surface-3)] text-[var(--color-text-muted)] hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]'
}`}
key={agent.id}
onClick={() => toggleAgentScope(agent.id)}
@@ -583,7 +582,7 @@ function ApprovalCheckpointRow({
{/* Optional additional content (e.g. tool auto-approval list) */}
{enabled && children && (
<div className="mt-3 border-t border-zinc-800/50 pt-3">
<div className="mt-3 border-t border-[var(--color-border-subtle)] pt-3">
{children}
</div>
)}
@@ -620,7 +619,7 @@ function ToolApprovalGroupedList({
{groups.map((group, i) => (
<div key={group.kind}>
{showHeaders && (
<div className={`text-[9px] font-semibold uppercase tracking-wider text-zinc-600 ${i > 0 ? 'mt-3' : ''} mb-1`}>
<div className={`text-[9px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)] ${i > 0 ? 'mt-3' : ''} mb-1`}>
{approvalKindLabels[group.kind]}
</div>
)}
@@ -650,13 +649,13 @@ function ToolApprovalToggleRow({
const detail = tool.description || (tool.providerNames.length > 0 ? tool.providerNames.join(', ') : undefined);
return (
<button
className="flex w-full items-center gap-2.5 rounded-lg px-2 py-1.5 text-left transition hover:bg-zinc-800/60"
className="flex w-full items-center gap-2.5 rounded-lg px-2 py-1.5 text-left transition-all duration-200 hover:bg-[var(--color-surface-3)]/60"
onClick={onToggle}
type="button"
>
<div className="min-w-0 flex-1">
<span className="truncate text-[12px] font-medium text-zinc-300">{tool.label}</span>
{detail && <div className="truncate text-[10px] text-zinc-600">{detail}</div>}
<span className="truncate text-[12px] font-medium text-[var(--color-text-secondary)]">{tool.label}</span>
{detail && <div className="truncate text-[10px] text-[var(--color-text-muted)]">{detail}</div>}
</div>
<ToggleSwitch enabled={enabled} />
</button>
@@ -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="overlay-slide-enter 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-[var(--color-text-secondary)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]"
onClick={onClose}
type="button"
>
<ChevronLeft className="size-4" />
</button>
<h2 className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">
Project Settings
<span className="ml-2 font-normal text-[var(--color-text-muted)]">·</span>
<span className="ml-2 font-normal text-[var(--color-text-secondary)]">{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-[var(--color-text-muted)]">
{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-all duration-200 ${
isActive
? 'bg-[var(--color-surface-3)] font-medium text-[var(--color-text-primary)]'
: 'text-[var(--color-text-secondary)] hover:bg-[var(--color-surface-3)]/50 hover:text-[var(--color-text-secondary)]'
}`}
key={item.id}
onClick={() => {
setActiveSection(item.id);
setConfirmingRemove(false);
}}
type="button"
>
<span className={isActive ? 'text-[var(--color-text-secondary)]' : 'text-[var(--color-text-muted)]'}>{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-[var(--color-border)] 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-all duration-200 ${
activeSection === 'danger-zone'
? 'bg-[var(--color-surface-3)] font-medium text-[var(--color-status-error)]'
: 'text-[var(--color-text-muted)] hover:bg-[var(--color-surface-3)]/50 hover:text-[var(--color-status-error)]'
}`}
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-[var(--color-surface-3)] px-1.5 py-0.5 text-[10px] font-medium text-[var(--color-text-muted)]">
{total !== undefined ? `${count}/${total}` : count}
</span>
);
}
function PendingBadge({ count }: { count: number }) {
return (
<span className="rounded-full bg-[var(--color-status-warning)]/10 px-1.5 py-0.5 text-[10px] font-medium text-[var(--color-status-warning)]">
{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-[var(--color-border)] bg-[var(--color-glass)] px-5 py-4 space-y-3">
<div className="flex items-center gap-3">
<FolderOpen className="size-5 shrink-0 text-[var(--color-text-accent)]" />
<div className="min-w-0">
<div className="text-[13px] font-medium text-[var(--color-text-primary)]">{project.name}</div>
<div className="mt-0.5 truncate text-[12px] text-[var(--color-text-muted)]">{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-[var(--color-text-muted)]">
<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-[var(--color-status-warning)]">
<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-[var(--color-status-error)]">
<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-[var(--color-text-secondary)]">
<GitBranch className="size-3.5 shrink-0" />
<span>{branchLabel}</span>
{git.isDirty && <Circle className="size-1.5 shrink-0 fill-[var(--color-status-warning)] text-[var(--color-status-warning)]" />}
{parts.length > 0 && (
<span className="text-[var(--color-text-muted)]">· {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-[var(--color-text-secondary)]">.github/copilot-instructions.md</code> or <code className="text-[var(--color-text-secondary)]">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-[var(--color-border)] bg-[var(--color-glass)]">
<button
className="flex w-full items-center gap-3 px-5 py-3.5 text-left transition-all duration-200 hover:bg-[var(--color-glass)]"
onClick={() => setExpanded(!expanded)}
type="button"
>
<FileCode2 className="size-4 shrink-0 text-[var(--color-text-accent)]" />
<span className="flex-1 text-[13px] font-medium text-[var(--color-text-primary)]">{instruction.sourcePath}</span>
<ChevronDown
className={`size-3.5 shrink-0 text-[var(--color-text-muted)] transition-transform ${expanded ? 'rotate-180' : ''}`}
/>
</button>
{expanded && (
<div className="border-t border-[var(--color-border)] px-5 py-4">
<pre className="whitespace-pre-wrap text-[11px] leading-relaxed text-[var(--color-text-secondary)]">
{instruction.content}
</pre>
</div>
)}
{!expanded && (
<div className="px-5 pb-3">
<p className={`text-[11px] leading-relaxed text-[var(--color-text-muted)] ${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-[var(--color-text-secondary)]">.agent.md</code> files to <code className="text-[var(--color-text-secondary)]">.github/agents/</code> in your project.
</EmptyState>
) : (
<>
{agents.length > 1 && (
<div className="mb-3 text-[11px] text-[var(--color-text-muted)]">
{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-[var(--color-border)] bg-[var(--color-glass)]'
: 'border-[var(--color-border-subtle)] bg-[var(--color-surface-1)]/20 opacity-60'
}`}>
<div className="flex items-start gap-3">
<Sparkles className={`mt-0.5 size-4 shrink-0 ${agent.enabled ? 'text-[var(--color-status-warning)]' : 'text-[var(--color-text-muted)]'}`} />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="text-[13px] font-medium text-[var(--color-text-primary)]">
{agent.displayName ?? agent.name}
</span>
{agent.tools && agent.tools.length > 0 && (
<span className="rounded-full bg-[var(--color-surface-3)] px-2 py-0.5 text-[10px] font-medium text-[var(--color-text-muted)]">
{agent.tools.length} tool{agent.tools.length === 1 ? '' : 's'}
</span>
)}
</div>
{agent.description && (
<p className="mt-1 text-[12px] leading-relaxed text-[var(--color-text-muted)]">{agent.description}</p>
)}
<p className="mt-1 text-[11px] text-[var(--color-text-muted)]">{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-[var(--color-text-secondary)]">.prompt.md</code> files to <code className="text-[var(--color-text-secondary)]">.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-[var(--color-border)] bg-[var(--color-glass)] px-5 py-4">
<div className="flex items-start gap-3">
<FileText className="mt-0.5 size-4 shrink-0 text-[var(--color-status-success)]" />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="text-[13px] font-medium text-[var(--color-text-primary)]">{prompt.name}</span>
{prompt.variables.length > 0 && (
<span className="rounded-full bg-[var(--color-surface-3)] px-2 py-0.5 text-[10px] font-medium text-[var(--color-text-muted)]">
{prompt.variables.length} variable{prompt.variables.length === 1 ? '' : 's'}
</span>
)}
</div>
{prompt.description && (
<p className="mt-1 text-[12px] leading-relaxed text-[var(--color-text-muted)]">{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-[var(--color-surface-3)] px-2 py-0.5 text-[10px] font-medium text-[var(--color-text-secondary)]"
title={v.placeholder}
>
{v.name}
</span>
))}
</div>
)}
<p className="mt-1.5 text-[11px] text-[var(--color-text-muted)]">{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-[var(--color-status-success)]/10 px-3 py-1.5 text-[12px] font-medium text-[var(--color-status-success)] transition-all duration-200 hover:bg-[var(--color-status-success)]/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-[var(--color-text-muted)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]"
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-[var(--color-status-success)]/10 text-[var(--color-status-success)]'
: 'bg-[var(--color-status-warning)]/10 text-[var(--color-status-warning)]';
return (
<div className="flex items-center gap-3 rounded-xl border border-transparent px-4 py-3 hover:border-[var(--color-border)] hover:bg-[var(--color-surface-1)]">
<Server className="size-4 shrink-0 text-[var(--color-text-muted)]" />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate text-[13px] font-medium text-[var(--color-text-primary)]">{server.name}</span>
<span className="rounded-full bg-[var(--color-surface-3)] px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-[var(--color-text-secondary)]">
{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-[var(--color-text-muted)]">
{detail}
<span className="ml-2 text-[var(--color-text-muted)]">· {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-[var(--color-status-success)] transition-all duration-200 hover:bg-[var(--color-status-success)]/10"
onClick={onAccept}
type="button"
>
Accept
</button>
)}
{onDismiss && (
<button
className="rounded-lg px-2.5 py-1 text-[12px] font-medium text-[var(--color-text-muted)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]"
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-[var(--color-status-error)]/20 bg-[var(--color-status-error)]/5 px-5 py-5">
<h4 className="text-[13px] font-semibold text-[var(--color-text-primary)]">Remove project</h4>
<p className="mt-1 text-[12px] text-[var(--color-text-muted)]">
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-all duration-200 ${
confirmingRemove
? 'bg-[var(--color-status-error)] text-white hover:bg-[var(--color-status-error)]'
: 'bg-[var(--color-status-error)]/10 text-[var(--color-status-error)] hover:bg-[var(--color-status-error)]/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-[var(--color-text-secondary)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]"
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="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">{title}</h3>
<p className="mt-0.5 text-[12px] text-[var(--color-text-muted)]">{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-[var(--color-surface-3)] px-3 py-1.5 text-[13px] font-medium text-[var(--color-text-primary)] transition-all duration-200 hover:bg-[var(--color-surface-3)]"
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-[var(--color-border)] bg-[var(--color-surface-1)]/20 px-5 py-8 text-center text-[12px] leading-relaxed text-[var(--color-text-muted)]">
{children}
</div>
);
}
+3 -3
View File
@@ -51,9 +51,9 @@ const iconComponents: Record<ModelProvider, React.FC<{ className?: string }>> =
};
export const providerColors: Record<ModelProvider, string> = {
openai: 'text-emerald-400',
anthropic: 'text-orange-400',
google: 'text-blue-400',
openai: 'text-[var(--color-status-success)]',
anthropic: 'text-[var(--color-accent-purple)]',
google: 'text-[var(--color-status-info)]',
};
export function ProviderIcon({ provider, className }: ProviderIconProps) {
+94 -84
View File
@@ -26,25 +26,26 @@ import {
} from '@renderer/lib/runTimelineFormatting';
import type { OrchestrationMode } from '@shared/domain/pattern';
import type { RunTimelineEventRecord, SessionRunRecord } from '@shared/domain/runTimeline';
import { FileChangePreview } from '@renderer/components/chat/FileChangePreview';
/* ── Mode accent colours (shared with ActivityPanel) ───────── */
const modeAccent: Record<OrchestrationMode, { dot: string; ring: string; text: string }> = {
single: { dot: 'bg-indigo-400', ring: 'ring-indigo-500/30', text: 'text-indigo-400' },
sequential: { dot: 'bg-amber-400', ring: 'ring-amber-500/30', text: 'text-amber-400' },
concurrent: { dot: 'bg-emerald-400', ring: 'ring-emerald-500/30', text: 'text-emerald-400' },
handoff: { dot: 'bg-sky-400', ring: 'ring-sky-500/30', text: 'text-sky-400' },
'group-chat': { dot: 'bg-violet-400', ring: 'ring-violet-500/30', text: 'text-violet-400' },
magentic: { dot: 'bg-zinc-500', ring: 'ring-zinc-600/30', text: 'text-zinc-500' },
single: { dot: 'bg-[#245CF9]', ring: 'ring-[#245CF9]/30', text: 'text-[#245CF9]' },
sequential: { dot: 'bg-[var(--color-status-warning)]', ring: 'ring-[var(--color-status-warning)]/30', text: 'text-[var(--color-status-warning)]' },
concurrent: { dot: 'bg-[var(--color-status-success)]', ring: 'ring-[var(--color-status-success)]/30', text: 'text-[var(--color-status-success)]' },
handoff: { dot: 'bg-[var(--color-accent-sky)]', ring: 'ring-[var(--color-accent-sky)]/30', text: 'text-[var(--color-accent-sky)]' },
'group-chat': { dot: 'bg-[var(--color-accent-purple)]', ring: 'ring-[var(--color-accent-purple)]/30', text: 'text-[var(--color-accent-purple)]' },
magentic: { dot: 'bg-[var(--color-text-muted)]', ring: 'ring-[var(--color-text-muted)]/30', text: 'text-[var(--color-text-muted)]' },
};
/* ── Status badges ─────────────────────────────────────────── */
const runStatusStyles: Record<SessionRunRecord['status'], { icon: ReactNode; className: string }> = {
running: { icon: <CircleDot className="size-3" />, className: 'text-blue-400' },
completed: { icon: <CheckCircle2 className="size-3" />, className: 'text-emerald-400' },
cancelled: { icon: <XCircle className="size-3" />, className: 'text-zinc-400' },
error: { icon: <XCircle className="size-3" />, className: 'text-red-400' },
running: { icon: <CircleDot className="size-3" />, className: 'text-[var(--color-status-info)]' },
completed: { icon: <CheckCircle2 className="size-3" />, className: 'text-[var(--color-status-success)]' },
cancelled: { icon: <XCircle className="size-3" />, className: 'text-[var(--color-text-muted)]' },
error: { icon: <XCircle className="size-3" />, className: 'text-[var(--color-status-error)]' },
};
/* ── Event node icon ───────────────────────────────────────── */
@@ -53,23 +54,23 @@ function EventIcon({ kind, status }: { kind: RunTimelineEventRecord['kind']; sta
const base = 'size-3.5';
switch (kind) {
case 'run-started':
return <Play className={`${base} text-zinc-500`} />;
return <Play className={`${base} text-[var(--color-text-muted)]`} />;
case 'thinking':
return <Brain className={`${base} ${status === 'running' ? 'text-sky-400 animate-pulse' : 'text-zinc-500'}`} />;
return <Brain className={`${base} ${status === 'running' ? 'text-[var(--color-accent-sky)] animate-pulse' : 'text-[var(--color-text-muted)]'}`} />;
case 'handoff':
return <ArrowRight className={`${base} text-amber-400`} />;
return <ArrowRight className={`${base} text-[var(--color-status-warning)]`} />;
case 'tool-call':
return <Wrench className={`${base} text-violet-400`} />;
return <Wrench className={`${base} text-[var(--color-accent-purple)]`} />;
case 'approval':
return <AlertTriangle className={`${base} ${status === 'running' ? 'text-amber-400 animate-pulse' : status === 'error' ? 'text-red-400' : 'text-emerald-400'}`} />;
return <AlertTriangle className={`${base} ${status === 'running' ? 'text-[var(--color-status-warning)] animate-pulse' : status === 'error' ? 'text-[var(--color-status-error)]' : 'text-[var(--color-status-success)]'}`} />;
case 'message':
return <MessageSquare className={`${base} ${status === 'running' ? 'text-blue-400 animate-pulse' : status === 'error' ? 'text-red-400' : 'text-emerald-400'}`} />;
return <MessageSquare className={`${base} ${status === 'running' ? 'text-[var(--color-status-info)] animate-pulse' : status === 'error' ? 'text-[var(--color-status-error)]' : 'text-[var(--color-status-success)]'}`} />;
case 'run-completed':
return <CheckCircle2 className={`${base} text-emerald-400`} />;
return <CheckCircle2 className={`${base} text-[var(--color-status-success)]`} />;
case 'run-cancelled':
return <XCircle className={`${base} text-zinc-400`} />;
return <XCircle className={`${base} text-[var(--color-text-muted)]`} />;
case 'run-failed':
return <AlertTriangle className={`${base} text-red-400`} />;
return <AlertTriangle className={`${base} text-[var(--color-status-error)]`} />;
}
}
@@ -91,67 +92,76 @@ function TimelineEventRow({
const terminal = isTerminalEvent(event.kind);
return (
<button
className={`group relative flex w-full gap-2.5 text-left ${terminal ? 'py-1' : 'py-1.5'} ${isClickable ? 'cursor-pointer' : 'cursor-default'}`}
disabled={!isClickable}
onClick={isClickable ? () => onJumpToMessage(event.messageId!) : undefined}
type="button"
>
<div className="relative">
{/* Vertical connector line */}
{!isLast && (
<div className="absolute left-[7px] top-[22px] bottom-0 w-px bg-zinc-800" />
<div className="absolute left-[7px] top-[22px] bottom-0 w-px bg-[var(--color-border)]" />
)}
{/* Node */}
<div className="relative z-10 flex shrink-0 items-start pt-0.5">
<div className="flex size-[15px] items-center justify-center rounded-full bg-[var(--color-surface-1)]">
<EventIcon kind={event.kind} status={event.status} />
<button
className={`group flex w-full gap-2.5 text-left transition-all duration-200 ${terminal ? 'py-1' : 'py-1.5'} ${isClickable ? 'cursor-pointer' : 'cursor-default'}`}
disabled={!isClickable}
onClick={isClickable ? () => onJumpToMessage(event.messageId!) : undefined}
type="button"
>
{/* Node */}
<div className="relative z-10 flex shrink-0 items-start pt-0.5">
<div className={`flex size-[15px] items-center justify-center rounded-full ${event.status === 'running' ? 'brand-gradient-bg' : 'bg-[var(--color-surface-2)]'}`}>
<EventIcon kind={event.kind} status={event.status} />
</div>
</div>
</div>
{/* Content */}
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<span className={`text-[11px] font-medium ${terminal ? 'text-zinc-600' : 'text-zinc-300'} ${isClickable ? 'group-hover:text-indigo-300' : ''}`}>
{label}
</span>
{/* Approval kind badge */}
{event.kind === 'approval' && event.approvalKind && (
<span className={`rounded-full px-1.5 py-0.5 text-[8px] font-semibold uppercase tracking-wider ${
event.status === 'running'
? 'bg-amber-500/15 text-amber-400'
: event.status === 'completed'
? 'bg-emerald-500/15 text-emerald-400'
: 'bg-red-500/15 text-red-400'
}`}>
{event.approvalKind === 'final-response' ? 'response' : 'tool'}
{/* Content */}
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<span className={`text-[11px] font-medium ${terminal ? 'text-[var(--color-text-muted)]' : 'text-[var(--color-text-secondary)]'} ${isClickable ? 'group-hover:text-[var(--color-text-accent)]' : ''}`}>
{label}
</span>
{/* Approval kind badge */}
{event.kind === 'approval' && event.approvalKind && (
<span className={`rounded-full px-1.5 py-0.5 text-[8px] font-semibold uppercase tracking-wider ${
event.status === 'running'
? 'bg-[var(--color-status-warning)]/15 text-[var(--color-status-warning)]'
: event.status === 'completed'
? 'bg-[var(--color-status-success)]/15 text-[var(--color-status-success)]'
: 'bg-[var(--color-status-error)]/15 text-[var(--color-status-error)]'
}`}>
{event.approvalKind === 'final-response' ? 'response' : 'tool'}
</span>
)}
<span className="font-mono ml-auto shrink-0 text-[9px] tabular-nums text-[var(--color-text-muted)]">{timestamp}</span>
</div>
{/* Content preview for message events */}
{preview && (
<p className={`mt-0.5 text-[10px] leading-snug text-[var(--color-text-muted)] ${isClickable ? 'group-hover:text-[var(--color-text-secondary)]' : ''}`}>
{preview}
</p>
)}
{/* Approval detail */}
{event.kind === 'approval' && event.approvalDetail && (
<p className="mt-0.5 text-[10px] leading-snug text-[var(--color-text-muted)]">
{truncateContent(event.approvalDetail, 120)}
</p>
)}
{/* Error detail */}
{event.error && (
<p className="mt-0.5 text-[10px] leading-snug text-[var(--color-status-error)]/80">
{truncateContent(event.error, 120)}
</p>
)}
<span className="ml-auto shrink-0 text-[9px] tabular-nums text-zinc-700">{timestamp}</span>
</div>
</button>
{/* Content preview for message events */}
{preview && (
<p className={`mt-0.5 text-[10px] leading-snug text-zinc-600 ${isClickable ? 'group-hover:text-zinc-500' : ''}`}>
{preview}
</p>
)}
{/* Approval detail */}
{event.kind === 'approval' && event.approvalDetail && (
<p className="mt-0.5 text-[10px] leading-snug text-zinc-500">
{truncateContent(event.approvalDetail, 120)}
</p>
)}
{/* Error detail */}
{event.error && (
<p className="mt-0.5 text-[10px] leading-snug text-red-500/80">
{truncateContent(event.error, 120)}
</p>
)}
</div>
</button>
{/* File change preview for tool-call events */}
{event.kind === 'tool-call' && event.fileChanges && event.fileChanges.length > 0 && (
<div className="relative z-10 ml-[25px] pb-1">
<FileChangePreview fileChanges={event.fileChanges} />
</div>
)}
</div>
);
}
@@ -169,15 +179,15 @@ function ThinkingGroupRow({
return (
<div className="group relative flex w-full gap-2.5 py-1">
{!isLast && (
<div className="absolute left-[7px] top-[22px] bottom-0 w-px bg-zinc-800" />
<div className="absolute left-[7px] top-[22px] bottom-0 w-px bg-[var(--color-border)]" />
)}
<div className="relative z-10 flex shrink-0 items-start pt-0.5">
<div className="flex size-[15px] items-center justify-center rounded-full bg-[var(--color-surface-1)]">
<Brain className="size-3.5 text-zinc-500" />
<div className="flex size-[15px] items-center justify-center rounded-full bg-[var(--color-surface-2)]">
<Brain className="size-3.5 text-[var(--color-text-muted)]" />
</div>
</div>
<div className="min-w-0 flex-1">
<span className="text-[11px] text-zinc-600">
<span className="text-[11px] text-[var(--color-text-muted)]">
{agentName ? `${agentName} thinking` : 'Thinking'} ×{events.length}
</span>
</div>
@@ -225,26 +235,26 @@ function RunCard({
);
return (
<div className="rounded-lg border border-zinc-800 bg-zinc-900/40">
<div className="glass-surface rounded-lg">
{/* Run header */}
<button
className="flex w-full items-center gap-2 px-3 py-2 text-left transition hover:bg-zinc-800/30"
className="flex w-full items-center gap-2 px-3 py-2 text-left transition-all duration-200 hover:bg-[var(--color-surface-3)]"
onClick={onToggle}
type="button"
>
{expanded
? <ChevronDown className="size-3 shrink-0 text-zinc-600" />
: <ChevronRight className="size-3 shrink-0 text-zinc-600" />}
? <ChevronDown className="size-3 shrink-0 text-[var(--color-text-muted)]" />
: <ChevronRight className="size-3 shrink-0 text-[var(--color-text-muted)]" />}
<Bot className={`size-3 shrink-0 ${accent.text}`} />
<span className="min-w-0 flex-1 truncate text-[11px] font-medium text-zinc-300">
<span className="min-w-0 flex-1 truncate text-[11px] font-medium text-[var(--color-text-secondary)]">
{run.patternName}
</span>
{/* Status */}
<span className={`flex items-center gap-1 shrink-0 ${statusStyle.className}`}>
{run.status === 'running' && <span className="size-1.5 animate-pulse rounded-full bg-blue-400" />}
{run.status === 'running' && <span className="size-1.5 animate-pulse rounded-full bg-[var(--color-status-info)]" />}
{run.status !== 'running' && statusStyle.icon}
<span className="text-[9px] font-medium">{formatRunStatusLabel(run.status)}</span>
</span>
@@ -252,13 +262,13 @@ function RunCard({
{/* Expanded timeline */}
{expanded && (
<div className="border-t border-zinc-800/60 px-3 pb-2 pt-1.5">
<div className="border-t border-[var(--color-border-subtle)] px-3 pb-2 pt-1.5">
{/* Agent badges */}
{run.agents.length > 1 && (
<div className="mb-2 flex flex-wrap gap-1">
{run.agents.map((agent) => (
<span
className="rounded-full bg-zinc-800/80 px-2 py-0.5 text-[9px] font-medium text-zinc-500"
className="rounded-full bg-[var(--color-surface-2)] px-2 py-0.5 text-[9px] font-medium text-[var(--color-text-muted)]"
key={agent.agentId}
>
{agent.agentName}
@@ -281,7 +291,7 @@ function RunCard({
{/* Duration footer */}
{duration && (
<div className="mt-1 border-t border-zinc-800/40 pt-1.5 text-[9px] tabular-nums text-zinc-700">
<div className="font-mono mt-1 border-t border-[var(--color-border-subtle)] pt-1.5 text-[9px] tabular-nums text-[var(--color-text-muted)]">
Duration: {duration}
</div>
)}
@@ -295,7 +305,7 @@ function RunCard({
function EmptyTimeline() {
return (
<p className="py-4 text-center text-[11px] text-zinc-600">
<p className="py-4 text-center text-[11px] text-[var(--color-text-muted)]">
Send a message to see the run timeline
</p>
);
@@ -0,0 +1,259 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Search, MessageSquare, ArrowRight } from 'lucide-react';
import type { WorkspaceState } from '@shared/domain/workspace';
import type { ChatMessageRecord, SessionRecord } from '@shared/domain/session';
import { isScratchpadProject } from '@shared/domain/project';
export interface SessionSearchPanelProps {
workspace: WorkspaceState;
onClose: () => void;
onSelectSession: (sessionId: string) => void;
}
interface SearchHit {
session: SessionRecord;
projectName: string;
message: ChatMessageRecord;
/** The matching substring context around the first token hit. */
snippet: string;
/** Character offset of the match within the snippet for highlighting. */
matchStart: number;
matchLength: number;
}
function extractSnippet(content: string, query: string): { snippet: string; matchStart: number; matchLength: number } | undefined {
const lower = content.toLowerCase();
const qLower = query.toLowerCase().trim();
if (!qLower) return undefined;
// Find first occurrence of query in content
const idx = lower.indexOf(qLower);
if (idx === -1) {
// Try individual tokens
const tokens = qLower.split(/\s+/).filter(Boolean);
for (const token of tokens) {
const tidx = lower.indexOf(token);
if (tidx !== -1) {
const start = Math.max(0, tidx - 40);
const end = Math.min(content.length, tidx + token.length + 80);
const snippet = (start > 0 ? '…' : '') + content.slice(start, end).replace(/\n/g, ' ') + (end < content.length ? '…' : '');
const adjustedStart = (start > 0 ? 1 : 0) + (tidx - start);
return { snippet, matchStart: adjustedStart, matchLength: token.length };
}
}
return undefined;
}
const start = Math.max(0, idx - 40);
const end = Math.min(content.length, idx + qLower.length + 80);
const snippet = (start > 0 ? '…' : '') + content.slice(start, end).replace(/\n/g, ' ') + (end < content.length ? '…' : '');
const adjustedStart = (start > 0 ? 1 : 0) + (idx - start);
return { snippet, matchStart: adjustedStart, matchLength: qLower.length };
}
export function SessionSearchPanel({ workspace, onClose, onSelectSession }: SessionSearchPanelProps) {
const [query, setQuery] = useState('');
const [selectedIndex, setSelectedIndex] = useState(0);
const inputRef = useRef<HTMLInputElement>(null);
const listRef = useRef<HTMLDivElement>(null);
useEffect(() => { inputRef.current?.focus(); }, []);
// Escape to close in capture phase
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
e.preventDefault();
e.stopImmediatePropagation();
onClose();
}
};
document.addEventListener('keydown', handleEscape, true);
return () => document.removeEventListener('keydown', handleEscape, true);
}, [onClose]);
// Build project name lookup
const projectNames = useMemo(() => {
const map = new Map<string, string>();
for (const p of workspace.projects) {
map.set(p.id, isScratchpadProject(p) ? 'Scratchpad' : p.name);
}
return map;
}, [workspace.projects]);
// Search across all sessions and messages
const hits = useMemo<SearchHit[]>(() => {
const q = query.trim();
if (!q) return [];
const results: SearchHit[] = [];
const activeSessions = workspace.sessions.filter((s) => !s.isArchived);
for (const session of activeSessions) {
for (const message of session.messages) {
if (!message.content) continue;
const extracted = extractSnippet(message.content, q);
if (extracted) {
results.push({
session,
projectName: projectNames.get(session.projectId) ?? 'Unknown',
message,
...extracted,
});
}
}
}
// Limit results for performance and sort by session recency
return results.slice(0, 50);
}, [query, workspace.sessions, projectNames]);
useEffect(() => { setSelectedIndex(0); }, [query]);
const handleSelect = useCallback((hit: SearchHit) => {
onClose();
onSelectSession(hit.session.id);
// After navigation, scroll to the matching message
requestAnimationFrame(() => {
setTimeout(() => {
const el = document.querySelector(`[data-message-id="${CSS.escape(hit.message.id)}"]`);
if (el) {
el.scrollIntoView({ behavior: 'smooth', block: 'center' });
el.classList.add('ring-1', 'ring-[var(--color-accent)]/40', 'rounded-lg');
setTimeout(() => el.classList.remove('ring-1', 'ring-[var(--color-accent)]/40', 'rounded-lg'), 2000);
}
}, 100);
});
}, [onClose, onSelectSession]);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (e.key === 'ArrowDown') {
e.preventDefault();
if (hits.length > 0) setSelectedIndex((i) => Math.min(i + 1, hits.length - 1));
} else if (e.key === 'ArrowUp') {
e.preventDefault();
setSelectedIndex((i) => Math.max(i - 1, 0));
} else if (e.key === 'Enter') {
e.preventDefault();
const hit = hits[selectedIndex];
if (hit) handleSelect(hit);
}
},
[hits, selectedIndex, handleSelect],
);
useEffect(() => {
const item = listRef.current?.querySelector(`[data-search-index="${selectedIndex}"]`);
item?.scrollIntoView({ block: 'nearest' });
}, [selectedIndex]);
return (
<div
className="palette-backdrop-enter fixed inset-0 z-[60] flex justify-center bg-[#07080e]/80 pt-[15vh] backdrop-blur-sm"
onClick={onClose}
role="dialog"
aria-modal="true"
aria-label="Search sessions"
>
<div
className="palette-enter glow-border flex h-fit max-h-[min(520px,65vh)] w-full max-w-2xl flex-col overflow-hidden rounded-xl bg-[var(--color-surface-1)] shadow-[0_16px_64px_rgba(0,0,0,0.5)]"
onClick={(e) => e.stopPropagation()}
onKeyDown={handleKeyDown}
>
{/* Search input */}
<div className="flex items-center gap-3 border-b border-[var(--color-border)] px-4">
<Search className="size-4 shrink-0 text-[var(--color-text-muted)]" />
<input
ref={inputRef}
type="text"
className="flex-1 bg-transparent py-3.5 text-[14px] text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-muted)]"
placeholder="Search across all sessions…"
value={query}
onChange={(e) => setQuery(e.target.value)}
aria-label="Search session content"
autoComplete="off"
spellCheck={false}
/>
{query && (
<span className="shrink-0 text-[11px] text-[var(--color-text-muted)]">
{hits.length} result{hits.length !== 1 ? 's' : ''}
</span>
)}
</div>
{/* Results */}
<div ref={listRef} className="flex-1 overflow-y-auto py-1.5" role="listbox">
{query && hits.length === 0 ? (
<div className="px-4 py-10 text-center text-[13px] text-[var(--color-text-muted)]">
No matches found
</div>
) : !query ? (
<div className="px-4 py-10 text-center text-[13px] text-[var(--color-text-muted)]">
Type to search across all session messages
</div>
) : (
hits.map((hit, index) => {
const isSelected = index === selectedIndex;
return (
<button
key={`${hit.session.id}-${hit.message.id}`}
data-search-index={index}
className={`flex w-full flex-col gap-1 px-4 py-2.5 text-left transition-colors ${
isSelected
? 'bg-[var(--color-accent-muted)] text-[var(--color-text-primary)]'
: 'text-[var(--color-text-secondary)] hover:bg-[var(--color-glass-hover)] hover:text-[var(--color-text-primary)]'
}`}
onClick={() => handleSelect(hit)}
onMouseEnter={() => setSelectedIndex(index)}
role="option"
aria-selected={isSelected}
type="button"
>
{/* Session title row */}
<div className="flex items-center gap-2">
<MessageSquare className={`size-3.5 shrink-0 ${isSelected ? 'text-[var(--color-text-accent)]' : 'text-[var(--color-text-muted)]'}`} />
<span className="truncate text-[12px] font-medium">{hit.session.title}</span>
<span className="text-[10px] text-[var(--color-text-muted)]">·</span>
<span className="truncate text-[10px] text-[var(--color-text-muted)]">{hit.projectName}</span>
<ArrowRight className="ml-auto size-3 shrink-0 text-[var(--color-text-muted)]" />
</div>
{/* Message snippet with highlighted match */}
<div className="pl-5.5 text-[12px] leading-relaxed text-[var(--color-text-muted)]">
<span className="line-clamp-2">
{hit.snippet.slice(0, hit.matchStart)}
<mark className="rounded-sm bg-[var(--color-accent)]/20 px-0.5 text-[var(--color-text-accent)]">
{hit.snippet.slice(hit.matchStart, hit.matchStart + hit.matchLength)}
</mark>
{hit.snippet.slice(hit.matchStart + hit.matchLength)}
</span>
</div>
<div className="pl-5.5 text-[10px] text-[var(--color-text-muted)]">
{hit.message.role === 'user' ? 'You' : hit.message.authorName}
</div>
</button>
);
})
)}
</div>
{/* Footer hints */}
<div className="flex items-center gap-4 border-t border-[var(--color-border)] px-4 py-2 text-[11px] text-[var(--color-text-muted)]">
<span className="flex items-center gap-1">
<kbd className="rounded border border-[var(--color-border-subtle)] px-1 font-mono text-[10px]"></kbd>
navigate
</span>
<span className="flex items-center gap-1">
<kbd className="rounded border border-[var(--color-border-subtle)] px-1 font-mono text-[10px]"></kbd>
jump to message
</span>
<span className="flex items-center gap-1">
<kbd className="rounded border border-[var(--color-border-subtle)] px-1 font-mono text-[10px]">esc</kbd>
close
</span>
</div>
</div>
</div>
);
}
+153 -123
View File
@@ -1,12 +1,13 @@
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 { ToggleSwitch } from '@renderer/components/ui';
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 +27,6 @@ interface SettingsPanelProps {
theme: AppearanceTheme;
toolingSettings: WorkspaceToolingSettings;
discoveredUserTooling: DiscoveredToolingState;
discoveredProjectTooling?: ProjectDiscoveredTooling;
selectedProjectName?: string;
isRefreshingCapabilities: boolean;
onRefreshCapabilities: () => void;
onClose: () => void;
@@ -41,11 +40,14 @@ interface SettingsPanelProps {
onDeleteLspProfile: (profileId: string) => Promise<void>;
onNewLspProfile: () => LspProfileDefinition;
onSetTheme: (theme: AppearanceTheme) => void;
notificationsEnabled: boolean;
onSetNotificationsEnabled: (enabled: boolean) => void;
minimizeToTray: boolean;
onSetMinimizeToTray: (enabled: boolean) => 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';
@@ -96,8 +98,8 @@ const navGroups: NavGroup[] = [
];
function modeBadgeClasses(pattern: PatternDefinition) {
if (pattern.availability === 'unavailable') return 'bg-amber-500/10 text-amber-400';
return 'bg-zinc-800 text-zinc-400';
if (pattern.availability === 'unavailable') return 'bg-[var(--color-status-warning)]/10 text-[var(--color-status-warning)]';
return 'bg-[var(--color-surface-3)] text-[var(--color-text-secondary)]';
}
export function SettingsPanel({
@@ -107,8 +109,6 @@ export function SettingsPanel({
theme,
toolingSettings,
discoveredUserTooling,
discoveredProjectTooling,
selectedProjectName,
isRefreshingCapabilities,
onRefreshCapabilities,
onClose,
@@ -122,11 +122,14 @@ export function SettingsPanel({
onDeleteLspProfile,
onNewLspProfile,
onSetTheme,
notificationsEnabled,
onSetNotificationsEnabled,
minimizeToTray,
onSetMinimizeToTray,
onOpenAppDataFolder,
onResetLocalWorkspace,
onRescanProjectConfigs,
onResolveUserDiscoveredTooling,
onResolveProjectDiscoveredTooling,
onGetQuota,
}: SettingsPanelProps) {
const [activeSection, setActiveSection] = useState<SettingsSection>('appearance');
const [editingPattern, setEditingPattern] = useState<PatternDefinition | null>(null);
@@ -213,16 +216,16 @@ export function SettingsPanel({
}
return (
<div className="fixed inset-0 z-50 flex flex-col bg-[var(--color-surface-0)]">
<div className="overlay-slide-enter fixed inset-0 z-50 flex flex-col bg-[var(--color-surface-0)]">
<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"
className="no-drag flex size-8 items-center justify-center rounded-lg text-[var(--color-text-secondary)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]"
onClick={onClose}
type="button"
>
<ChevronLeft className="size-4" />
</button>
<h2 className="text-[13px] font-semibold text-zinc-100">Settings</h2>
<h2 className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">Settings</h2>
</div>
<div className="flex min-h-0 flex-1">
@@ -230,7 +233,7 @@ export function SettingsPanel({
<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">
<span className="mb-1 block px-3 text-[10px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
{group.label}
</span>
<div className="space-y-0.5">
@@ -238,16 +241,16 @@ export function SettingsPanel({
const isActive = item.id === activeSection;
return (
<button
className={`flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-left text-[13px] transition ${
className={`flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-left text-[13px] transition-all duration-200 ${
isActive
? 'bg-zinc-800 font-medium text-zinc-100'
: 'text-zinc-400 hover:bg-zinc-800/50 hover:text-zinc-300'
? 'bg-[var(--color-surface-3)] font-medium text-[var(--color-text-primary)]'
: 'text-[var(--color-text-secondary)] hover:bg-[var(--color-surface-3)]/50 hover:text-[var(--color-text-secondary)]'
}`}
key={item.id}
onClick={() => setActiveSection(item.id)}
type="button"
>
<span className={isActive ? 'text-zinc-300' : 'text-zinc-500'}>{item.icon}</span>
<span className={isActive ? 'text-[var(--color-text-secondary)]' : 'text-[var(--color-text-muted)]'}>{item.icon}</span>
{item.label}
</button>
);
@@ -261,7 +264,14 @@ export function SettingsPanel({
<div className="flex-1 overflow-y-auto">
<div className="mx-auto max-w-2xl px-8 py-6">
{activeSection === 'appearance' && (
<AppearanceSection theme={theme} onSetTheme={onSetTheme} />
<AppearanceSection
theme={theme}
onSetTheme={onSetTheme}
notificationsEnabled={notificationsEnabled}
onSetNotificationsEnabled={onSetNotificationsEnabled}
minimizeToTray={minimizeToTray}
onSetMinimizeToTray={onSetMinimizeToTray}
/>
)}
{activeSection === 'connection' && (
<ConnectionSection
@@ -269,6 +279,7 @@ export function SettingsPanel({
isRefreshing={isRefreshingCapabilities}
modelCount={sidecarCapabilities?.models.length ?? 0}
onRefresh={onRefreshCapabilities}
onGetQuota={onGetQuota}
/>
)}
{activeSection === 'patterns' && (
@@ -287,12 +298,8 @@ export function SettingsPanel({
)}
{activeSection === 'mcp-servers' && (
<DiscoveredMcpSection
discoveredProjectTooling={discoveredProjectTooling}
discoveredUserTooling={discoveredUserTooling}
onRescanProjectConfigs={onRescanProjectConfigs}
onResolveProjectDiscoveredTooling={onResolveProjectDiscoveredTooling}
onResolveUserDiscoveredTooling={onResolveUserDiscoveredTooling}
selectedProjectName={selectedProjectName}
/>
)}
{activeSection === 'lsp-profiles' && (
@@ -324,15 +331,23 @@ const themeOptions: { value: AppearanceTheme; label: string; description: string
function AppearanceSection({
theme,
onSetTheme,
notificationsEnabled,
onSetNotificationsEnabled,
minimizeToTray,
onSetMinimizeToTray,
}: {
theme: AppearanceTheme;
onSetTheme: (theme: AppearanceTheme) => void;
}) {
notificationsEnabled: boolean;
onSetNotificationsEnabled: (enabled: boolean) => void;
minimizeToTray: boolean;
onSetMinimizeToTray: (enabled: boolean) => void;
}){
return (
<div>
<div className="mb-1">
<h3 className="text-[13px] font-semibold text-zinc-200">Appearance</h3>
<p className="mt-0.5 text-[12px] text-zinc-500">
<h3 className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">Appearance</h3>
<p className="mt-0.5 text-[12px] text-[var(--color-text-muted)]">
Choose how Aryx looks on your device
</p>
</div>
@@ -342,32 +357,80 @@ function AppearanceSection({
const isSelected = option.value === theme;
return (
<button
className={`flex w-full items-center gap-3 rounded-lg border px-4 py-3 text-left transition ${
className={`flex w-full items-center gap-3 rounded-lg border px-4 py-3 text-left transition-all duration-200 ${
isSelected
? 'border-indigo-500/50 bg-indigo-500/10'
: 'border-[var(--color-border)] hover:border-zinc-600 hover:bg-zinc-800/40'
? 'border-[var(--color-border-glow)] bg-[var(--color-accent-muted)]'
: 'border-[var(--color-border)] hover:border-[var(--color-border)] hover:bg-[var(--color-surface-3)]/40'
}`}
key={option.value}
onClick={() => onSetTheme(option.value)}
type="button"
>
<div
className={`flex size-4 shrink-0 items-center justify-center rounded-full border-2 transition ${
isSelected ? 'border-indigo-500' : 'border-zinc-600'
className={`flex size-4 shrink-0 items-center justify-center rounded-full border-2 transition-all duration-200 ${
isSelected ? 'border-[var(--color-accent)]' : 'border-[var(--color-border)]'
}`}
>
{isSelected && <div className="size-2 rounded-full bg-indigo-500" />}
{isSelected && <div className="size-2 rounded-full bg-[var(--color-accent)]" />}
</div>
<div>
<span className={`text-[13px] font-medium ${isSelected ? 'text-zinc-100' : 'text-zinc-300'}`}>
<span className={`text-[13px] font-medium ${isSelected ? 'text-[var(--color-text-primary)]' : 'text-[var(--color-text-secondary)]'}`}>
{option.label}
</span>
<p className="text-[12px] text-zinc-500">{option.description}</p>
<p className="text-[12px] text-[var(--color-text-muted)]">{option.description}</p>
</div>
</button>
);
})}
</div>
{/* Notifications */}
<div className="mt-8 mb-1">
<h3 className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">Notifications</h3>
<p className="mt-0.5 text-[12px] text-[var(--color-text-muted)]">
Control when Aryx sends desktop notifications
</p>
</div>
<button
className="mt-4 flex w-full items-center justify-between rounded-lg border border-[var(--color-border)] px-4 py-3 text-left transition hover:bg-[var(--color-surface-3)]/40"
onClick={() => onSetNotificationsEnabled(!notificationsEnabled)}
type="button"
>
<div>
<span className="text-[13px] font-medium text-[var(--color-text-primary)]">
Run completion alerts
</span>
<p className="text-[12px] text-[var(--color-text-muted)]">
Notify when a session run completes, fails, or needs approval while the app is unfocused
</p>
</div>
<ToggleSwitch enabled={notificationsEnabled} />
</button>
{/* System Tray */}
<div className="mt-8 mb-1">
<h3 className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">System Tray</h3>
<p className="mt-0.5 text-[12px] text-[var(--color-text-muted)]">
Control how Aryx behaves when you close the window
</p>
</div>
<button
className="mt-4 flex w-full items-center justify-between rounded-lg border border-[var(--color-border)] px-4 py-3 text-left transition hover:bg-[var(--color-surface-3)]/40"
onClick={() => onSetMinimizeToTray(!minimizeToTray)}
type="button"
>
<div>
<span className="text-[13px] font-medium text-[var(--color-text-primary)]">
Minimize to tray on close
</span>
<p className="text-[12px] text-[var(--color-text-muted)]">
Keep Aryx running in the system tray when you close the window instead of quitting
</p>
</div>
<ToggleSwitch enabled={minimizeToTray} />
</button>
</div>
);
}
@@ -377,25 +440,28 @@ function ConnectionSection({
modelCount,
isRefreshing,
onRefresh,
onGetQuota,
}: {
connection?: SidecarCapabilities['connection'];
modelCount: number;
isRefreshing: boolean;
onRefresh: () => void;
onGetQuota?: () => Promise<Record<string, QuotaSnapshot>>;
}) {
return (
<div>
<div className="mb-1">
<h3 className="text-[13px] font-semibold text-zinc-200">GitHub Copilot</h3>
<p className="mt-0.5 text-[12px] text-zinc-500">
<h3 className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">GitHub Copilot</h3>
<p className="mt-0.5 text-[12px] text-[var(--color-text-muted)]">
Aryx uses your installed GitHub Copilot CLI for AI capabilities
</p>
</div>
<div className="mt-4 rounded-xl border border-[var(--color-border)] bg-zinc-900/30 p-4">
<div className="mt-4 rounded-xl border border-[var(--color-border)] bg-[var(--color-glass)] p-4">
<CopilotStatusCard
connection={connection}
isRefreshing={isRefreshing}
modelCount={modelCount}
onGetQuota={onGetQuota}
onRefresh={onRefresh}
/>
</div>
@@ -424,25 +490,25 @@ function PatternsSection({
<div className="space-y-1">
{patterns.map((pattern) => (
<button
className="group flex w-full items-center gap-3 rounded-xl border border-transparent px-4 py-3 text-left transition hover:border-zinc-800 hover:bg-zinc-900"
className="group flex w-full items-center gap-3 rounded-xl border border-transparent px-4 py-3 text-left transition-all duration-200 hover:border-[var(--color-border)] hover:bg-[var(--color-surface-1)]"
key={pattern.id}
onClick={() => onEditPattern(pattern)}
type="button"
>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="text-[13px] font-medium text-zinc-200">{pattern.name}</span>
<span className="text-[13px] font-medium text-[var(--color-text-primary)]">{pattern.name}</span>
<span className={`rounded-full px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide ${modeBadgeClasses(pattern)}`}>
{pattern.mode}
</span>
</div>
<p className="mt-0.5 truncate text-[12px] text-zinc-500">{pattern.description}</p>
<p className="mt-0.5 truncate text-[12px] text-[var(--color-text-muted)]">{pattern.description}</p>
</div>
<div className="flex items-center gap-2">
<span className="text-[12px] text-zinc-600">
<span className="text-[12px] text-[var(--color-text-muted)]">
{pattern.agents.length} agent{pattern.agents.length === 1 ? '' : 's'}
</span>
<ChevronRight className="size-4 text-zinc-700 transition group-hover:text-zinc-500" />
<ChevronRight className="size-4 text-[var(--color-text-muted)] transition-all duration-200 group-hover:text-[var(--color-text-muted)]" />
</div>
</button>
))}
@@ -543,8 +609,8 @@ function SectionHeader({
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>
<h3 className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">{title}</h3>
<p className="mt-0.5 text-[12px] text-[var(--color-text-muted)]">{description}</p>
</div>
{children}
</div>
@@ -554,7 +620,7 @@ function SectionHeader({
function SectionAction({ label, onClick }: { label: string; onClick: () => void }) {
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"
className="flex items-center gap-1.5 rounded-lg bg-[var(--color-surface-3)] px-3 py-1.5 text-[13px] font-medium text-[var(--color-text-primary)] transition-all duration-200 hover:bg-[var(--color-surface-3)]"
onClick={onClick}
type="button"
>
@@ -577,27 +643,27 @@ function ToolingListButton({
}) {
return (
<button
className="group flex w-full items-center gap-3 rounded-xl border border-transparent px-4 py-3 text-left transition hover:border-zinc-800 hover:bg-zinc-900"
className="group flex w-full items-center gap-3 rounded-xl border border-transparent px-4 py-3 text-left transition-all duration-200 hover:border-[var(--color-border)] hover:bg-[var(--color-surface-1)]"
onClick={onClick}
type="button"
>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate text-[13px] font-medium text-zinc-200">{label}</span>
<span className="rounded-full bg-zinc-800 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-zinc-400">
<span className="truncate text-[13px] font-medium text-[var(--color-text-primary)]">{label}</span>
<span className="rounded-full bg-[var(--color-surface-3)] px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-[var(--color-text-secondary)]">
{meta}
</span>
</div>
<p className="mt-0.5 truncate text-[12px] text-zinc-500">{detail}</p>
<p className="mt-0.5 truncate text-[12px] text-[var(--color-text-muted)]">{detail}</p>
</div>
<ChevronRight className="size-4 text-zinc-700 transition group-hover:text-zinc-500" />
<ChevronRight className="size-4 text-[var(--color-text-muted)] transition-all duration-200 group-hover:text-[var(--color-text-muted)]" />
</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">
<div className="rounded-xl border border-dashed border-[var(--color-border)] bg-[var(--color-surface-1)]/20 px-5 py-8 text-center text-[12px] leading-relaxed text-[var(--color-text-muted)]">
{children}
</div>
);
@@ -607,68 +673,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>
);
}
@@ -690,8 +720,8 @@ function DiscoveredSubSection({
<div className="mb-4">
<div className="mb-2 flex items-center justify-between">
<div>
<span className="text-[12px] font-medium text-zinc-300">{label}</span>
<p className="text-[11px] text-zinc-600">{description}</p>
<span className="text-[12px] font-medium text-[var(--color-text-secondary)]">{label}</span>
<p className="text-[11px] text-[var(--color-text-muted)]">{description}</p>
</div>
</div>
<div className="space-y-1">
@@ -734,30 +764,30 @@ function DiscoveredServerRow({
: server.url || 'No URL';
const statusBadge = status === 'accepted'
? 'bg-emerald-500/10 text-emerald-400'
: 'bg-amber-500/10 text-amber-400';
? 'bg-[var(--color-status-success)]/10 text-[var(--color-status-success)]'
: 'bg-[var(--color-status-warning)]/10 text-[var(--color-status-warning)]';
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">
<div className="flex items-center gap-3 rounded-xl border border-transparent px-4 py-3 hover:border-[var(--color-border)] hover:bg-[var(--color-surface-1)]">
<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">
<span className="truncate text-[13px] font-medium text-[var(--color-text-primary)]">{server.name}</span>
<span className="rounded-full bg-[var(--color-surface-3)] px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-[var(--color-text-secondary)]">
{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">
<p className="mt-0.5 truncate text-[12px] text-[var(--color-text-muted)]">
{detail}
<span className="ml-2 text-zinc-700">· {server.sourceLabel}</span>
<span className="ml-2 text-[var(--color-text-muted)]">· {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"
className="rounded-lg px-2.5 py-1 text-[12px] font-medium text-[var(--color-status-success)] transition-all duration-200 hover:bg-[var(--color-status-success)]/10"
onClick={onAccept}
type="button"
>
@@ -766,7 +796,7 @@ function DiscoveredServerRow({
)}
{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"
className="rounded-lg px-2.5 py-1 text-[12px] font-medium text-[var(--color-text-muted)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]"
onClick={onDismiss}
type="button"
>
@@ -814,12 +844,12 @@ function TroubleshootingSection({
/>
</div>
<div className="mt-8 rounded-xl border border-red-500/20 bg-red-500/5 p-5">
<div className="mt-8 rounded-xl border border-[var(--color-status-error)]/20 bg-[var(--color-status-error)]/5 p-5">
<div className="flex items-start gap-3">
<TriangleAlert className="mt-0.5 size-4 shrink-0 text-red-400" />
<TriangleAlert className="mt-0.5 size-4 shrink-0 text-[var(--color-status-error)]" />
<div className="min-w-0 flex-1">
<h4 className="text-[13px] font-semibold text-red-300">Reset Local Workspace</h4>
<p className="mt-1 text-[12px] leading-relaxed text-zinc-400">
<h4 className="text-[13px] font-semibold text-[var(--color-status-error)]">Reset Local Workspace</h4>
<p className="mt-1 text-[12px] leading-relaxed text-[var(--color-text-secondary)]">
Restore Aryx to its initial state. This permanently removes all sessions, custom patterns,
MCP server definitions, LSP profiles, and scratchpad contents. Your GitHub Copilot sign-in
is not affected.
@@ -827,7 +857,7 @@ function TroubleshootingSection({
{!confirmingReset ? (
<button
className="mt-3 rounded-lg border border-red-500/30 bg-red-500/10 px-3.5 py-1.5 text-[13px] font-medium text-red-300 transition hover:border-red-500/50 hover:bg-red-500/20"
className="mt-3 rounded-lg border border-[var(--color-status-error)]/30 bg-[var(--color-status-error)]/10 px-3.5 py-1.5 text-[13px] font-medium text-[var(--color-status-error)] transition-all duration-200 hover:border-[var(--color-status-error)]/50 hover:bg-[var(--color-status-error)]/20"
onClick={() => setConfirmingReset(true)}
type="button"
>
@@ -836,7 +866,7 @@ function TroubleshootingSection({
) : (
<div className="mt-3 flex items-center gap-2">
<button
className="rounded-lg bg-red-600 px-3.5 py-1.5 text-[13px] font-medium text-white transition hover:bg-red-500 disabled:opacity-50"
className="rounded-lg bg-[var(--color-status-error)] px-3.5 py-1.5 text-[13px] font-medium text-white transition-all duration-200 hover:bg-[var(--color-status-error)] disabled:opacity-50"
disabled={isResetting}
onClick={() => void handleReset()}
type="button"
@@ -844,7 +874,7 @@ function TroubleshootingSection({
{isResetting ? 'Resetting…' : 'Confirm reset'}
</button>
<button
className="rounded-lg border border-[var(--color-border)] px-3.5 py-1.5 text-[13px] font-medium text-zinc-400 transition hover:bg-zinc-800 hover:text-zinc-200"
className="rounded-lg border border-[var(--color-border)] px-3.5 py-1.5 text-[13px] font-medium text-[var(--color-text-secondary)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]"
disabled={isResetting}
onClick={() => setConfirmingReset(false)}
type="button"
@@ -873,16 +903,16 @@ function TroubleshootingAction({
}) {
return (
<button
className="group flex w-full items-center gap-3 rounded-xl border border-transparent px-4 py-3 text-left transition hover:border-zinc-800 hover:bg-zinc-900"
className="group flex w-full items-center gap-3 rounded-xl border border-transparent px-4 py-3 text-left transition-all duration-200 hover:border-[var(--color-border)] hover:bg-[var(--color-surface-1)]"
onClick={onClick}
type="button"
>
<span className="text-zinc-500 transition group-hover:text-zinc-300">{icon}</span>
<span className="text-[var(--color-text-muted)] transition-all duration-200 group-hover:text-[var(--color-text-secondary)]">{icon}</span>
<div className="min-w-0 flex-1">
<span className="text-[13px] font-medium text-zinc-200">{label}</span>
<p className="mt-0.5 text-[12px] text-zinc-500">{description}</p>
<span className="text-[13px] font-medium text-[var(--color-text-primary)]">{label}</span>
<p className="mt-0.5 text-[12px] text-[var(--color-text-muted)]">{description}</p>
</div>
<ChevronRight className="size-4 text-zinc-700 transition group-hover:text-zinc-500" />
<ChevronRight className="size-4 text-[var(--color-text-muted)] transition-all duration-200 group-hover:text-[var(--color-text-muted)]" />
</button>
);
}
+105 -63
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;
@@ -53,12 +54,12 @@ interface SidebarProps {
/* ── Mode icon + accent colour mapping ─────────────────────── */
const modeVisuals: Record<OrchestrationMode, { icon: LucideIcon; color: string }> = {
single: { icon: MessageSquare, color: 'text-indigo-400' },
sequential: { icon: ListOrdered, color: 'text-amber-400' },
concurrent: { icon: GitFork, color: 'text-emerald-400' },
handoff: { icon: ArrowLeftRight, color: 'text-sky-400' },
'group-chat': { icon: Users, color: 'text-violet-400' },
magentic: { icon: Lock, color: 'text-zinc-500' },
single: { icon: MessageSquare, color: 'text-[#245CF9]' },
sequential: { icon: ListOrdered, color: 'text-[var(--color-status-warning)]' },
concurrent: { icon: GitFork, color: 'text-[var(--color-status-success)]' },
handoff: { icon: ArrowLeftRight, color: 'text-[var(--color-accent-sky)]' },
'group-chat': { icon: Users, color: 'text-[var(--color-accent-purple)]' },
magentic: { icon: Lock, color: 'text-[var(--color-text-muted)]' },
};
/* ── Relative time helper ──────────────────────────────────── */
@@ -82,7 +83,7 @@ function relativeTime(iso: string): string {
function GitContextBadge({ git }: { git: ProjectGitContext }) {
if (git.status === 'not-repository') {
return (
<span className="text-[10px] text-zinc-600" title="Not a git repository">
<span className="text-[10px] text-[var(--color-text-muted)]" title="Not a git repository">
no repo
</span>
);
@@ -116,7 +117,7 @@ function GitContextBadge({ git }: { git: ProjectGitContext }) {
if (git.behind) parts.push(`${git.behind}`);
return (
<span className="flex items-center gap-1 text-[10px] text-zinc-500" title={parts.join(' · ') || branchLabel}>
<span className="flex items-center gap-1 text-[10px] text-[var(--color-text-muted)]" title={parts.join(' · ') || branchLabel}>
<GitBranch className="size-2.5 shrink-0" />
<span className="max-w-[80px] truncate">{branchLabel}</span>
{git.isDirty && <Circle className="size-1.5 shrink-0 fill-amber-500 text-amber-500" />}
@@ -139,7 +140,7 @@ function ActionMenuItem({
}) {
return (
<button
className={`flex w-full items-center gap-2 px-3 py-1.5 text-[12px] transition hover:bg-zinc-800 ${className ?? 'text-zinc-300'}`}
className={`flex w-full items-center gap-2 px-3 py-1.5 text-[12px] transition-all duration-150 hover:bg-[var(--color-surface-2)] ${className ?? 'text-[var(--color-text-primary)]'}`}
onClick={onClick}
role="menuitem"
type="button"
@@ -212,10 +213,10 @@ function SessionItem({
return (
<div
className={`group relative flex w-full cursor-pointer items-start gap-2.5 rounded-lg px-2.5 py-2 text-left transition-all duration-150 ${
className={`session-item-enter group relative flex w-full cursor-pointer items-start gap-2.5 rounded-lg px-2.5 py-2 text-left transition-all duration-200 ${
isActive
? 'bg-indigo-500/10 ring-1 ring-indigo-500/25'
: 'hover:bg-zinc-800/60'
? 'bg-[var(--color-accent-muted)] ring-1 ring-[var(--color-border-glow)]'
: 'hover:bg-[var(--color-surface-2)]/60'
} ${isRunning ? 'sidebar-running' : ''} ${session.isArchived ? 'opacity-50' : ''}`}
onClick={isRenaming ? undefined : onSelect}
role="button"
@@ -224,19 +225,19 @@ function SessionItem({
>
{/* Running/approval left accent bar */}
{isRunning && !hasPendingApproval && (
<span className="absolute inset-y-1.5 left-0 w-[3px] rounded-full bg-blue-400 sidebar-pulse" />
<span className="absolute inset-y-1.5 left-0 w-[3px] rounded-full accent-flow" />
)}
{hasPendingApproval && (
<span className="absolute inset-y-1.5 left-0 w-[3px] rounded-full bg-amber-400" />
<span className="absolute inset-y-1.5 left-0 w-[3px] rounded-full bg-[var(--color-status-warning)]" />
)}
{/* Mode icon */}
<span
className={`mt-0.5 flex size-6 shrink-0 items-center justify-center rounded-md ${
isActive ? 'bg-indigo-500/15' : 'bg-zinc-800/80'
isActive ? 'bg-[var(--color-accent-muted)]' : 'bg-[var(--color-surface-2)]'
}`}
>
<ModeIcon className={`size-3.5 ${isActive ? 'text-indigo-400' : visual.color}`} />
<ModeIcon className={`size-3.5 ${isActive ? 'text-[var(--color-accent)]' : visual.color}`} />
</span>
{/* Content */}
@@ -246,7 +247,7 @@ function SessionItem({
{isRenaming ? (
<input
ref={inputRef}
className="w-full rounded bg-zinc-800 px-1.5 py-0.5 text-[13px] font-medium text-zinc-100 outline-none ring-1 ring-indigo-500/50"
className="w-full rounded bg-[var(--color-surface-2)] px-1.5 py-0.5 text-[13px] font-medium text-[var(--color-text-primary)] outline-none ring-1 ring-[var(--color-border-glow)]"
value={renameText}
onChange={(e) => setRenameText(e.target.value)}
onKeyDown={handleRenameKeyDown}
@@ -256,7 +257,7 @@ function SessionItem({
) : (
<span
className={`truncate text-[13px] font-medium leading-tight ${
isActive ? 'text-indigo-100' : 'text-zinc-200 group-hover:text-zinc-100'
isActive ? 'text-[var(--color-text-primary)]' : 'text-[var(--color-text-primary)] group-hover:text-[var(--color-text-primary)]'
}`}
>
{session.title}
@@ -266,36 +267,55 @@ function SessionItem({
<div className="mt-1 flex items-center gap-2">
{agentCount > 1 && (
<span className="inline-flex items-center gap-0.5 text-[10px] text-zinc-500">
<span className="inline-flex items-center gap-0.5 text-[10px] text-[var(--color-text-muted)]">
<Users className="size-2.5" />
{agentCount}
</span>
)}
{isRunning && !hasPendingApproval && (
<span className="inline-flex items-center gap-1 text-[10px] font-medium text-blue-400">
<span className="size-1.5 rounded-full bg-blue-400 sidebar-pulse" />
<span className="inline-flex items-center gap-1 text-[10px] font-medium text-[var(--color-accent-sky)]">
<span className="size-1.5 rounded-full bg-[var(--color-accent-sky)] sidebar-pulse" />
Running
</span>
)}
{hasPendingApproval && (
<span className="inline-flex items-center gap-1 text-[10px] font-medium text-amber-400">
<span className="size-1.5 rounded-full bg-amber-400 animate-pulse" />
<span className="inline-flex items-center gap-1 text-[10px] font-medium text-[var(--color-status-warning)]">
<span className="size-1.5 rounded-full bg-[var(--color-status-warning)] animate-pulse" />
Awaiting approval{queuedCount > 0 && ` (+${queuedCount})`}
</span>
)}
{isError && (
<span className="inline-flex items-center gap-1 text-[10px] font-medium text-red-400">
<span className="size-1.5 rounded-full bg-red-400" />
<span className="inline-flex items-center gap-1 text-[10px] font-medium text-[var(--color-status-error)]">
<span className="size-1.5 rounded-full bg-[var(--color-status-error)]" />
Error
</span>
)}
{session.isArchived && (
<span className="inline-flex items-center gap-1 text-[10px] text-zinc-600">
<span className="inline-flex items-center gap-1 text-[10px] text-[var(--color-text-muted)]">
<Archive className="size-2.5" />
Archived
</span>
)}
<span className="ml-auto text-[10px] text-zinc-600 group-hover:text-zinc-500">
{session.branchOrigin && (
<span
className="inline-flex items-center gap-0.5 text-[10px] text-[var(--color-text-muted)]"
title={
session.branchOrigin.action === 'regenerate'
? 'Regenerated response'
: session.branchOrigin.action === 'edit-and-resend'
? 'Edited & resent'
: 'Branched session'
}
>
{session.branchOrigin.action === 'regenerate'
? <RefreshCw className="size-2.5" />
: session.branchOrigin.action === 'edit-and-resend'
? <Pencil className="size-2.5" />
: <GitBranch className="size-2.5" />
}
</span>
)}
<span className="ml-auto text-[10px] text-[var(--color-text-muted)] group-hover:text-[var(--color-text-secondary)]">
{relativeTime(session.updatedAt)}
</span>
</div>
@@ -304,7 +324,7 @@ function SessionItem({
{/* Actions button (hidden during rename) */}
{!isRenaming && (
<button
className="absolute right-1.5 top-1.5 flex size-6 items-center justify-center rounded-md text-zinc-600 opacity-0 transition hover:bg-zinc-700 hover:text-zinc-300 group-hover:opacity-100"
className="absolute right-1.5 top-1.5 flex size-6 items-center justify-center rounded-md text-[var(--color-text-muted)] opacity-0 transition-all duration-150 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)] group-hover:opacity-100"
onClick={(e) => { e.stopPropagation(); onOpenMenu(e); }}
type="button"
>
@@ -328,6 +348,7 @@ function ProjectGroup({
onRenameSubmit,
onRenameCancel,
onRefreshGitContext,
onOpenProjectSettings,
onNewSession,
newSessionLabel,
}: {
@@ -341,6 +362,7 @@ function ProjectGroup({
onRenameSubmit: (sessionId: string, title: string) => void;
onRenameCancel: () => void;
onRefreshGitContext?: (projectId: string) => void;
onOpenProjectSettings?: (projectId: string) => void;
onNewSession?: () => void;
newSessionLabel?: string;
}){
@@ -373,19 +395,19 @@ function ProjectGroup({
return (
<div>
<button
className="group flex w-full items-center gap-2 rounded-lg px-2 py-2 text-left text-[13px] font-semibold text-zinc-400 transition hover:bg-zinc-800/40 hover:text-zinc-200"
className="group flex w-full items-center gap-2 rounded-lg px-2 py-2 text-left text-[13px] font-semibold text-[var(--color-text-secondary)] transition-all duration-150 hover:bg-[var(--color-surface-2)]/40 hover:text-[var(--color-text-primary)]"
onClick={() => setExpanded(!expanded)}
type="button"
>
{expanded ? (
<ChevronDown className="size-3 shrink-0 text-zinc-500" />
<ChevronDown className="size-3 shrink-0 text-[var(--color-text-muted)]" />
) : (
<ChevronRight className="size-3 shrink-0 text-zinc-500" />
<ChevronRight className="size-3 shrink-0 text-[var(--color-text-muted)]" />
)}
{isScratchpad ? (
<MessageSquare className="size-3.5 shrink-0 text-zinc-500 transition group-hover:text-indigo-400" />
<MessageSquare className="size-3.5 shrink-0 text-[var(--color-text-muted)] transition group-hover:text-[var(--color-accent)]" />
) : (
<FolderOpen className="size-3.5 shrink-0 text-zinc-500 transition group-hover:text-indigo-400" />
<FolderOpen className="size-3.5 shrink-0 text-[var(--color-text-muted)] transition group-hover:text-[var(--color-accent)]" />
)}
<span className="truncate">{project.name}</span>
@@ -394,9 +416,22 @@ 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-[var(--color-text-muted)] opacity-0 transition hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)] 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"
className="flex size-5 items-center justify-center rounded text-[var(--color-text-muted)] opacity-0 transition hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)] group-hover:opacity-100"
onClick={(e) => {
e.stopPropagation();
onRefreshGitContext(project.id);
@@ -408,27 +443,32 @@ function ProjectGroup({
</span>
)}
{runningCount > 0 && (
<span className="flex items-center gap-1 rounded-full bg-blue-500/10 px-1.5 py-0.5 text-[10px] font-medium text-blue-400">
<span className="size-1.5 rounded-full bg-blue-400 sidebar-pulse" />
<span className="flex items-center gap-1 rounded-full bg-[var(--color-accent-sky)]/10 px-1.5 py-0.5 text-[10px] font-medium text-[var(--color-accent-sky)]">
<span className="size-1.5 rounded-full bg-[var(--color-accent-sky)] sidebar-pulse" />
{runningCount}
</span>
)}
{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>
)}
<span className="rounded-full bg-zinc-800 px-1.5 py-0.5 text-[10px] font-medium text-zinc-500">
<span className="rounded-full bg-[var(--color-surface-2)] px-1.5 py-0.5 text-[10px] font-medium text-[var(--color-text-muted)]">
{visibleSessions.length}
</span>
</div>
</button>
{expanded && (
<div className="ml-2 mt-0.5 space-y-0.5 border-l border-zinc-800/60 pl-2">
<div className="ml-2 mt-0.5 space-y-0.5 border-l border-[var(--color-border-subtle)] pl-2">
{visibleSessions.length > 0 &&
visibleSessions.map((session) => (
<SessionItem
@@ -445,7 +485,7 @@ function ProjectGroup({
))}
{onNewSession ? (
<button
className="flex w-full items-center justify-center gap-1.5 rounded-md border border-dashed border-zinc-700/60 bg-zinc-800/20 px-2.5 py-1.5 text-[12px] font-medium text-zinc-500 transition hover:border-indigo-500/40 hover:bg-indigo-500/5 hover:text-indigo-300"
className="flex w-full items-center justify-center gap-1.5 rounded-md border border-dashed border-[var(--color-border)] bg-[var(--color-surface-1)]/40 px-2.5 py-1.5 text-[12px] font-medium text-[var(--color-text-muted)] transition-all duration-200 hover:border-[var(--color-border-glow)] hover:bg-[var(--color-accent-muted)] hover:text-[var(--color-accent)]"
onClick={onNewSession}
type="button"
>
@@ -454,7 +494,7 @@ function ProjectGroup({
</button>
) : (
visibleSessions.length === 0 && (
<div className="px-3 py-3 text-center text-[12px] text-zinc-600">
<div className="px-3 py-3 text-center text-[12px] text-[var(--color-text-muted)]">
{isScratchpad ? 'No scratchpad chats yet' : 'No sessions yet'}
</div>
)
@@ -475,6 +515,7 @@ export function Sidebar({
onProjectSelect,
onSessionSelect,
onOpenSettings,
onOpenProjectSettings,
onRenameSession,
onDuplicateSession,
onSetSessionPinned,
@@ -540,19 +581,19 @@ export function Sidebar({
return (
<div className="flex h-full flex-col">
{/* Header — extra top padding clears the title bar overlay zone */}
<div className="drag-region flex items-center justify-between border-b border-[var(--color-border)] px-4 pb-3 pt-3">
<div className="drag-region flex items-center justify-between border-b border-[var(--color-border-subtle)] px-4 pb-3 pt-3">
<div className="flex items-center gap-2.5">
<img alt="aryx" className="size-8 rounded-xl" src={appIconUrl} />
<div>
<span className="text-sm font-semibold text-zinc-100">aryx</span>
<span className="ml-1.5 rounded bg-zinc-800 px-1 py-0.5 text-[9px] font-medium text-zinc-500">
<span className="font-display text-sm font-semibold text-[var(--color-text-primary)]">aryx</span>
<span className="ml-1.5 rounded bg-[var(--color-surface-2)] px-1 py-0.5 text-[9px] font-medium text-[var(--color-text-muted)]">
ALPHA
</span>
</div>
</div>
<div className="flex items-center gap-1">
<button
className="no-drag flex size-8 items-center justify-center rounded-lg text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300"
className="no-drag flex size-8 items-center justify-center rounded-lg text-[var(--color-text-muted)] transition-all duration-150 hover:bg-[var(--color-surface-2)] hover:text-[var(--color-text-primary)]"
onClick={onOpenSettings}
title="Settings"
type="button"
@@ -565,16 +606,16 @@ export function Sidebar({
{/* Search + Filters */}
<div className="space-y-2 px-3 pt-3 pb-1">
<div className="relative">
<Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-zinc-500" />
<Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-[var(--color-text-muted)]" />
<input
className="w-full rounded-lg border border-zinc-800 bg-zinc-900/60 py-1.5 pl-8 pr-8 text-[12px] text-zinc-200 placeholder-zinc-600 outline-none transition focus:border-zinc-700 focus:bg-zinc-900"
className="w-full rounded-xl border border-[var(--color-border)] bg-[var(--color-surface-0)]/60 py-1.5 pl-8 pr-8 text-[12px] text-[var(--color-text-primary)] placeholder-[var(--color-text-muted)] outline-none transition-all duration-200 focus:border-[var(--color-border-glow)] focus:bg-[var(--color-surface-0)] focus:shadow-[0_0_12px_rgba(36,92,249,0.06)]"
placeholder="Search sessions…"
value={searchText}
onChange={(e) => setSearchText(e.target.value)}
/>
{searchText && (
<button
className="absolute right-2 top-1/2 -translate-y-1/2 text-zinc-500 hover:text-zinc-300"
className="absolute right-2 top-1/2 -translate-y-1/2 text-[var(--color-text-muted)] hover:text-[var(--color-text-primary)]"
onClick={() => setSearchText('')}
type="button"
>
@@ -593,11 +634,11 @@ export function Sidebar({
{isQueryActive ? (
/* ── Flat search / filter results ──────────────────────── */
<div className="space-y-1">
<div className="px-2 text-[10px] font-semibold uppercase tracking-[0.12em] text-zinc-600">
<div className="px-2 text-[10px] font-semibold uppercase tracking-[0.12em] text-[var(--color-text-muted)]">
Results ({queryResults.length})
</div>
{queryResults.length === 0 ? (
<div className="px-3 py-6 text-center text-[12px] text-zinc-600">
<div className="px-3 py-6 text-center text-[12px] text-[var(--color-text-muted)]">
No sessions match your search
</div>
) : (
@@ -621,7 +662,7 @@ export function Sidebar({
<div className="space-y-3">
{scratchpadProject && (
<div className="space-y-1">
<div className="px-2 text-[10px] font-semibold uppercase tracking-[0.12em] text-zinc-600">
<div className="px-2 text-[10px] font-semibold uppercase tracking-[0.12em] text-[var(--color-text-muted)]">
Scratchpad
</div>
<ProjectGroup
@@ -644,21 +685,21 @@ export function Sidebar({
{userProjects.length === 0 ? (
<div className="flex flex-col items-center gap-4 px-4 py-8 text-center">
<div className="relative">
<div className="flex size-14 items-center justify-center rounded-2xl bg-zinc-800/50 ring-1 ring-zinc-700/50">
<FolderOpen className="size-7 text-zinc-600" />
<div className="flex size-14 items-center justify-center rounded-2xl bg-[var(--color-surface-2)] ring-1 ring-[var(--color-border)]">
<FolderOpen className="size-7 text-[var(--color-text-muted)]" />
</div>
<div className="absolute -bottom-1 -right-1 flex size-6 items-center justify-center rounded-full bg-indigo-600 ring-2 ring-[var(--color-surface-1)]">
<div className="absolute -bottom-1 -right-1 flex size-6 items-center justify-center rounded-full brand-gradient-bg ring-2 ring-[var(--color-surface-1)]">
<Plus className="size-3 text-white" />
</div>
</div>
<div>
<p className="text-[13px] font-medium text-zinc-300">No projects yet</p>
<p className="mt-1 text-[12px] leading-relaxed text-zinc-500">
<p className="text-[13px] font-medium text-[var(--color-text-primary)]">No projects yet</p>
<p className="mt-1 text-[12px] leading-relaxed text-[var(--color-text-muted)]">
Use Scratchpad for ad-hoc chat or add a repo<br />to work against project files
</p>
</div>
<button
className="rounded-lg bg-indigo-600 px-4 py-2 text-[13px] font-medium text-white transition hover:bg-indigo-500"
className="rounded-lg brand-gradient-bg px-4 py-2 text-[13px] font-medium text-white shadow-[0_2px_12px_rgba(36,92,249,0.25)] transition-all duration-200 hover:shadow-[0_4px_20px_rgba(36,92,249,0.35)]"
onClick={onAddProject}
type="button"
>
@@ -667,7 +708,7 @@ export function Sidebar({
</div>
) : (
<div className="space-y-1">
<div className="px-2 text-[10px] font-semibold uppercase tracking-[0.12em] text-zinc-600">
<div className="px-2 text-[10px] font-semibold uppercase tracking-[0.12em] text-[var(--color-text-muted)]">
Projects
</div>
{userProjects.map((project) => (
@@ -678,6 +719,7 @@ export function Sidebar({
onRenameSubmit={handleRenameSubmit}
onRenameCancel={() => setRenamingSessionId(undefined)}
onRefreshGitContext={onRefreshGitContext}
onOpenProjectSettings={onOpenProjectSettings}
renamingSessionId={renamingSessionId}
patterns={workspace.patterns}
project={project}
@@ -694,9 +736,9 @@ export function Sidebar({
{/* Footer */}
{userProjects.length > 0 && (
<div className="border-t border-[var(--color-border)] px-3 py-2">
<div className="border-t border-[var(--color-border-subtle)] px-3 py-2">
<button
className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-[12px] text-zinc-500 transition hover:bg-zinc-800/60 hover:text-zinc-300"
className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-[12px] text-[var(--color-text-muted)] transition-all duration-150 hover:bg-[var(--color-surface-2)]/60 hover:text-[var(--color-text-primary)]"
onClick={onAddProject}
type="button"
>
@@ -711,7 +753,7 @@ export function Sidebar({
<>
<div className="fixed inset-0 z-40" onClick={closeMenu} onKeyDown={(e) => { if (e.key === 'Escape') closeMenu(); }} />
<div
className="fixed z-50 w-40 rounded-lg border border-zinc-700 bg-zinc-900 py-1 shadow-xl"
className="fixed z-50 w-40 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] py-1 shadow-[0_8px_32px_rgba(0,0,0,0.4)]"
role="menu"
style={{ top: menuState.top, left: menuState.left }}
>
@@ -748,7 +790,7 @@ export function Sidebar({
}}
/>
<ActionMenuItem
className="text-red-400 hover:bg-red-500/10"
className="text-[var(--color-status-error)] hover:bg-[var(--color-status-error)]/10"
icon={Trash2}
label="Delete"
onClick={() => {
+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: '#07080e',
foreground: '#e8eaf0',
cursor: '#245CF9',
cursorAccent: '#07080e',
selectionBackground: 'rgba(36, 92, 249, 0.2)',
selectionForeground: '#e8eaf0',
black: '#1e2233',
red: '#f87171',
green: '#4ade80',
yellow: '#facc15',
blue: '#248CFD',
magenta: '#a855f7',
cyan: '#22d3ee',
white: '#e8eaf0',
brightBlack: '#4e5368',
brightRed: '#fca5a5',
brightGreen: '#86efac',
brightYellow: '#fde047',
brightBlue: '#60a5fa',
brightMagenta: '#c084fc',
brightCyan: '#67e8f9',
brightWhite: '#f8f9fc',
};
/* ── 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: '"JetBrains Mono Variable", "JetBrains Mono", ui-monospace, "SF Mono", Menlo, 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-[var(--color-surface-0)]"
style={{ height, minHeight: MIN_HEIGHT }}
>
{/* Resize handle */}
<div
className={`h-1 shrink-0 cursor-row-resize transition-colors ${isDragging ? 'bg-[var(--color-accent)]/40' : 'hover:bg-[var(--color-surface-3)]/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-[var(--color-border)] px-3">
<span className={`size-1.5 shrink-0 rounded-full ${isRunning ? 'bg-emerald-400' : 'bg-[var(--color-text-muted)]'}`} />
<span className="min-w-0 flex-1 truncate font-mono text-[11px] text-[var(--color-text-muted)]">
{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-[var(--color-text-muted)] transition hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]"
onClick={handleRestart}
type="button"
>
<RotateCcw className="size-3" />
</button>
<button
aria-label="Minimize terminal"
className="rounded p-0.5 text-[var(--color-text-muted)] transition hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]"
onClick={onMinimize}
type="button"
>
<Minus className="size-3" />
</button>
<button
aria-label="Close terminal"
className="rounded p-0.5 text-[var(--color-text-muted)] transition hover:bg-[var(--color-surface-3)] 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 };
+195 -38
View File
@@ -1,61 +1,218 @@
import { MessageSquare, Plus, Settings } from 'lucide-react';
import { CheckCircle2, Circle, FolderPlus, MessageSquarePlus, Settings, Zap } from 'lucide-react';
import { motion } from 'motion/react';
import type { SidecarConnectionStatus } from '@shared/contracts/sidecar';
import appIconUrl from '../../../assets/icons/icon.png';
interface WelcomePaneProps {
hasProjects: boolean;
connectionStatus?: SidecarConnectionStatus;
onNewScratchpad: () => void;
onAddProject: () => void;
onOpenSettings: () => void;
}
const fadeUp = (delay: number) =>
({
initial: { opacity: 0, y: 12 },
animate: { opacity: 1, y: 0 },
transition: { duration: 0.45, ease: [0.25, 0.46, 0.45, 0.94] as const, delay },
}) as const;
interface ActionCardProps {
icon: React.ReactNode;
title: string;
description: string;
onClick: () => void;
highlight?: boolean;
}
function ActionCard({ icon, title, description, onClick, highlight }: ActionCardProps) {
return (
<button
type="button"
onClick={onClick}
className={`group flex w-full cursor-pointer items-center gap-4 rounded-xl border px-5 py-4 text-left backdrop-blur-sm transition-all duration-200 ${
highlight
? 'border-[var(--color-border-glow)] bg-[var(--color-accent-muted)] shadow-[0_0_24px_rgba(36,92,249,0.1)] hover:shadow-[0_0_32px_rgba(36,92,249,0.15)]'
: 'border-[var(--color-glass-border)] bg-[var(--color-glass)] hover:border-[var(--color-border-glow)] hover:shadow-[0_0_20px_rgba(36,92,249,0.08),0_4px_12px_rgba(0,0,0,0.2)]'
}`}
>
<div className="brand-gradient-bg flex size-9 shrink-0 items-center justify-center rounded-full">
{icon}
</div>
<div className="min-w-0">
<span className="block text-[13px] font-medium text-[var(--color-text-primary)]">
{title}
</span>
<span className="block text-[12px] leading-relaxed text-[var(--color-text-muted)]">
{description}
</span>
</div>
</button>
);
}
interface SetupStepProps {
label: string;
done: boolean;
active?: boolean;
}
function SetupStep({ label, done, active }: SetupStepProps) {
return (
<div className={`flex items-center gap-2 text-[12px] ${active ? 'text-[var(--color-text-primary)]' : 'text-[var(--color-text-muted)]'}`}>
{done
? <CheckCircle2 className="size-3.5 text-[var(--color-status-success)]" />
: <Circle className={`size-3.5 ${active ? 'text-[var(--color-accent)]' : 'text-[var(--color-text-muted)]'}`} />
}
<span className={done ? 'line-through opacity-60' : ''}>{label}</span>
</div>
);
}
export function WelcomePane({
hasProjects,
connectionStatus,
onNewScratchpad,
onAddProject,
onOpenSettings,
}: WelcomePaneProps) {
const isConnected = connectionStatus === 'ready';
const isFirstRun = !hasProjects;
// Determine setup progress
const steps = [
{ label: 'GitHub Copilot connected', done: isConnected },
{ label: 'First project added', done: hasProjects },
];
const completedSteps = steps.filter((s) => s.done).length;
const allDone = completedSteps === steps.length;
return (
<div className="flex h-full flex-col items-center justify-center px-8">
<div className="flex flex-col items-center gap-6 text-center">
<div className="flex size-16 items-center justify-center rounded-2xl bg-indigo-600/10">
<MessageSquare className="size-8 text-indigo-400" />
</div>
<div className="relative flex h-full flex-col items-center justify-center overflow-hidden px-8">
{/* Ambient nebula glow */}
<div
className="pointer-events-none absolute inset-0"
aria-hidden="true"
style={{
background: [
'radial-gradient(ellipse 50% 40% at 50% 45%, rgba(36, 92, 249, 0.07) 0%, transparent 70%)',
'radial-gradient(ellipse 40% 35% at 55% 50%, rgba(138, 41, 230, 0.05) 0%, transparent 65%)',
'radial-gradient(ellipse 60% 50% at 45% 48%, rgba(54, 21, 207, 0.04) 0%, transparent 60%)',
].join(', '),
}}
/>
<div>
<h1 className="text-base font-semibold text-zinc-100">Welcome to aryx</h1>
<p className="mt-2 max-w-md text-[13px] leading-relaxed text-zinc-500">
Start a scratchpad conversation for ad-hoc questions or connect a project to work with
repo-aware Copilot agents.
<div className="relative z-10 flex w-full max-w-sm flex-col items-center gap-6 text-center">
{/* Icon */}
<motion.div {...fadeUp(0)}>
<img
src={appIconUrl}
alt="aryx"
width={64}
height={64}
className="drop-shadow-[0_0_24px_rgba(36,92,249,0.3)]"
/>
</motion.div>
{/* Heading */}
<motion.div {...fadeUp(0.08)}>
<h1 className="font-display brand-gradient-text text-2xl font-bold tracking-tight">
{isFirstRun ? 'Welcome to Aryx' : 'aryx'}
</h1>
<p className="mt-2 max-w-sm text-[13px] leading-relaxed text-[var(--color-text-secondary)]">
{isFirstRun
? 'Your AI workspace powered by GitHub Copilot. Start a scratchpad for quick questions or connect a project for full agent support.'
: 'Start a scratchpad conversation for ad-hoc questions or connect a project to work with repo-aware Copilot agents.'
}
</p>
</div>
</motion.div>
<div className="flex flex-col items-center gap-2">
<button
className="flex items-center gap-2 rounded-lg bg-indigo-600 px-5 py-2.5 text-[13px] font-medium text-white transition hover:bg-indigo-500"
onClick={onNewScratchpad}
type="button"
>
<Plus className="size-4" />
New Scratchpad
</button>
{!hasProjects && (
<button
className="flex items-center gap-2 rounded-lg px-4 py-2 text-[13px] text-zinc-500 transition hover:bg-zinc-900 hover:text-zinc-300"
onClick={onAddProject}
type="button"
>
<Plus className="size-3.5" />
Add Your First Project
</button>
{/* Setup progress — only for first-run */}
{isFirstRun && !allDone && (
<motion.div {...fadeUp(0.12)} className="w-full rounded-xl border border-[var(--color-border)] bg-[var(--color-surface-1)]/60 p-4">
<div className="mb-3 flex items-center justify-between">
<span className="text-[11px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
Getting started
</span>
<span className="text-[11px] text-[var(--color-text-muted)]">
{completedSteps}/{steps.length}
</span>
</div>
{/* Progress bar */}
<div className="mb-3 h-1 overflow-hidden rounded-full bg-[var(--color-surface-3)]">
<motion.div
className="h-full rounded-full bg-gradient-to-r from-[var(--color-accent)] to-[var(--color-accent-purple)]"
initial={{ width: 0 }}
animate={{ width: `${(completedSteps / steps.length) * 100}%` }}
transition={{ duration: 0.6, ease: 'easeOut', delay: 0.3 }}
/>
</div>
<div className="space-y-2">
{steps.map((step, i) => (
<SetupStep
key={step.label}
label={step.label}
done={step.done}
active={!step.done && steps.slice(0, i).every((s) => s.done)}
/>
))}
</div>
</motion.div>
)}
{/* Action cards */}
<motion.div {...fadeUp(isFirstRun && !allDone ? 0.2 : 0.16)} className="flex w-full flex-col gap-2.5">
{/* Primary CTA adapts to state */}
{!isConnected && (
<ActionCard
icon={<Zap className="size-4 text-white" />}
title="Connect GitHub Copilot"
description="Check connection status and configure your CLI"
onClick={onOpenSettings}
highlight
/>
)}
<button
className="flex items-center gap-2 rounded-lg px-4 py-2 text-[13px] text-zinc-500 transition hover:bg-zinc-900 hover:text-zinc-300"
<ActionCard
icon={<MessageSquarePlus className="size-4 text-white" />}
title={isFirstRun ? 'Try a Quick Scratchpad' : 'New Scratchpad'}
description={isFirstRun ? 'Start a conversation — no setup needed' : 'Ask anything without a project context'}
onClick={onNewScratchpad}
highlight={isConnected && isFirstRun}
/>
{!hasProjects && (
<ActionCard
icon={<FolderPlus className="size-4 text-white" />}
title="Add Your First Project"
description="Connect a repo for full agent support"
onClick={onAddProject}
/>
)}
<ActionCard
icon={<Settings className="size-4 text-white" />}
title="Manage Patterns"
description="Customize agent behaviors and workflows"
onClick={onOpenSettings}
type="button"
>
<Settings className="size-3.5" />
Manage patterns
</button>
</div>
/>
</motion.div>
{/* Keyboard shortcut hints for returning users */}
{!isFirstRun && (
<motion.div {...fadeUp(0.24)} className="flex items-center gap-4 text-[11px] text-[var(--color-text-muted)]">
<span>
<kbd className="rounded border border-[var(--color-border)] px-1.5 py-0.5 font-mono text-[10px]">Ctrl+N</kbd>
{' '}new session
</span>
<span>
<kbd className="rounded border border-[var(--color-border)] px-1.5 py-0.5 font-mono text-[10px]">Ctrl+K</kbd>
{' '}commands
</span>
</motion.div>
)}
</div>
</div>
);
+29 -29
View File
@@ -30,50 +30,50 @@ export function ApprovalBanner({
const approvalToolLabel = approvalToolKey ? resolveToolLabel(approvalToolKey) : undefined;
return (
<div className="rounded-xl border border-amber-500/30 bg-amber-500/5 px-4 py-3" role="alert">
<div className="rounded-xl border border-[var(--color-glass-border)] border-l-4 border-l-[var(--color-status-warning)] bg-[var(--color-glass)] px-4 py-3" role="alert">
{/* Header */}
<div className="flex items-start gap-2.5">
<ShieldAlert className="mt-0.5 size-4 shrink-0 text-amber-400" />
<ShieldAlert className="mt-0.5 size-4 shrink-0 text-[var(--color-status-warning)]" />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="text-[13px] font-semibold text-amber-200">{approval.title}</span>
<span className="rounded-full bg-amber-500/15 px-2 py-0.5 text-[9px] font-semibold uppercase tracking-wider text-amber-400">
<span className="text-[13px] font-semibold text-[var(--color-status-warning)]">{approval.title}</span>
<span className="rounded-full bg-[var(--color-status-warning)]/15 px-2 py-0.5 text-[9px] font-semibold uppercase tracking-wider text-[var(--color-status-warning)]">
{kindLabel}
</span>
{showPosition && (
<span className="rounded-full bg-zinc-800 px-2 py-0.5 text-[9px] font-semibold tabular-nums text-zinc-400">
<span className="rounded-full bg-[var(--color-surface-2)] px-2 py-0.5 text-[9px] font-semibold tabular-nums text-[var(--color-text-secondary)]">
{position} of {total}
</span>
)}
</div>
<div className="mt-1 flex flex-wrap items-center gap-2 text-[11px] text-zinc-400">
{approval.agentName && <span>Agent: <span className="text-zinc-300">{approval.agentName}</span></span>}
{approval.toolName && <span>Tool: <span className="text-zinc-300">{approval.toolName}</span></span>}
{approval.permissionKind && <span>Permission: <span className="text-zinc-300">{approval.permissionKind}</span></span>}
<div className="mt-1 flex flex-wrap items-center gap-2 text-[11px] text-[var(--color-text-secondary)]">
{approval.agentName && <span>Agent: <span className="text-[var(--color-text-primary)]">{approval.agentName}</span></span>}
{approval.toolName && <span>Tool: <span className="text-[var(--color-text-primary)]">{approval.toolName}</span></span>}
{approval.permissionKind && <span>Permission: <span className="text-[var(--color-text-primary)]">{approval.permissionKind}</span></span>}
</div>
{approval.permissionDetail
? <PermissionDetailView detail={approval.permissionDetail} />
: approval.detail && (
<p className="mt-1.5 text-[12px] leading-relaxed text-zinc-400">{approval.detail}</p>
<p className="mt-1.5 text-[12px] leading-relaxed text-[var(--color-text-secondary)]">{approval.detail}</p>
)}
</div>
</div>
{/* Final-response message preview */}
{hasMessages && (
<div className="mt-3 space-y-2 rounded-lg border border-zinc-800 bg-zinc-900/60 p-3">
<p className="text-[10px] font-semibold uppercase tracking-wider text-zinc-500">
<div className="mt-3 space-y-2 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] p-3">
<p className="text-[10px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
Pending messages not yet published
</p>
{approval.messages!.map((message) => (
<div className="mt-2" key={message.id}>
<div className="mb-1 flex items-center gap-2 text-[11px] font-medium text-zinc-500">
<div className="mb-1 flex items-center gap-2 text-[11px] font-medium text-[var(--color-text-muted)]">
<Bot className="size-3" />
<span>{message.authorName}</span>
</div>
<div className="rounded-lg border border-zinc-800/60 bg-zinc-900/40 px-3 py-2 text-[13px] leading-relaxed text-zinc-300">
<div className="rounded-lg border border-[var(--color-border-subtle)] bg-[var(--color-surface-1)]/60 px-3 py-2 text-[13px] leading-relaxed text-[var(--color-text-secondary)]">
<MarkdownContent content={message.content} />
</div>
</div>
@@ -84,7 +84,7 @@ export function ApprovalBanner({
{/* Actions */}
<div className="mt-3 flex items-center gap-2">
<button
className="inline-flex items-center gap-1.5 rounded-lg bg-emerald-600 px-3.5 py-1.5 text-[12px] font-medium text-white transition hover:bg-emerald-500 disabled:cursor-not-allowed disabled:opacity-50"
className="brand-gradient-bg inline-flex items-center gap-1.5 rounded-lg px-3.5 py-1.5 text-[12px] font-medium text-white transition-all duration-200 hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResolving}
onClick={() => onResolve('approved')}
type="button"
@@ -95,7 +95,7 @@ export function ApprovalBanner({
{canAlwaysApprove && (
<button
aria-label={`Always approve ${approvalToolLabel}`}
className="inline-flex items-center gap-1.5 rounded-lg bg-emerald-600/20 px-3.5 py-1.5 text-[12px] font-medium text-emerald-300 transition hover:bg-emerald-600/30 disabled:cursor-not-allowed disabled:opacity-50"
className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--color-status-success)]/15 px-3.5 py-1.5 text-[12px] font-medium text-[var(--color-status-success)] transition-all duration-200 hover:bg-[var(--color-status-success)]/25 disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResolving}
onClick={() => onResolve('approved', true)}
title={`Auto-approve "${approvalToolLabel}" for the rest of this session`}
@@ -106,7 +106,7 @@ export function ApprovalBanner({
</button>
)}
<button
className="inline-flex items-center gap-1.5 rounded-lg bg-zinc-800 px-3.5 py-1.5 text-[12px] font-medium text-zinc-300 transition hover:bg-zinc-700 hover:text-white disabled:cursor-not-allowed disabled:opacity-50"
className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--color-surface-2)] px-3.5 py-1.5 text-[12px] font-medium text-[var(--color-text-secondary)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)] disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResolving}
onClick={() => onResolve('rejected')}
type="button"
@@ -115,7 +115,7 @@ export function ApprovalBanner({
Reject
</button>
{showPosition && (
<span className="ml-auto text-[10px] text-zinc-600">
<span className="ml-auto text-[10px] text-[var(--color-text-muted)]">
Next approval will appear after this one is resolved
</span>
)}
@@ -130,42 +130,42 @@ export function QueuedApprovalsList({ approvals }: { approvals: PendingApprovalR
const [expanded, setExpanded] = useState(false);
return (
<div className="rounded-lg border border-zinc-800 bg-zinc-900/40 px-3 py-2">
<div className="rounded-lg border border-[var(--color-border)] bg-[var(--color-glass)] px-3 py-2">
<button
aria-expanded={expanded}
className="flex w-full items-center gap-2 text-left"
onClick={() => setExpanded(!expanded)}
type="button"
>
<ShieldCheck className="size-3 text-zinc-500" />
<span className="text-[11px] font-medium text-zinc-400">
<ShieldCheck className="size-3 text-[var(--color-text-muted)]" />
<span className="text-[11px] font-medium text-[var(--color-text-secondary)]">
{approvals.length} queued approval{approvals.length === 1 ? '' : 's'}
</span>
<ChevronDown
className={`ml-auto size-3 text-zinc-600 transition-transform ${expanded ? 'rotate-180' : ''}`}
className={`ml-auto size-3 text-[var(--color-text-muted)] transition-transform ${expanded ? 'rotate-180' : ''}`}
/>
</button>
{expanded && (
<div className="mt-2 space-y-1.5 border-t border-zinc-800/60 pt-2">
<div className="mt-2 space-y-1.5 border-t border-[var(--color-border-subtle)] pt-2">
{approvals.map((approval) => {
const kindLabel = approval.kind === 'final-response' ? 'response' : 'tool';
return (
<div
className="flex items-center gap-2 rounded-md bg-zinc-800/40 px-2.5 py-1.5"
className="flex items-center gap-2 rounded-md bg-[var(--color-surface-2)]/40 px-2.5 py-1.5"
key={approval.id}
>
<ShieldAlert className="size-3 shrink-0 text-zinc-600" />
<span className="min-w-0 flex-1 truncate text-[11px] text-zinc-400">
<ShieldAlert className="size-3 shrink-0 text-[var(--color-text-muted)]" />
<span className="min-w-0 flex-1 truncate text-[11px] text-[var(--color-text-secondary)]">
{(approval.permissionDetail && permissionDetailSummary(approval.permissionDetail)) || approval.title}
</span>
<span className="shrink-0 rounded-full bg-zinc-800 px-1.5 py-0.5 text-[8px] font-semibold uppercase tracking-wider text-zinc-500">
<span className="shrink-0 rounded-full bg-[var(--color-surface-2)] px-1.5 py-0.5 text-[8px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
{kindLabel}
</span>
{approval.toolName && (
<span className="shrink-0 text-[10px] text-zinc-500">{approval.toolName}</span>
<span className="shrink-0 text-[10px] text-[var(--color-text-muted)]">{approval.toolName}</span>
)}
{approval.agentName && (
<span className="shrink-0 text-[10px] text-zinc-600">{approval.agentName}</span>
<span className="shrink-0 text-[10px] text-[var(--color-text-muted)]">{approval.agentName}</span>
)}
</div>
);
@@ -0,0 +1,212 @@
import { useState, useMemo } from 'react';
import { ChevronRight, FileCode2, FilePlus2 } from 'lucide-react';
import type { ToolCallFileChangePreview } from '@shared/contracts/sidecar';
/* ── Diff stat helpers ─────────────────────────────────────── */
interface DiffStats {
additions: number;
deletions: number;
}
function parseDiffStats(diff: string | undefined): DiffStats {
if (!diff) return { additions: 0, deletions: 0 };
let additions = 0;
let deletions = 0;
for (const line of diff.split('\n')) {
if (line.startsWith('+') && !line.startsWith('+++')) additions++;
else if (line.startsWith('-') && !line.startsWith('---')) deletions++;
}
return { additions, deletions };
}
function fileBaseName(path: string): string {
const normalized = path.replace(/\\/g, '/');
const lastSlash = normalized.lastIndexOf('/');
return lastSlash >= 0 ? normalized.slice(lastSlash + 1) : normalized;
}
function fileDir(path: string): string {
const normalized = path.replace(/\\/g, '/');
const lastSlash = normalized.lastIndexOf('/');
return lastSlash > 0 ? normalized.slice(0, lastSlash + 1) : '';
}
/* ── Mini diff-stats bar (GitHub-style) ────────────────────── */
function DiffStatsBar({ additions, deletions }: DiffStats) {
const total = additions + deletions;
if (total === 0) return null;
const blocks = 5;
const addBlocks = Math.max(additions > 0 ? 1 : 0, Math.round((additions / total) * blocks));
const delBlocks = blocks - addBlocks;
return (
<span className="inline-flex gap-px" aria-label={`${additions} additions, ${deletions} deletions`}>
{Array.from({ length: addBlocks }, (_, i) => (
<span key={`a${i}`} className="size-1.5 rounded-[1px] bg-[var(--color-status-success)]" />
))}
{Array.from({ length: delBlocks }, (_, i) => (
<span key={`d${i}`} className="size-1.5 rounded-[1px] bg-[var(--color-status-error)]" />
))}
</span>
);
}
/* ── Diff line renderer ────────────────────────────────────── */
function DiffLine({ line }: { line: string }) {
let textClass = 'text-[var(--color-text-secondary)]';
let bgClass = '';
if (line.startsWith('+') && !line.startsWith('+++')) {
textClass = 'text-[var(--color-status-success)]';
bgClass = 'bg-[var(--color-status-success)]/[0.06]';
} else if (line.startsWith('-') && !line.startsWith('---')) {
textClass = 'text-[var(--color-status-error)]';
bgClass = 'bg-[var(--color-status-error)]/[0.06]';
} else if (line.startsWith('@@')) {
textClass = 'text-[var(--color-accent-sky)]';
} else if (line.startsWith('diff ') || line.startsWith('index ') || line.startsWith('---') || line.startsWith('+++')) {
textClass = 'text-[var(--color-text-muted)]';
}
return <div className={`${textClass} ${bgClass} -mx-3 px-3`}>{line || '\u00A0'}</div>;
}
/* ── Individual file entry ─────────────────────────────────── */
function FileChangeEntry({ file }: { file: ToolCallFileChangePreview }) {
const [expanded, setExpanded] = useState(false);
const isNewFile = !file.diff && !!file.newFileContents;
const stats = useMemo(() => parseDiffStats(file.diff), [file.diff]);
const hasContent = !!file.diff || !!file.newFileContents;
const dir = fileDir(file.path);
const base = fileBaseName(file.path);
return (
<div className="border-b border-[var(--color-border-subtle)] last:border-b-0">
<button
className="flex w-full items-center gap-1.5 px-2 py-[5px] text-left text-[10px] transition-colors duration-150 hover:bg-[var(--color-surface-3)]/40 disabled:cursor-default"
disabled={!hasContent}
onClick={hasContent ? () => setExpanded(!expanded) : undefined}
type="button"
aria-expanded={hasContent ? expanded : undefined}
>
{hasContent ? (
<ChevronRight
className={`size-2.5 shrink-0 text-[var(--color-text-muted)] transition-transform duration-150 ${expanded ? 'rotate-90' : ''}`}
/>
) : (
<span className="w-2.5 shrink-0" />
)}
{isNewFile
? <FilePlus2 className="size-3 shrink-0 text-[var(--color-status-success)]" />
: <FileCode2 className="size-3 shrink-0 text-[var(--color-accent-sky)]" />}
<span className="min-w-0 flex-1 truncate font-mono">
{dir && <span className="text-[var(--color-text-muted)]">{dir}</span>}
<span className="text-[var(--color-text-primary)]">{base}</span>
</span>
{isNewFile ? (
<span className="shrink-0 rounded px-1 py-px text-[8px] font-semibold uppercase tracking-wider bg-[var(--color-status-success)]/10 text-[var(--color-status-success)]">
new
</span>
) : (stats.additions > 0 || stats.deletions > 0) ? (
<span className="flex items-center gap-1.5 shrink-0">
<span className="flex items-center gap-0.5 font-mono">
{stats.additions > 0 && <span className="text-[var(--color-status-success)]">+{stats.additions}</span>}
{stats.deletions > 0 && <span className="text-[var(--color-status-error)]">{stats.deletions}</span>}
</span>
<DiffStatsBar additions={stats.additions} deletions={stats.deletions} />
</span>
) : null}
</button>
{expanded && (
<div className="border-t border-[var(--color-border-subtle)]">
<pre className="max-h-64 overflow-auto bg-[var(--color-surface-0)] px-3 py-1.5 font-mono text-[10px] leading-relaxed">
{file.diff
? file.diff.split('\n').map((line, i) => <DiffLine key={i} line={line} />)
: file.newFileContents!.split('\n').map((line, i) => (
<div key={i} className="text-[var(--color-text-secondary)]">{line || '\u00A0'}</div>
))}
</pre>
</div>
)}
</div>
);
}
/* ── Main export ───────────────────────────────────────────── */
interface FileChangePreviewProps {
fileChanges: ToolCallFileChangePreview[];
}
export function FileChangePreview({ fileChanges }: FileChangePreviewProps) {
const [expanded, setExpanded] = useState(false);
const totalStats = useMemo(() => {
let additions = 0;
let deletions = 0;
let newFiles = 0;
for (const fc of fileChanges) {
if (!fc.diff && fc.newFileContents) {
newFiles++;
} else {
const s = parseDiffStats(fc.diff);
additions += s.additions;
deletions += s.deletions;
}
}
return { additions, deletions, newFiles };
}, [fileChanges]);
const fileWord = fileChanges.length === 1 ? 'file' : 'files';
return (
<div className="mt-1 overflow-hidden rounded-md border border-[var(--color-border-subtle)] bg-[var(--color-surface-1)]/60">
<button
className="flex w-full items-center gap-1.5 px-2 py-1 text-left text-[10px] font-medium text-[var(--color-text-muted)] transition-colors duration-150 hover:bg-[var(--color-surface-2)]/40 hover:text-[var(--color-text-secondary)]"
onClick={() => setExpanded(!expanded)}
type="button"
aria-expanded={expanded}
aria-label={`${fileChanges.length} file changes`}
>
<ChevronRight
className={`size-2.5 shrink-0 transition-transform duration-150 ${expanded ? 'rotate-90' : ''}`}
/>
<span>{fileChanges.length} {fileWord} changed</span>
{(totalStats.additions > 0 || totalStats.deletions > 0) && (
<span className="ml-auto flex shrink-0 items-center gap-1.5 font-mono">
{totalStats.additions > 0 && (
<span className="text-[var(--color-status-success)]">+{totalStats.additions}</span>
)}
{totalStats.deletions > 0 && (
<span className="text-[var(--color-status-error)]">{totalStats.deletions}</span>
)}
<DiffStatsBar additions={totalStats.additions} deletions={totalStats.deletions} />
</span>
)}
{totalStats.newFiles > 0 && (
<span className={`shrink-0 rounded px-1 py-px text-[8px] font-semibold uppercase tracking-wider bg-[var(--color-status-success)]/10 text-[var(--color-status-success)] ${totalStats.additions === 0 && totalStats.deletions === 0 ? 'ml-auto' : ''}`}>
{totalStats.newFiles} new
</span>
)}
</button>
{expanded && (
<div className="border-t border-[var(--color-border-subtle)]">
{fileChanges.map((fc) => (
<FileChangeEntry file={fc} key={fc.path} />
))}
</div>
)}
</div>
);
}
+328 -85
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';
@@ -14,9 +15,9 @@ import { RotateCcw, Server, ShieldCheck } from 'lucide-react';
function TierBadge({ tier }: { tier: ModelDefinition['tier'] }) {
if (!tier) return null;
const styles = {
premium: 'bg-amber-500/10 text-amber-400',
standard: 'bg-zinc-700/50 text-zinc-500',
fast: 'bg-emerald-500/10 text-emerald-400',
premium: 'bg-[var(--color-status-warning)]/10 text-[var(--color-status-warning)]',
standard: 'bg-[var(--color-surface-3)]/50 text-[var(--color-text-muted)]',
fast: 'bg-[var(--color-status-success)]/10 text-[var(--color-status-success)]',
};
return (
<span className={`ml-auto rounded px-1.5 py-0.5 text-[9px] font-medium ${styles[tier]}`}>
@@ -63,10 +64,10 @@ export function InlineModelPill({
<button
aria-expanded={open}
aria-haspopup="listbox"
className={`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-pill font-medium transition ${
className={`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-pill font-medium transition-all duration-200 ${
open
? 'border-indigo-500/40 bg-indigo-500/10 text-indigo-300'
: 'border-zinc-700/60 bg-zinc-800/40 text-zinc-400 hover:border-zinc-600 hover:text-zinc-300'
? 'border-[var(--color-border-glow)] bg-[var(--color-accent-muted)] text-[var(--color-text-accent)]'
: 'border-[var(--color-border-subtle)] bg-[var(--color-surface-2)]/40 text-[var(--color-text-secondary)] hover:border-[var(--color-border)] hover:text-[var(--color-text-primary)]'
} disabled:cursor-not-allowed disabled:opacity-50`}
disabled={disabled}
onClick={() => setOpen(!open)}
@@ -78,19 +79,19 @@ export function InlineModelPill({
</button>
{open && !disabled && (
<div className="absolute bottom-full right-0 z-40 mb-1.5 max-h-72 w-64 overflow-y-auto rounded-lg border border-zinc-700 bg-zinc-900 py-1 shadow-2xl" role="listbox">
<div className="absolute bottom-full right-0 z-40 mb-1.5 max-h-72 w-64 overflow-y-auto rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] py-1 shadow-2xl" role="listbox">
{groupedModels.map((pg) => (
<div key={pg.id}>
<div className="flex items-center gap-2 px-3 pb-1 pt-2.5">
<ProviderIcon provider={pg.id} className="size-3.5" />
<span className="text-[10px] font-semibold uppercase tracking-wider text-zinc-500">
<span className="text-[10px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
{pg.label}
</span>
</div>
{pg.models.map((model) => (
<button
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-[13px] transition hover:bg-zinc-800 ${
model.id === value ? 'bg-indigo-500/10 text-indigo-200' : 'text-zinc-300'
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-[13px] transition-all duration-200 hover:bg-[var(--color-surface-3)] ${
model.id === value ? 'bg-[var(--color-accent-muted)] text-[var(--color-text-accent)]' : 'text-[var(--color-text-primary)]'
}`}
key={model.id}
onClick={() => { onChange(model.id); setOpen(false); }}
@@ -106,13 +107,13 @@ export function InlineModelPill({
))}
{otherModels.length > 0 && (
<div>
<div className="px-3 pb-1 pt-2.5 text-[10px] font-semibold uppercase tracking-wider text-zinc-500">
<div className="px-3 pb-1 pt-2.5 text-[10px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
Other
</div>
{otherModels.map((model) => (
<button
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-[13px] transition hover:bg-zinc-800 ${
model.id === value ? 'bg-indigo-500/10 text-indigo-200' : 'text-zinc-300'
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-[13px] transition-all duration-200 hover:bg-[var(--color-surface-3)] ${
model.id === value ? 'bg-[var(--color-accent-muted)] text-[var(--color-text-accent)]' : 'text-[var(--color-text-primary)]'
}`}
key={model.id}
onClick={() => { onChange(model.id); setOpen(false); }}
@@ -154,7 +155,7 @@ export function InlineThinkingPill({
if (supportedEfforts && supportedEfforts.length === 0) {
return (
<span className="inline-flex items-center gap-1 rounded border border-zinc-800/40 bg-zinc-800/20 px-1.5 py-0.5 text-pill text-zinc-600">
<span className="inline-flex items-center gap-1 rounded border border-[var(--color-border-subtle)] bg-[var(--color-surface-2)]/20 px-1.5 py-0.5 text-pill text-[var(--color-text-muted)]">
<Sparkles className="size-2.5" />
N/A
</span>
@@ -168,10 +169,10 @@ export function InlineThinkingPill({
<button
aria-expanded={open}
aria-haspopup="listbox"
className={`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-pill font-medium transition ${
className={`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-pill font-medium transition-all duration-200 ${
open
? 'border-indigo-500/40 bg-indigo-500/10 text-indigo-300'
: 'border-zinc-700/60 bg-zinc-800/40 text-zinc-400 hover:border-zinc-600 hover:text-zinc-300'
? 'border-[var(--color-border-glow)] bg-[var(--color-accent-muted)] text-[var(--color-text-accent)]'
: 'border-[var(--color-border-subtle)] bg-[var(--color-surface-2)]/40 text-[var(--color-text-secondary)] hover:border-[var(--color-border)] hover:text-[var(--color-text-primary)]'
} disabled:cursor-not-allowed disabled:opacity-50`}
disabled={disabled}
onClick={() => setOpen(!open)}
@@ -183,11 +184,11 @@ export function InlineThinkingPill({
</button>
{open && !disabled && (
<div className="absolute bottom-full right-0 z-40 mb-1.5 w-36 overflow-hidden rounded-lg border border-zinc-700 bg-zinc-900 py-1 shadow-2xl" role="listbox">
<div className="absolute bottom-full right-0 z-40 mb-1.5 w-36 overflow-hidden rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] py-1 shadow-2xl" role="listbox">
{options.map((option) => (
<button
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-[13px] transition hover:bg-zinc-800 ${
option.value === value ? 'bg-indigo-500/10 text-indigo-200' : 'text-zinc-300'
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-[13px] transition-all duration-200 hover:bg-[var(--color-surface-3)] ${
option.value === value ? 'bg-[var(--color-accent-muted)] text-[var(--color-text-accent)]' : 'text-[var(--color-text-primary)]'
}`}
key={option.value}
onClick={() => { onChange(option.value); setOpen(false); }}
@@ -234,10 +235,10 @@ export function InlineToolsPill({
<button
aria-expanded={open}
aria-haspopup="listbox"
className={`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-pill font-medium transition ${
className={`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-pill font-medium transition-all duration-200 ${
open
? 'border-indigo-500/40 bg-indigo-500/10 text-indigo-300'
: 'border-zinc-700/60 bg-zinc-800/40 text-zinc-400 hover:border-zinc-600 hover:text-zinc-300'
? 'border-[var(--color-border-glow)] bg-[var(--color-accent-muted)] text-[var(--color-text-accent)]'
: 'border-[var(--color-border-subtle)] bg-[var(--color-surface-2)]/40 text-[var(--color-text-secondary)] hover:border-[var(--color-border)] hover:text-[var(--color-text-primary)]'
} disabled:cursor-not-allowed disabled:opacity-50`}
disabled={disabled}
onClick={() => setOpen(!open)}
@@ -249,7 +250,7 @@ export function InlineToolsPill({
</button>
{open && !disabled && (
<div className="absolute bottom-full left-0 z-40 mb-1.5 w-64 overflow-y-auto rounded-lg border border-zinc-700 bg-zinc-900 py-1 shadow-2xl">
<div className="absolute bottom-full left-0 z-40 mb-1.5 w-64 overflow-y-auto rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] py-1 shadow-2xl">
{workspaceMcpServers.length > 0 && (
<McpServerGroup
label="Workspace MCP"
@@ -276,7 +277,7 @@ export function InlineToolsPill({
)}
{lspProfiles.length > 0 && (
<div>
<div className="px-3 pb-1 pt-2 text-[9px] font-semibold uppercase tracking-wider text-zinc-600">
<div className="px-3 pb-1 pt-2 text-[9px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
Language Servers
</div>
{lspProfiles.map((profile) => (
@@ -314,7 +315,7 @@ function McpServerGroup({
}) {
return (
<div>
<div className="px-3 pb-1 pt-2 text-[9px] font-semibold uppercase tracking-wider text-zinc-600">
<div className="px-3 pb-1 pt-2 text-[9px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
{label}
</div>
{servers.map((server) => (
@@ -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,79 +407,288 @@ 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}>
<button
aria-expanded={open}
aria-haspopup="listbox"
className={`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-pill font-medium transition ${
className={`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-pill font-medium transition-all duration-200 ${
open
? 'border-indigo-500/40 bg-indigo-500/10 text-indigo-300'
? 'border-[var(--color-border-glow)] bg-[var(--color-accent-muted)] text-[var(--color-text-accent)]'
: isOverridden
? 'border-amber-500/30 bg-amber-500/5 text-amber-400 hover:border-amber-500/50'
: 'border-zinc-700/60 bg-zinc-800/40 text-zinc-400 hover:border-zinc-600 hover:text-zinc-300'
? 'border-[var(--color-status-warning)]/30 bg-[var(--color-status-warning)]/5 text-[var(--color-status-warning)] hover:border-[var(--color-status-warning)]/50'
: 'border-[var(--color-border-subtle)] bg-[var(--color-surface-2)]/40 text-[var(--color-text-secondary)] hover:border-[var(--color-border)] hover:text-[var(--color-text-primary)]'
} disabled:cursor-not-allowed disabled:opacity-50`}
disabled={disabled}
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-[var(--color-text-muted)]"> · 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-[var(--color-border)] bg-[var(--color-surface-1)] shadow-2xl">
{/* Header: session override / pattern defaults */}
<div className="sticky top-0 z-10 border-b border-[var(--color-border)] bg-[var(--color-surface-1)]">
<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-[var(--color-status-warning)]/15 text-[var(--color-status-warning)]'
: 'bg-[var(--color-surface-2)] text-[var(--color-text-muted)]'
}`}>
{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-[var(--color-text-muted)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]"
onClick={() => onUpdate({})}
type="button"
>
<RotateCcw className="size-2.5" />
Reset
</button>
)}
</div>
{/* Search */}
{showSearch && (
<div className="border-t border-[var(--color-border-subtle)] px-3 py-1.5">
<div className="flex items-center gap-2 rounded border border-[var(--color-border)] bg-[var(--color-surface-2)]/30 px-2 py-1">
<Search className="size-3 shrink-0 text-[var(--color-text-muted)]" />
<input
autoFocus
className="w-full bg-transparent text-[12px] text-[var(--color-text-primary)] placeholder-[var(--color-text-muted)] 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-[var(--color-text-muted)]`}>
{group.label}
</div>
) : (
<div
className={`flex w-full cursor-pointer items-center gap-1.5 px-2.5 py-1.5 text-left transition-all duration-200 hover:bg-[var(--color-surface-3)]/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-[var(--color-text-accent)]" aria-label="Probing server" />
) : group.tools.length > 0 ? (
<ChevronRight className={`size-3 shrink-0 text-[var(--color-text-muted)] transition ${expanded ? 'rotate-90' : ''}`} />
) : (
<Server className="size-3 shrink-0 text-[var(--color-text-muted)]" />
)}
<span className="min-w-0 flex-1 truncate text-[12px] font-medium text-[var(--color-text-primary)]">{group.label}</span>
{probing ? (
<span className="shrink-0 rounded-full bg-[var(--color-accent-muted)] px-1.5 py-px text-[9px] font-medium text-[var(--color-text-accent)]">
probing
</span>
) : (
<span className="shrink-0 rounded-full bg-[var(--color-surface-2)]/80 px-1.5 py-px text-[9px] font-medium tabular-nums text-[var(--color-text-muted)]">
{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-[var(--color-text-muted)]">
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-[var(--color-accent)]' : someApproved ? 'bg-[var(--color-surface-3)]' : 'bg-[var(--color-surface-3)]'
}`}
onClick={onToggle}
type="button"
>
{someApproved ? (
<Minus className="absolute left-1/2 size-2 -translate-x-1/2 text-[var(--color-text-primary)]" 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-all duration-200 ${
isOpen
? 'bg-[var(--color-accent-muted)] text-[var(--color-text-accent)] hover:bg-[var(--color-accent)]/20'
: 'text-[var(--color-text-muted)] hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]'
} disabled:cursor-not-allowed disabled:opacity-50`}
disabled={disabled}
onClick={onToggle}
type="button"
>
{isRunning && <span className="size-1.5 shrink-0 rounded-full bg-[var(--color-status-success)]" />}
<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-[var(--color-text-muted)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]"
disabled={disabled}
onClick={() => setOpen(!open)}
type="button"
>
<FileText className="size-3" />
Prompts
<span className="text-[var(--color-text-muted)]">({promptFiles.length})</span>
</button>
{open && !disabled && (
<div
className="absolute bottom-full left-0 z-40 mb-1.5 w-80 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] 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-[var(--color-text-muted)]">
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-all duration-200 hover:bg-[var(--color-surface-3)]"
onClick={() => onSelect(prompt)}
role="option"
type="button"
>
<FileText className="mt-0.5 size-3.5 shrink-0 text-[var(--color-text-muted)]" />
<div className="min-w-0 flex-1">
<div className="truncate text-[12px] font-medium text-[var(--color-text-primary)]">
{prompt.name}
</div>
{prompt.description && (
<div className="mt-0.5 truncate text-[11px] text-[var(--color-text-muted)]">
{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-[var(--color-surface-2)] px-1.5 py-0.5 text-[10px] text-[var(--color-text-muted)]"
>
{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-[var(--color-text-muted)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]"
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-[var(--color-text-primary)]">
{prompt.name}
</div>
{prompt.description && (
<div className="truncate text-[10px] text-[var(--color-text-muted)]">{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-all duration-200 ${
submitDisabled
? 'bg-[var(--color-surface-2)] text-[var(--color-text-muted)]'
: 'brand-gradient-bg text-white hover:brightness-110'
}`}
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-[var(--color-text-secondary)]">
{variable.name}
</label>
<input
className="w-full rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-2)] px-2.5 py-1.5 text-[12px] text-[var(--color-text-primary)] placeholder-[var(--color-text-muted)] transition-all duration-200 focus:border-[var(--color-border-glow)] 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>
);
}
+11 -11
View File
@@ -24,20 +24,20 @@ export function McpAuthBanner({
const hasFailed = mcpAuth.status === 'failed';
return (
<div className="rounded-xl border border-amber-500/30 bg-amber-500/5 px-4 py-3" role="alert">
<div className="rounded-xl border border-[var(--color-glass-border)] border-l-4 border-l-[var(--color-status-warning)] bg-[var(--color-glass)] px-4 py-3" role="alert">
<div className="flex items-start gap-2.5">
<KeyRound className="mt-0.5 size-4 shrink-0 text-amber-400" />
<KeyRound className="mt-0.5 size-4 shrink-0 text-[var(--color-status-warning)]" />
<div className="min-w-0 flex-1">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<span className="text-[13px] font-semibold text-amber-200">Authentication required</span>
<span className="rounded-full bg-amber-500/15 px-2 py-0.5 text-[9px] font-semibold uppercase tracking-wider text-amber-400">
<span className="text-[13px] font-semibold text-[var(--color-status-warning)]">Authentication required</span>
<span className="rounded-full bg-[var(--color-status-warning)]/15 px-2 py-0.5 text-[9px] font-semibold uppercase tracking-wider text-[var(--color-status-warning)]">
MCP
</span>
</div>
<button
aria-label="Dismiss authentication prompt"
className="rounded p-0.5 text-zinc-500 transition hover:bg-zinc-700/50 hover:text-zinc-300"
className="rounded p-0.5 text-[var(--color-text-muted)] transition-all duration-200 hover:bg-[var(--color-surface-3)]/50 hover:text-[var(--color-text-primary)]"
onClick={handleDismiss}
type="button"
>
@@ -45,21 +45,21 @@ export function McpAuthBanner({
</button>
</div>
<p className="mt-2 text-[13px] leading-relaxed text-zinc-200">
<p className="mt-2 text-[13px] leading-relaxed text-[var(--color-text-primary)]">
The MCP server{' '}
<span className="font-medium text-amber-200">{mcpAuth.serverName}</span>{' '}
<span className="font-medium text-[var(--color-status-warning)]">{mcpAuth.serverName}</span>{' '}
requires OAuth authentication to connect.
</p>
<p className="mt-1 text-[11px] text-zinc-500">{mcpAuth.serverUrl}</p>
<p className="mt-1 text-[11px] text-[var(--color-text-muted)]">{mcpAuth.serverUrl}</p>
{hasFailed && mcpAuth.errorMessage && (
<p className="mt-2 text-[12px] text-red-400">{mcpAuth.errorMessage}</p>
<p className="mt-2 text-[12px] text-[var(--color-status-error)]">{mcpAuth.errorMessage}</p>
)}
<div className="mt-3 flex items-center gap-3">
<button
className="inline-flex items-center gap-1.5 rounded-lg bg-amber-500/20 px-3 py-1.5 text-[12px] font-medium text-amber-200 transition hover:bg-amber-500/30 disabled:opacity-50"
className="brand-gradient-bg inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[12px] font-medium text-white transition-all duration-200 hover:brightness-110 disabled:opacity-50"
disabled={isAuthenticating}
onClick={handleAuthenticate}
type="button"
@@ -75,7 +75,7 @@ export function McpAuthBanner({
'Authenticate in browser'
)}
</button>
<span className="text-[11px] text-zinc-500">
<span className="text-[11px] text-[var(--color-text-muted)]">
{isAuthenticating
? 'Waiting for consent in the browser…'
: 'Opens your browser for OAuth consent. Token is stored for this session only.'}
@@ -0,0 +1,113 @@
import { useState } from 'react';
import { Bookmark, Check, ClipboardCopy, GitBranch, Pencil, RefreshCw } from 'lucide-react';
import type { ChatMessageRecord } from '@shared/domain/session';
export interface MessageActionsProps {
message: ChatMessageRecord;
isLastAssistant: boolean;
onCopy: () => void;
onPin: () => void;
onBranch: () => void;
onRegenerate?: () => void;
onEdit?: () => void;
}
export function MessageActions({
message,
isLastAssistant,
onCopy,
onPin,
onBranch,
onRegenerate,
onEdit,
}: MessageActionsProps) {
const [copied, setCopied] = useState(false);
const isUser = message.role === 'user';
const isPinned = !!message.isPinned;
function handleCopy() {
onCopy();
setCopied(true);
setTimeout(() => setCopied(false), 1800);
}
return (
<div
className="msg-actions-enter flex items-center gap-0.5 rounded-lg border border-[var(--color-border-subtle)] bg-[var(--color-surface-1)]/90 px-1 py-0.5 opacity-0 shadow-sm backdrop-blur-sm transition-opacity duration-150 group-hover:opacity-100"
role="toolbar"
aria-label="Message actions"
>
{/* Copy */}
<ActionButton
icon={copied ? <Check className="size-3 text-[var(--color-status-success)]" /> : <ClipboardCopy className="size-3" />}
label={copied ? 'Copied' : 'Copy as markdown'}
onClick={handleCopy}
/>
{/* Pin / Unpin */}
<ActionButton
icon={
<Bookmark
className={`size-3 ${isPinned ? 'fill-[var(--color-accent-sky)] text-[var(--color-accent-sky)]' : ''}`}
/>
}
label={isPinned ? 'Unpin message' : 'Pin message'}
onClick={onPin}
active={isPinned}
/>
{/* Edit (user messages only) */}
{isUser && onEdit && (
<ActionButton
icon={<Pencil className="size-3" />}
label="Edit &amp; resend"
onClick={onEdit}
/>
)}
{/* Regenerate (last assistant only) */}
{!isUser && isLastAssistant && onRegenerate && (
<ActionButton
icon={<RefreshCw className="size-3" />}
label="Regenerate response"
onClick={onRegenerate}
/>
)}
{/* Branch */}
<ActionButton
icon={<GitBranch className="size-3" />}
label={isUser ? 'Branch from this message' : 'Branch from this response'}
onClick={onBranch}
/>
</div>
);
}
/* ── Small action button ────────────────────────────────────── */
interface ActionButtonProps {
icon: React.ReactNode;
label: string;
onClick: () => void;
active?: boolean;
}
function ActionButton({ icon, label, onClick, active }: ActionButtonProps) {
return (
<button
aria-label={label}
className={`flex size-6 items-center justify-center rounded-md transition-all duration-100 ${
active
? 'text-[var(--color-accent-sky)]'
: 'text-[var(--color-text-muted)] hover:bg-[var(--color-surface-2)] hover:text-[var(--color-text-primary)]'
}`}
onClick={onClick}
title={label}
type="button"
>
{icon}
</button>
);
}
@@ -0,0 +1,81 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { Check, X } from 'lucide-react';
export interface MessageEditComposerProps {
initialContent: string;
onSave: (content: string) => void;
onCancel: () => void;
}
export function MessageEditComposer({ initialContent, onSave, onCancel }: MessageEditComposerProps) {
const [content, setContent] = useState(initialContent);
const textareaRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
const ta = textareaRef.current;
if (!ta) return;
ta.focus();
ta.setSelectionRange(ta.value.length, ta.value.length);
resizeTextarea(ta);
}, []);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (e.key === 'Escape') {
e.preventDefault();
onCancel();
}
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
const trimmed = content.trim();
if (trimmed) onSave(trimmed);
}
},
[content, onCancel, onSave],
);
function resizeTextarea(el: HTMLTextAreaElement) {
el.style.height = 'auto';
el.style.height = `${Math.min(el.scrollHeight, 300)}px`;
}
const canSave = content.trim().length > 0 && content.trim() !== initialContent.trim();
return (
<div className="msg-actions-enter">
<textarea
ref={textareaRef}
className="w-full resize-none rounded-lg border border-[var(--color-border-glow)] bg-[var(--color-surface-0)] px-3 py-2 text-[14px] leading-relaxed text-[var(--color-text-primary)] outline-none transition-colors focus:border-[var(--color-accent)]/50"
onChange={(e) => {
setContent(e.target.value);
resizeTextarea(e.target);
}}
onKeyDown={handleKeyDown}
rows={1}
value={content}
/>
<div className="mt-1.5 flex items-center gap-1.5">
<button
className="flex items-center gap-1 rounded-md bg-[var(--color-accent)] px-2.5 py-1 text-[11px] font-medium text-white transition-all duration-150 hover:bg-[var(--color-accent-hover)] disabled:cursor-not-allowed disabled:opacity-40"
disabled={!canSave}
onClick={() => onSave(content.trim())}
type="button"
>
<Check className="size-3" />
Save &amp; Resend
</button>
<button
className="flex items-center gap-1 rounded-md px-2.5 py-1 text-[11px] font-medium text-[var(--color-text-secondary)] transition-all duration-150 hover:bg-[var(--color-surface-2)] hover:text-[var(--color-text-primary)]"
onClick={onCancel}
type="button"
>
<X className="size-3" />
Cancel
</button>
<span className="ml-auto text-[10px] text-[var(--color-text-muted)]">
Ctrl+Enter to save · Esc to cancel
</span>
</div>
</div>
);
}
@@ -68,7 +68,7 @@ function ShellDetail({ detail }: { detail: PermissionDetail }) {
<div className="mt-2.5 space-y-2">
{detail.intention && <IntentionLine text={detail.intention} />}
{detail.warning && (
<div className="flex items-start gap-1.5 rounded-md bg-red-500/10 px-2.5 py-1.5 text-[11px] text-red-300">
<div className="flex items-start gap-1.5 rounded-md bg-[var(--color-status-error)]/10 px-2.5 py-1.5 text-[11px] text-[var(--color-status-error)]">
<AlertTriangle className="mt-0.5 size-3 shrink-0" />
<span>{detail.warning}</span>
</div>
@@ -89,8 +89,8 @@ function WriteDetail({ detail }: { detail: PermissionDetail }) {
<div className="mt-2.5 space-y-2">
{detail.intention && <IntentionLine text={detail.intention} />}
{detail.fileName && (
<div className="flex items-center gap-1.5 text-[11px] text-zinc-300">
<FileEdit className="size-3 shrink-0 text-zinc-500" />
<div className="flex items-center gap-1.5 text-[11px] text-[var(--color-text-primary)]">
<FileEdit className="size-3 shrink-0 text-[var(--color-text-muted)]" />
<code className="font-mono">{detail.fileName}</code>
</div>
)}
@@ -107,8 +107,8 @@ function ReadDetail({ detail }: { detail: PermissionDetail }) {
<div className="mt-2.5 space-y-2">
{detail.intention && <IntentionLine text={detail.intention} />}
{detail.path && (
<div className="flex items-center gap-1.5 text-[11px] text-zinc-300">
<FileText className="size-3 shrink-0 text-zinc-500" />
<div className="flex items-center gap-1.5 text-[11px] text-[var(--color-text-primary)]">
<FileText className="size-3 shrink-0 text-[var(--color-text-muted)]" />
<code className="font-mono">{detail.path}</code>
</div>
)}
@@ -121,14 +121,14 @@ function McpDetail({ detail }: { detail: PermissionDetail }) {
<div className="mt-2.5 space-y-2">
<div className="flex flex-wrap items-center gap-2 text-[11px]">
{detail.serverName && (
<span className="inline-flex items-center gap-1 rounded-full bg-indigo-500/15 px-2 py-0.5 text-indigo-300">
<span className="inline-flex items-center gap-1 rounded-full bg-[var(--color-accent-muted)] px-2 py-0.5 text-[var(--color-text-accent)]">
<Server className="size-2.5" />
{detail.serverName}
</span>
)}
{detail.toolTitle && <span className="text-zinc-300">{detail.toolTitle}</span>}
{detail.toolTitle && <span className="text-[var(--color-text-primary)]">{detail.toolTitle}</span>}
{detail.readOnly && (
<span className="rounded-full bg-emerald-500/15 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wider text-emerald-400">
<span className="rounded-full bg-[var(--color-status-success)]/15 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wider text-[var(--color-status-success)]">
read-only
</span>
)}
@@ -145,10 +145,10 @@ function UrlDetail({ detail }: { detail: PermissionDetail }) {
<div className="mt-2.5 space-y-2">
{detail.intention && <IntentionLine text={detail.intention} />}
{detail.url && (
<div className="flex items-center gap-1.5 rounded-md bg-zinc-800/60 px-2.5 py-1.5 text-[11px] text-blue-300">
<div className="flex items-center gap-1.5 rounded-md bg-[var(--color-surface-2)]/60 px-2.5 py-1.5 text-[11px] text-[var(--color-accent-sky)]">
<Globe className="size-3 shrink-0" />
<code className="min-w-0 flex-1 break-all font-mono">{detail.url}</code>
<ExternalLink className="size-3 shrink-0 text-zinc-500" />
<ExternalLink className="size-3 shrink-0 text-[var(--color-text-muted)]" />
</div>
)}
</div>
@@ -160,18 +160,18 @@ function MemoryDetail({ detail }: { detail: PermissionDetail }) {
<div className="mt-2.5 space-y-1.5">
{detail.subject && (
<div className="flex items-center gap-1.5 text-[11px]">
<BookOpen className="size-3 shrink-0 text-zinc-500" />
<span className="font-medium text-zinc-300">{detail.subject}</span>
<BookOpen className="size-3 shrink-0 text-[var(--color-text-muted)]" />
<span className="font-medium text-[var(--color-text-primary)]">{detail.subject}</span>
</div>
)}
{detail.fact && (
<p className="rounded-md bg-zinc-800/60 px-2.5 py-1.5 text-[11px] leading-relaxed text-zinc-300">
<p className="rounded-md bg-[var(--color-surface-2)]/60 px-2.5 py-1.5 text-[11px] leading-relaxed text-[var(--color-text-primary)]">
{detail.fact}
</p>
)}
{detail.citations && (
<p className="text-[10px] text-zinc-500">
Source: <span className="text-zinc-400">{detail.citations}</span>
<p className="text-[10px] text-[var(--color-text-muted)]">
Source: <span className="text-[var(--color-text-secondary)]">{detail.citations}</span>
</p>
)}
</div>
@@ -182,7 +182,7 @@ function CustomToolDetail({ detail }: { detail: PermissionDetail }) {
return (
<div className="mt-2.5 space-y-2">
{detail.toolDescription && (
<p className="text-[11px] text-zinc-400">{detail.toolDescription}</p>
<p className="text-[11px] text-[var(--color-text-secondary)]">{detail.toolDescription}</p>
)}
{detail.args && Object.keys(detail.args).length > 0 && (
<CollapsibleCode label="Arguments" text={JSON.stringify(detail.args, null, 2)} />
@@ -195,7 +195,7 @@ function HookDetail({ detail }: { detail: PermissionDetail }) {
return (
<div className="mt-2.5 space-y-2">
{detail.hookMessage && (
<div className="flex items-start gap-1.5 rounded-md bg-amber-500/10 px-2.5 py-1.5 text-[11px] text-amber-200">
<div className="flex items-start gap-1.5 rounded-md bg-[var(--color-status-warning)]/10 px-2.5 py-1.5 text-[11px] text-[var(--color-status-warning)]">
<AlertTriangle className="mt-0.5 size-3 shrink-0" />
<span>{detail.hookMessage}</span>
</div>
@@ -210,12 +210,12 @@ function HookDetail({ detail }: { detail: PermissionDetail }) {
/* ── Shared primitives ──────────────────────────────────────── */
function IntentionLine({ text }: { text: string }) {
return <p className="text-[11px] italic text-zinc-400">{text}</p>;
return <p className="text-[11px] italic text-[var(--color-text-secondary)]">{text}</p>;
}
function CommandBlock({ text }: { text: string }) {
return (
<pre className="overflow-x-auto rounded-md bg-zinc-900/80 px-3 py-2 font-mono text-[11px] leading-relaxed text-emerald-300">
<pre className="overflow-x-auto rounded-md bg-[var(--color-surface-1)] px-3 py-2 font-mono text-[11px] leading-relaxed text-[var(--color-status-success)]">
{text}
</pre>
);
@@ -225,12 +225,12 @@ function DiffBlock({ text }: { text: string }) {
const lines = text.split('\n');
return (
<CollapsibleCode label="Diff" text={text} defaultExpanded>
<pre className="max-h-48 overflow-auto rounded-md bg-zinc-900/80 px-3 py-2 font-mono text-[10px] leading-relaxed">
<pre className="max-h-48 overflow-auto rounded-md bg-[var(--color-surface-1)] px-3 py-2 font-mono text-[10px] leading-relaxed">
{lines.map((line, i) => {
let color = 'text-zinc-400';
if (line.startsWith('+')) color = 'text-emerald-400';
else if (line.startsWith('-')) color = 'text-red-400';
else if (line.startsWith('@@')) color = 'text-blue-400';
let color = 'text-[var(--color-text-secondary)]';
if (line.startsWith('+')) color = 'text-[var(--color-status-success)]';
else if (line.startsWith('-')) color = 'text-[var(--color-status-error)]';
else if (line.startsWith('@@')) color = 'text-[var(--color-accent-sky)]';
return (
<div className={color} key={i}>
{line}
@@ -256,10 +256,10 @@ function CollapsibleCode({
const [expanded, setExpanded] = useState(defaultExpanded);
return (
<div className="rounded-md border border-zinc-800/60 bg-zinc-900/40">
<div className="rounded-md border border-[var(--color-border-subtle)] bg-[var(--color-surface-1)]">
<button
aria-expanded={expanded}
className="flex w-full items-center gap-1.5 px-2.5 py-1.5 text-left text-[10px] font-medium text-zinc-500 hover:text-zinc-400"
className="flex w-full items-center gap-1.5 px-2.5 py-1.5 text-left text-[10px] font-medium text-[var(--color-text-muted)] transition-all duration-200 hover:text-[var(--color-text-secondary)]"
onClick={() => setExpanded(!expanded)}
type="button"
>
@@ -269,9 +269,9 @@ function CollapsibleCode({
{label}
</button>
{expanded && (
<div className="border-t border-zinc-800/40 px-2.5 py-1.5">
<div className="border-t border-[var(--color-border-subtle)] px-2.5 py-1.5">
{children ?? (
<pre className="max-h-48 overflow-auto font-mono text-[10px] leading-relaxed text-zinc-300">
<pre className="max-h-48 overflow-auto font-mono text-[10px] leading-relaxed text-[var(--color-text-primary)]">
{text}
</pre>
)}
@@ -283,9 +283,9 @@ function CollapsibleCode({
function MetaList({ label, items }: { label: string; items: string[] }) {
return (
<div className="text-[10px] text-zinc-500">
<div className="text-[10px] text-[var(--color-text-muted)]">
<span className="font-medium">{label}:</span>{' '}
<span className="text-zinc-400">{items.join(', ')}</span>
<span className="text-[var(--color-text-secondary)]">{items.join(', ')}</span>
</div>
);
}
@@ -16,21 +16,21 @@ export function PlanReviewBanner({
}, [planReview, onDismiss]);
return (
<div className="rounded-xl border border-emerald-500/30 bg-emerald-500/5 px-4 py-3" role="alert">
<div className="rounded-xl border border-[var(--color-glass-border)] border-l-4 border-l-[var(--color-status-success)] bg-[var(--color-glass)] px-4 py-3" role="alert">
{/* Header */}
<div className="flex items-start gap-2.5">
<ClipboardList className="mt-0.5 size-4 shrink-0 text-emerald-400" />
<ClipboardList className="mt-0.5 size-4 shrink-0 text-[var(--color-status-success)]" />
<div className="min-w-0 flex-1">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<span className="text-[13px] font-semibold text-emerald-200">Plan ready for review</span>
<span className="rounded-full bg-emerald-500/15 px-2 py-0.5 text-[9px] font-semibold uppercase tracking-wider text-emerald-400">
<span className="text-[13px] font-semibold text-[var(--color-status-success)]">Plan ready for review</span>
<span className="rounded-full bg-[var(--color-status-success)]/15 px-2 py-0.5 text-[9px] font-semibold uppercase tracking-wider text-[var(--color-status-success)]">
Plan mode
</span>
</div>
<button
aria-label="Dismiss plan"
className="rounded p-0.5 text-zinc-500 transition hover:bg-zinc-700/50 hover:text-zinc-300"
className="rounded p-0.5 text-[var(--color-text-muted)] transition-all duration-200 hover:bg-[var(--color-surface-3)]/50 hover:text-[var(--color-text-primary)]"
onClick={handleDismiss}
type="button"
>
@@ -39,30 +39,30 @@ export function PlanReviewBanner({
</div>
{planReview.agentName && (
<div className="mt-1 text-[11px] text-zinc-400">
Agent: <span className="text-zinc-300">{planReview.agentName}</span>
<div className="mt-1 text-[11px] text-[var(--color-text-secondary)]">
Agent: <span className="text-[var(--color-text-primary)]">{planReview.agentName}</span>
</div>
)}
{/* Summary */}
{planReview.summary && (
<p className="mt-2 text-[13px] leading-relaxed text-zinc-200">
<p className="mt-2 text-[13px] leading-relaxed text-[var(--color-text-primary)]">
{planReview.summary}
</p>
)}
{/* Plan content (rendered markdown) */}
{planReview.planContent && (
<div className="mt-3 max-h-80 overflow-y-auto rounded-lg border border-zinc-700/50 bg-zinc-900/60 p-3">
<div className="mt-3 max-h-80 overflow-y-auto rounded-lg border border-[var(--color-border-subtle)] bg-[var(--color-surface-1)] p-3">
<MarkdownContent content={planReview.planContent} />
</div>
)}
{/* Guidance */}
<p className="mt-3 text-[12px] leading-relaxed text-zinc-400">
<p className="mt-3 text-[12px] leading-relaxed text-[var(--color-text-secondary)]">
Send a follow-up message to proceed e.g.{' '}
<span className="text-zinc-300">&quot;implement the plan&quot;</span>,{' '}
<span className="text-zinc-300">&quot;adjust step 3&quot;</span>, or ask for a different approach.
<span className="text-[var(--color-text-primary)]">&quot;implement the plan&quot;</span>,{' '}
<span className="text-[var(--color-text-primary)]">&quot;adjust step 3&quot;</span>, or ask for a different approach.
</p>
</div>
</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-[var(--color-accent-sky)]" aria-label="Running" />;
case 'completed':
return <CheckCircle2 className="size-3.5 text-[var(--color-status-success)]" aria-label="Completed" />;
case 'failed':
return <XCircle className="size-3.5 text-[var(--color-status-error)]" 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-[var(--color-text-muted)]">{elapsed}</span>
);
}
interface SubagentActivityCardProps {
subagent: ActiveSubagent;
}
function SubagentActivityCard({ subagent }: SubagentActivityCardProps) {
const borderClass =
subagent.status === 'running'
? 'border-[var(--color-accent-sky)]/20'
: subagent.status === 'failed'
? 'border-[var(--color-status-error)]/20'
: 'border-[var(--color-status-success)]/20';
return (
<div
className={`flex items-center gap-2 rounded-lg border bg-[var(--color-glass)] px-3 py-1.5 transition-all duration-200 ${borderClass}`}
role="status"
aria-label={`Sub-agent ${subagent.name}: ${subagent.activityLabel}`}
>
<StatusIcon status={subagent.status} />
<Bot className="size-3 text-[var(--color-text-muted)]" />
<span className="text-[11px] font-medium text-[var(--color-text-primary)]">{subagent.name}</span>
<span className="text-[10px] text-[var(--color-text-muted)]"></span>
<span className="text-[10px] text-[var(--color-text-secondary)]">{subagent.activityLabel}</span>
{subagent.status === 'running' && <ElapsedTimer startedAt={subagent.startedAt} />}
{subagent.error && (
<span className="truncate text-[10px] text-[var(--color-status-error)]" 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>
);
}
@@ -1,9 +1,9 @@
export function ThinkingDots() {
return (
<div className="flex items-center gap-1.5" aria-label="Thinking">
<span className="thinking-dot size-2 rounded-full bg-zinc-500" />
<span className="thinking-dot size-2 rounded-full bg-zinc-500" />
<span className="thinking-dot size-2 rounded-full bg-zinc-500" />
<span className="thinking-dot size-2 rounded-full bg-[var(--color-accent)]" />
<span className="thinking-dot size-2 rounded-full bg-[var(--color-accent-sky)]" />
<span className="thinking-dot size-2 rounded-full bg-[var(--color-accent-purple)]" />
</div>
);
}
@@ -42,25 +42,25 @@ export function UserInputBanner({
);
return (
<div className="rounded-xl border border-blue-500/30 bg-blue-500/5 px-4 py-3" role="alert">
<div className="rounded-xl border border-[var(--color-glass-border)] border-l-4 border-l-[var(--color-accent-sky)] bg-[var(--color-glass)] px-4 py-3" role="alert">
{/* Header */}
<div className="flex items-start gap-2.5">
<MessageCircleQuestion className="mt-0.5 size-4 shrink-0 text-blue-400" />
<MessageCircleQuestion className="mt-0.5 size-4 shrink-0 text-[var(--color-accent-sky)]" />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="text-[13px] font-semibold text-blue-200">Agent question</span>
<span className="rounded-full bg-blue-500/15 px-2 py-0.5 text-[9px] font-semibold uppercase tracking-wider text-blue-400">
<span className="text-[13px] font-semibold text-[var(--color-accent-sky)]">Agent question</span>
<span className="rounded-full bg-[var(--color-accent-sky)]/15 px-2 py-0.5 text-[9px] font-semibold uppercase tracking-wider text-[var(--color-accent-sky)]">
User input
</span>
</div>
{userInput.agentName && (
<div className="mt-1 text-[11px] text-zinc-400">
Agent: <span className="text-zinc-300">{userInput.agentName}</span>
<div className="mt-1 text-[11px] text-[var(--color-text-secondary)]">
Agent: <span className="text-[var(--color-text-primary)]">{userInput.agentName}</span>
</div>
)}
<p className="mt-2 text-[13px] leading-relaxed text-zinc-200 whitespace-pre-wrap">
<p className="mt-2 text-[13px] leading-relaxed text-[var(--color-text-primary)] whitespace-pre-wrap">
{userInput.question}
</p>
</div>
@@ -71,7 +71,7 @@ export function UserInputBanner({
<div className="mt-3 flex flex-wrap gap-2">
{userInput.choices!.map((choice) => (
<button
className="rounded-lg border border-blue-500/30 bg-blue-500/10 px-3.5 py-1.5 text-[12px] font-medium text-blue-200 transition hover:border-blue-400/50 hover:bg-blue-500/20 hover:text-white disabled:cursor-not-allowed disabled:opacity-50"
className="rounded-lg border border-[var(--color-accent-sky)]/30 bg-[var(--color-accent-sky)]/10 px-3.5 py-1.5 text-[12px] font-medium text-[var(--color-accent-sky)] transition-all duration-200 hover:border-[var(--color-accent-sky)]/50 hover:bg-[var(--color-accent-sky)]/20 hover:text-[var(--color-text-primary)] disabled:cursor-not-allowed disabled:opacity-50"
disabled={isSubmitting}
key={choice}
onClick={() => handleChoiceClick(choice)}
@@ -88,7 +88,7 @@ export function UserInputBanner({
<div className="mt-3 flex items-center gap-2">
<input
aria-label="Type your answer"
className="min-w-0 flex-1 rounded-lg border border-zinc-700 bg-zinc-900/60 px-3 py-1.5 text-[13px] text-zinc-200 placeholder-zinc-500 outline-none transition focus:border-blue-500/50 focus:ring-1 focus:ring-blue-500/30 disabled:cursor-not-allowed disabled:opacity-50"
className="min-w-0 flex-1 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] px-3 py-1.5 text-[13px] text-[var(--color-text-primary)] placeholder-[var(--color-text-muted)] outline-none transition-all duration-200 focus:border-[var(--color-border-glow)] focus:ring-1 focus:ring-[var(--color-border-glow)] disabled:cursor-not-allowed disabled:opacity-50"
disabled={isSubmitting}
onChange={(e) => setFreeformText(e.target.value)}
onKeyDown={handleKeyDown}
@@ -98,7 +98,7 @@ export function UserInputBanner({
/>
<button
aria-label="Submit answer"
className="inline-flex items-center gap-1.5 rounded-lg bg-blue-600 px-3.5 py-1.5 text-[12px] font-medium text-white transition hover:bg-blue-500 disabled:cursor-not-allowed disabled:opacity-50"
className="brand-gradient-bg inline-flex items-center gap-1.5 rounded-lg px-3.5 py-1.5 text-[12px] font-medium text-white transition-all duration-200 hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-50"
disabled={isSubmitting || !freeformText.trim()}
onClick={handleFreeformSubmit}
type="button"
@@ -16,9 +16,9 @@ const kindIcons: Record<PatternGraphNodeKind, typeof CircleUser> = {
};
const kindColors: Record<PatternGraphNodeKind, { bg: string; border: string; text: string }> = {
'user-input': { bg: 'bg-indigo-500/10', border: 'border-indigo-500/30', text: 'text-indigo-400' },
'user-output': { bg: 'bg-indigo-500/10', border: 'border-indigo-500/30', text: 'text-indigo-400' },
agent: { bg: 'bg-zinc-800/80', border: 'border-zinc-600/40', text: 'text-zinc-200' },
'user-input': { bg: 'bg-[var(--color-accent)]/10', border: 'border-[var(--color-accent)]/30', text: 'text-[var(--color-accent-sky)]' },
'user-output': { bg: 'bg-[var(--color-accent)]/10', border: 'border-[var(--color-accent)]/30', text: 'text-[var(--color-accent-sky)]' },
agent: { bg: 'bg-[var(--color-surface-2)]/80', border: 'border-[var(--color-border)]/40', text: 'text-[var(--color-text-primary)]' },
distributor: { bg: 'bg-amber-500/10', border: 'border-amber-500/30', text: 'text-amber-400' },
collector: { bg: 'bg-amber-500/10', border: 'border-amber-500/30', text: 'text-amber-400' },
orchestrator: { bg: 'bg-emerald-500/10', border: 'border-emerald-500/30', text: 'text-emerald-400' },
@@ -38,9 +38,9 @@ function GraphNodeContent({ data, selected }: { data: GraphNodeData; selected: b
return (
<div
className={`flex min-w-[120px] items-center gap-2 rounded-xl border px-3 py-2 shadow-md transition ${
className={`flex min-w-[120px] items-center gap-2 rounded-xl border px-3 py-2 shadow-md backdrop-blur-sm transition ${
colors.bg
} ${selected ? 'ring-2 ring-indigo-500/50' : ''} ${colors.border}`}
} ${selected ? 'ring-2 ring-[var(--color-accent)]/50' : ''} ${colors.border}`}
>
{renderIcon()}
<div className="min-w-0 flex-1">
@@ -48,11 +48,11 @@ function GraphNodeContent({ data, selected }: { data: GraphNodeData; selected: b
{data.label}
</div>
{isAgent && data.modelLabel && (
<div className="truncate text-[10px] text-zinc-500">{data.modelLabel}</div>
<div className="truncate text-[10px] text-[var(--color-text-muted)]">{data.modelLabel}</div>
)}
</div>
{data.readOnly && (
<span className="ml-1 rounded bg-zinc-700/50 px-1 py-0.5 text-[8px] font-medium text-zinc-500">
<span className="ml-1 rounded bg-[var(--color-surface-3)]/50 px-1 py-0.5 text-[8px] font-medium text-[var(--color-text-muted)]">
SYS
</span>
)}
@@ -61,8 +61,8 @@ function GraphNodeContent({ data, selected }: { data: GraphNodeData; selected: b
}
const handleStyles = {
system: '!size-2 !border-zinc-600 !bg-zinc-400',
agent: '!size-2 !border-indigo-400 !bg-indigo-500',
system: '!size-2 !border-[var(--color-border)] !bg-[var(--color-text-secondary)]',
agent: '!size-2 !border-[var(--color-accent-sky)] !bg-[var(--color-accent)]',
hidden: '!size-0 !border-0 !bg-transparent !min-w-0 !min-h-0',
};
@@ -169,7 +169,7 @@ function PatternGraphCanvasInner({
}, [graph, onGraphChange, fitView]);
return (
<div className="h-full w-full rounded-xl border border-zinc-800 bg-zinc-950/50">
<div className="h-full w-full rounded-xl border border-[var(--color-border)] bg-[var(--color-surface-0)]/50">
<ReactFlow
nodes={nodes.map((n) => ({
...n,
@@ -189,18 +189,18 @@ function PatternGraphCanvasInner({
proOptions={{ hideAttribution: true }}
defaultEdgeOptions={{
type: 'default',
style: { stroke: '#6366f1', strokeWidth: 1.5 },
markerEnd: { type: MarkerType.ArrowClosed, width: 16, height: 16, color: '#6366f1' },
style: { stroke: '#245CF9', strokeWidth: 1.5 },
markerEnd: { type: MarkerType.ArrowClosed, width: 16, height: 16, color: '#245CF9' },
}}
connectionLineStyle={{ stroke: '#6366f1', strokeWidth: 1.5 }}
connectionLineStyle={{ stroke: '#245CF9', strokeWidth: 1.5 }}
deleteKeyCode="Delete"
>
<Background variant={BackgroundVariant.Dots} gap={20} size={1} color="#27272a" />
<Background variant={BackgroundVariant.Dots} gap={20} size={1} color="#1a1e2e" />
<Panel position="top-right">
<button
type="button"
onClick={handleAutoLayout}
className="flex items-center gap-1.5 rounded-lg border border-zinc-700 bg-zinc-800/90 px-2.5 py-1.5 text-[11px] font-medium text-zinc-300 shadow-sm backdrop-blur transition hover:border-zinc-600 hover:bg-zinc-700/90 hover:text-zinc-100"
className="flex items-center gap-1.5 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-2)]/90 px-2.5 py-1.5 text-[11px] font-medium text-[var(--color-text-secondary)] shadow-sm backdrop-blur transition hover:border-[var(--color-border-glow)] hover:bg-[var(--color-surface-3)]/90 hover:text-[var(--color-text-primary)]"
title="Auto-layout nodes"
>
<LayoutGrid className="size-3.5" />
@@ -44,10 +44,10 @@ function InputField({
placeholder?: string;
}) {
const base =
'w-full rounded-lg border border-zinc-700 bg-zinc-900 px-3 py-2 text-[13px] text-zinc-100 placeholder-zinc-600 outline-none transition focus:border-indigo-500/50';
'w-full rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] px-3 py-2 text-[13px] text-[var(--color-text-primary)] placeholder-[var(--color-text-muted)] outline-none transition focus:border-[var(--color-accent)]/50';
return (
<label className="block space-y-1.5">
<span className="text-[12px] font-medium text-zinc-400">{label}</span>
<span className="text-[12px] font-medium text-[var(--color-text-secondary)]">{label}</span>
{multiline ? (
<textarea
className={`${base} min-h-20 resize-y`}
@@ -97,17 +97,17 @@ function SystemNodeInspector({ kind }: { kind: PatternGraphNodeKind }) {
return (
<div className="space-y-3">
<div className="flex items-center gap-2.5">
<div className="flex size-8 items-center justify-center rounded-lg bg-indigo-500/10">
<Icon className="size-4 text-indigo-400" />
<div className="flex size-8 items-center justify-center rounded-lg bg-[var(--color-accent)]/10">
<Icon className="size-4 text-[var(--color-accent-sky)]" />
</div>
<div>
<div className="text-[13px] font-semibold text-zinc-200">{kindLabels[kind]}</div>
<span className="rounded bg-zinc-700/50 px-1.5 py-0.5 text-[9px] font-medium text-zinc-500">
<div className="text-[13px] font-semibold text-[var(--color-text-primary)]">{kindLabels[kind]}</div>
<span className="rounded bg-[var(--color-surface-3)]/50 px-1.5 py-0.5 text-[9px] font-medium text-[var(--color-text-muted)]">
System node
</span>
</div>
</div>
<p className="text-[12px] leading-relaxed text-zinc-500">{kindDescriptions[kind]}</p>
<p className="text-[12px] leading-relaxed text-[var(--color-text-muted)]">{kindDescriptions[kind]}</p>
</div>
);
}
@@ -140,16 +140,16 @@ function AgentNodeInspector({
<div className="space-y-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2.5">
<div className="flex size-8 items-center justify-center rounded-lg bg-zinc-800">
<Bot className="size-4 text-zinc-300" />
<div className="flex size-8 items-center justify-center rounded-lg bg-[var(--color-surface-2)]">
<Bot className="size-4 text-[var(--color-text-secondary)]" />
</div>
<div className="text-[13px] font-semibold text-zinc-200">{agent.name || 'Unnamed'}</div>
<div className="text-[13px] font-semibold text-[var(--color-text-primary)]">{agent.name || 'Unnamed'}</div>
</div>
<div className="flex items-center gap-1">
{showReorder && (
<>
<button
className="flex size-6 items-center justify-center rounded text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300 disabled:opacity-30 disabled:hover:bg-transparent disabled:hover:text-zinc-500"
className="flex size-6 items-center justify-center rounded text-[var(--color-text-muted)] transition hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)] disabled:opacity-30 disabled:hover:bg-transparent disabled:hover:text-[var(--color-text-muted)]"
disabled={!canUp}
onClick={() => onGraphChange(swapSequentialOrder(graph, nodeId, 'up'))}
title="Move earlier in sequence"
@@ -158,7 +158,7 @@ function AgentNodeInspector({
<ChevronUp className="size-3.5" />
</button>
<button
className="flex size-6 items-center justify-center rounded text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300 disabled:opacity-30 disabled:hover:bg-transparent disabled:hover:text-zinc-500"
className="flex size-6 items-center justify-center rounded text-[var(--color-text-muted)] transition hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)] disabled:opacity-30 disabled:hover:bg-transparent disabled:hover:text-[var(--color-text-muted)]"
disabled={!canDown}
onClick={() => onGraphChange(swapSequentialOrder(graph, nodeId, 'down'))}
title="Move later in sequence"
@@ -169,7 +169,7 @@ function AgentNodeInspector({
</>
)}
<button
className="flex items-center gap-1 text-[12px] text-zinc-600 transition hover:text-red-400"
className="flex items-center gap-1 text-[12px] text-[var(--color-text-muted)] transition hover:text-red-400"
onClick={() => onAgentRemove(agent.id)}
type="button"
>
@@ -235,7 +235,7 @@ export function PatternGraphInspector({
if (!selectedNodeId) {
return (
<div className="flex h-full items-center justify-center p-4">
<p className="text-center text-[12px] text-zinc-600">
<p className="text-center text-[12px] text-[var(--color-text-muted)]">
Select a node on the graph to inspect it
</p>
</div>
@@ -29,7 +29,7 @@ export function LspProfileEditor({
title={profile.name || 'Untitled LSP Profile'}
>
<section className="space-y-4">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-zinc-500">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
General
</h4>
<div className="grid gap-4 sm:grid-cols-2">
@@ -50,7 +50,7 @@ export function LspProfileEditor({
</section>
<section className="space-y-4">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-zinc-500">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
Server
</h4>
<FormField label="Command" required>
@@ -71,7 +71,7 @@ export function LspProfileEditor({
</section>
<section className="space-y-4">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-zinc-500">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
File matching
</h4>
<FormField label="File extensions" required>
@@ -29,7 +29,7 @@ export function McpServerEditor({
title={server.name || 'Untitled MCP Server'}
>
<section className="space-y-4">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-zinc-500">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
General
</h4>
<div className="grid gap-4 sm:grid-cols-2">
@@ -54,7 +54,7 @@ export function McpServerEditor({
</section>
<section className="space-y-4">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-zinc-500">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
{server.transport === 'local' ? 'Process' : 'Endpoint'}
</h4>
{server.transport === 'local' ? (
@@ -94,7 +94,7 @@ export function McpServerEditor({
</section>
<section className="space-y-4">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-zinc-500">
<h4 className="text-[12px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
Advanced
</h4>
<div className="grid gap-4 sm:grid-cols-2">
@@ -25,21 +25,21 @@ export function ToolingEditorShell({
<div className="drag-region flex items-center justify-between border-b border-[var(--color-border)] px-5 pb-3 pt-3">
<div className="flex items-center gap-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"
className="no-drag flex size-8 items-center justify-center rounded-lg text-[var(--color-text-secondary)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]"
onClick={onBack}
type="button"
>
<ChevronLeft className="size-4" />
</button>
<div>
<h2 className="text-[13px] font-semibold text-zinc-100">{title}</h2>
<p className="text-[12px] text-zinc-500">{subtitle}</p>
<h2 className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">{title}</h2>
<p className="text-[12px] text-[var(--color-text-muted)]">{subtitle}</p>
</div>
</div>
<div className="no-drag flex items-center gap-2">
{onDelete && (
<button
className="flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] text-red-400 transition hover:bg-red-500/10"
className="flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] text-[var(--color-status-error)] transition-all duration-200 hover:bg-[var(--color-status-error)]/10"
onClick={() => void onDelete()}
type="button"
>
@@ -48,7 +48,7 @@ export function ToolingEditorShell({
</button>
)}
<button
className="rounded-lg bg-indigo-600 px-4 py-1.5 text-[13px] font-medium text-white transition hover:bg-indigo-500 disabled:cursor-not-allowed disabled:opacity-40"
className="rounded-lg bg-[var(--color-accent)] px-4 py-1.5 text-[13px] font-medium text-white transition-all duration-200 hover:bg-[var(--color-accent-sky)] disabled:cursor-not-allowed disabled:opacity-40"
disabled={disableSave}
onClick={() => void onSave()}
type="button"
@@ -61,7 +61,7 @@ export function ToolingEditorShell({
<div className="flex-1 overflow-y-auto px-6 py-5">
<div className="mx-auto max-w-2xl space-y-8">
{error && (
<div className="flex items-start gap-2 rounded-lg bg-amber-500/10 px-3 py-2 text-[13px] text-amber-300">
<div className="flex items-start gap-2 rounded-lg bg-[var(--color-status-warning)]/10 px-3 py-2 text-[13px] text-[var(--color-status-warning)]">
<AlertCircle className="mt-0.5 size-3.5 shrink-0" />
{error}
</div>
+2 -2
View File
@@ -11,9 +11,9 @@ export function FormField({
}) {
return (
<label className="block">
<span className="mb-1.5 block text-[12px] font-medium text-zinc-400">
<span className="mb-1.5 block text-[12px] font-medium text-[var(--color-text-secondary)]">
{label}
{required && <span className="ml-1 text-amber-400">*</span>}
{required && <span className="ml-1 text-[var(--color-status-warning)]">*</span>}
</span>
{children}
</label>
+2 -2
View File
@@ -3,8 +3,8 @@ import type { ReactNode } from 'react';
export function InfoCallout({ children }: { children: ReactNode }) {
return (
<div className="flex items-start gap-2.5 rounded-lg border border-zinc-800 bg-zinc-900/30 px-3 py-2.5 text-[12px] leading-relaxed text-zinc-500">
<Info className="mt-0.5 size-3.5 shrink-0 text-zinc-600" />
<div className="flex items-start gap-2.5 rounded-lg border border-[var(--color-border)] bg-[var(--color-glass)] px-3 py-2.5 text-[12px] leading-relaxed text-[var(--color-text-secondary)] backdrop-blur-sm">
<Info className="mt-0.5 size-3.5 shrink-0 text-[var(--color-accent)]" />
<span>{children}</span>
</div>
);
@@ -10,13 +10,13 @@ export interface PopoverToggleRowProps {
export function PopoverToggleRow({ label, detail, enabled, onToggle }: PopoverToggleRowProps) {
return (
<button
className="flex w-full items-center gap-2 px-3 py-1.5 text-left transition hover:bg-zinc-800"
className="flex w-full items-center gap-2 px-3 py-1.5 text-left transition-all duration-150 hover:bg-[var(--color-surface-2)]"
onClick={onToggle}
type="button"
>
<div className="min-w-0 flex-1">
<div className="truncate text-[12px] font-medium text-zinc-300">{label}</div>
{detail && <div className="truncate text-[10px] text-zinc-600">{detail}</div>}
<div className="truncate text-[12px] font-medium text-[var(--color-text-primary)]">{label}</div>
{detail && <div className="truncate text-[10px] text-[var(--color-text-muted)]">{detail}</div>}
</div>
<ToggleSwitch enabled={enabled} size="sm" />
</button>
+1 -1
View File
@@ -9,7 +9,7 @@ export function SelectInput({
}) {
return (
<select
className="w-full rounded-lg border border-zinc-700 bg-zinc-900 px-3 py-2 text-[13px] text-zinc-100 outline-none transition focus:border-indigo-500/50"
className="w-full rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-2)] px-3 py-2 text-[13px] text-[var(--color-text-primary)] outline-none transition-all duration-200 focus:border-[var(--color-border-glow)] focus:shadow-[0_0_0_1px_rgba(36,92,249,0.15),0_0_12px_rgba(36,92,249,0.08)]"
onChange={(event) => onChange(event.target.value)}
value={value}
>
+1 -1
View File
@@ -13,7 +13,7 @@ export function TextInput({
}) {
return (
<input
className="w-full rounded-lg border border-zinc-700 bg-zinc-900 px-3 py-2 text-[13px] text-zinc-100 outline-none transition placeholder:text-zinc-600 focus:border-indigo-500/50"
className="w-full rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-2)] px-3 py-2 text-[13px] text-[var(--color-text-primary)] outline-none transition-all duration-200 placeholder:text-[var(--color-text-muted)] focus:border-[var(--color-border-glow)] focus:shadow-[0_0_0_1px_rgba(36,92,249,0.15),0_0_12px_rgba(36,92,249,0.08)]"
inputMode={inputMode}
onChange={(event) => onChange(event.target.value)}
placeholder={placeholder}
+1 -1
View File
@@ -11,7 +11,7 @@ export function TextareaInput({
}) {
return (
<textarea
className="w-full rounded-lg border border-zinc-700 bg-zinc-900 px-3 py-2 text-[13px] text-zinc-100 outline-none transition placeholder:text-zinc-600 focus:border-indigo-500/50"
className="w-full rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-2)] px-3 py-2 text-[13px] text-[var(--color-text-primary)] outline-none transition-all duration-200 placeholder:text-[var(--color-text-muted)] focus:border-[var(--color-border-glow)] focus:shadow-[0_0_0_1px_rgba(36,92,249,0.15),0_0_12px_rgba(36,92,249,0.08)]"
onChange={(event) => onChange(event.target.value)}
placeholder={placeholder}
rows={rows}
+2 -2
View File
@@ -10,8 +10,8 @@ export function ToggleSwitch({ enabled, size = 'md' }: ToggleSwitchProps) {
return (
<span
className={`relative inline-flex ${trackSize} shrink-0 items-center rounded-full transition-colors ${
enabled ? 'bg-indigo-500' : 'bg-zinc-700'
className={`relative inline-flex ${trackSize} shrink-0 items-center rounded-full transition-all duration-200 ${
enabled ? 'brand-gradient-bg shadow-[0_0_8px_rgba(36,92,249,0.3)]' : 'bg-[var(--color-surface-3)]'
}`}
>
<span

Some files were not shown because too many files have changed in this diff Show More