Compare commits

...
99 Commits
Author SHA1 Message Date
David Kaya b434dd86b4 chore: bump version to 0.0.20 2026-03-31 17:10:47 +02:00
David Kaya c2a691774a feat: add light mode screenshots 2026-03-31 17:04:35 +01:00
David KayaandCopilot 78949c5efd feat: render per-turn thinking tiles in chat pane
Replace the single aggregate thinking tile with per-turn thinking groups.
Instead of collecting all thinking messages into one flat array and
rendering a single ThinkingProcess before the last assistant message,
process session.messages in chronological order to produce interleaved
display items that naturally group consecutive thinking messages by turn.

Each turn now shows its own collapsible thinking tile placed inline
before its assistant response, with correct per-turn isActive state
and turnStartedAt from the matching run.

Also fixes a latent index-mismatch bug in getAssistantMessagePhase where
the visible-messages index was compared against the full session.messages
index, potentially hiding the Final badge when thinking messages existed.
Switched to ID-based comparison.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-31 16:53:28 +01:00
David KayaandCopilot fb3e80ec47 refactor: move git panel to tabbed bottom panel alongside terminal
Replace the narrow 256px sidebar git section with a shared tabbed
bottom panel that hosts both Terminal and Git as peer tabs. This gives
git operations full horizontal width for file paths, diff previews,
branch lists, and commit history.

- Create BottomPanel with shared resize handle, tab bar, and content
  switching (terminal stays mounted via CSS visibility when inactive)
- Simplify TerminalPanel by extracting resize/close to BottomPanel
- Add InlineGitPill toggle in composer footer next to Terminal pill
- Wire tab switching: clicking active tab closes panel, clicking
  inactive tab switches to it
- Remove GitPanel from ActivityPanel sidebar
- Update ARCHITECTURE.md to describe tabbed bottom panel layout

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-31 16:51:51 +01:00
David KayaandCopilot 5a71539705 feat: add git workflow frontend components
- RunChangeSummaryCard: post-run change review card with expandable
  file diffs, origin badges, selective discard with confirmation,
  and commit composer launch button
- CommitComposer: slide-over panel for staging files, editing AI-
  suggested commit messages, conventional commit type selection,
  and commit with optional push
- GitPanel: embedded activity panel section with branch management,
  push/pull/fetch operations, working tree inspection with inline
  diffs, and recent commit history
- Wire RunChangeSummaryCard into RunTimeline after completed runs
- Wire CommitComposer as overlay in App.tsx with state management
- Wire GitPanel into ActivityPanel for non-scratchpad sessions
- Update ARCHITECTURE.md with frontend git integration description

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-31 16:43:45 +01:00
David KayaandCopilot 906433f408 feat: add git workflow backend operations
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-31 16:43:13 +01:00
David KayaandCopilot 44d0ab07db feat: add git integration enhancements (phase 1)
Real-time git awareness:
- Auto-refresh git context on window focus and after run completion
- Periodic background polling (60s interval, configurable via settings)
- Pre-run working tree snapshot capture for project-backed runs
- Debounced refresh scheduling to coalesce rapid triggers

Backend (main process):
- GitService.captureWorkingTreeSnapshot() with per-file metadata
- Enriched parseWorkingTree() producing ProjectGitWorkingTreeFile entries
- AryxAppService: scheduleProjectGitRefresh(), periodic timer, focus hook
- preRunGitSnapshot persisted on SessionRunRecord with normalization

Frontend (renderer):
- Settings toggle for auto-refresh (General > Git section)
- RunTimeline: git baseline indicator showing branch and change summary
- Enhanced GitContextBadge tooltip with change breakdown details
- ChatPane: enriched git tooltip with staged/modified/untracked counts
- New IPC channel: setGitAutoRefreshEnabled

Tests: 8 new tests covering snapshot capture, refresh scheduling,
scratchpad skip behavior, and auto-refresh setting persistence.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-31 16:37:02 +01:00
David KayaandCopilot 49933f218b feat(website): add light mode with theme toggle
- Add [data-theme='light'] CSS variable overrides for warm parchment surface palette
- Add sun/moon theme toggle button in nav (desktop + mobile)
- Inline FOUC-prevention script in <head> reading localStorage/prefers-color-scheme
- Screenshot <img> elements swap between dark/light variants via data attributes
- Dynamic meta theme-color update and proper ARIA labels on toggle
- Adjust grain overlay, dot-grid, and gradient-text for light mode

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-31 16:35:17 +01:00
David Kaya 63acd9e87e Merge branch 'main' of https://github.com/davidkaya/aryx 2026-03-31 14:20:19 +02:00
David KayaandCopilot ebb506a359 feat: show platform-specific Copilot CLI install instructions when CLI is missing
Replace the generic 'Install the copilot CLI' one-liner with a rich,
platform-tabbed installation guide. Auto-detects macOS/Windows/Linux and
shows the recommended install command (Homebrew, WinGet, or install script)
plus alternatives (npm). Includes copy-to-clipboard, auth step, and a
refresh button.

- Extend platform.ts with isWindows, isLinux, detectedPlatform
- Add cliInstallInstructions.ts with per-platform install data
- Add CliInstallGuide component in settings/ with platform tabs
- Integrate into CopilotStatusCard for copilot-cli-missing state
- Enhance WelcomePane with CliMissingCard showing quick-start command

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-31 12:34:01 +02:00
Dávid KayaandGitHub b25da56f5e chore: Add Contributor Covenant Code of Conduct
This document outlines the standards of behavior for community members, including pledges, acceptable and unacceptable behaviors, enforcement responsibilities, and consequences for violations.
2026-03-31 11:41:20 +02:00
Dávid KayaandGitHub 30ff81009a chore: Change Dependabot update interval from weekly to daily 2026-03-31 11:31:59 +02:00
David Kaya 9a261780c6 chore: bump version to 0.0.19 2026-03-31 11:09:12 +02:00
David KayaandCopilot 9b7e4dd6e9 feat: format and syntax-highlight JSON arguments in approval popup
- Add deepParseJsonStrings utility to recursively unwrap JSON-encoded
  string values inside tool-call args before display
- Apply to McpDetail, CustomToolDetail, and HookDetail renderers
- Add lightweight regex-based JSON syntax highlighting (keys, strings,
  numbers, booleans, punctuation) in CollapsibleCode when content is JSON
- Remove unused Terminal import

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-31 10:43:28 +02:00
David KayaandCopilot 4bc2c327f7 fix: honor MCP server auto-approvals in hook flow
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-31 10:11:15 +02:00
David Kaya 36126f1c74 chore: bump version to 0.0.18 2026-03-30 17:20:40 +02:00
David KayaandCopilot bec50da2b4 fix: add DPI awareness to NSIS installer
Add ManifestDPIAware true via a custom NSIS include file so the
installer renders at native resolution on high-DPI displays.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 17:19:58 +02:00
David KayaandCopilot 535adc64be fix: enable background update checks in dev builds
Remove the isPackaged guard from AutoUpdateService.start() so that
background update checks run in both packaged and dev builds.
forceDevUpdateConfig already handles dev-mode config correctly via
dev-app-update.yml — the start() gate was preventing the 10s initial
check and 4h periodic checks from ever being scheduled in dev.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 17:18:02 +02:00
David KayaandCopilot 772c84fed3 feat: add in-app update notification banner to sidebar
Subscribe to auto-update status at the App level and render a compact
UpdateBanner in the sidebar footer when an update is available,
downloading, or downloaded:

- Available/downloading: subtle banner with progress bar, dismissable
- Downloaded: prominent 'Restart to update' action with glow effect

Clicking the banner opens Settings directly on the Troubleshooting
section via a new initialSection prop on SettingsPanel.

New files:
- src/renderer/components/ui/UpdateBanner.tsx

Modified files:
- App.tsx: subscribe to onUpdateStatus, wire props
- Sidebar.tsx: accept and render UpdateBanner
- SettingsPanel.tsx: add initialSection prop + export SettingsSection type
- styles.css: add update-banner-enter slide-up animation

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 17:15:38 +02:00
David KayaandCopilot 9647b5fdb5 fix: restructure sidebar project header to prevent name truncation
Restructure the ProjectGroup header from a single cramped line into a
two-row layout so the project name gets adequate space:

- Row 1: chevron + icon + project name (min-w-0 flex-1) + hover actions
- Row 2: git branch badge + running/discovery/session count badges

Additional polish:
- Branch label uses font-mono (JetBrains Mono) for developer feel
- Branch max-width increased from 80px to 140px for better readability
- Project name tooltip shows full name and path on hover
- Scratchpad keeps session count inline on the identity row

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 17:02:47 +02:00
David Kaya 5946dc75ba chore: bump package.json to 0.0.17 2026-03-30 16:33:17 +02:00
David KayaandCopilot 59d3c81f9f fix: classify unstreamed sub-agent messages as thinking
Sub-agent messages bypass the streaming path (turn-delta) entirely due to
SDK batching behavior. They arrive only at turn-complete time via
FinalizeCompletedMessages. Without classification, they appear as separate
chat bubbles cluttering the transcript.

Two-pronged fix:

Sidecar: FinalizeCompletedMessages now tags messages from
_reclassifiedMessageIds with MessageKind='thinking'. This covers messages
that WERE streamed and reclassified during the turn. Added MessageKind
property to ChatMessageDto.

Main process: finalizeTurn detects unstreamed assistant messages (not in
existing session.messages) and classifies them as thinking when a visible
response was already streamed. Emits message-reclassified events so the
renderer can update incrementally, though the primary path is the
workspace:updated broadcast which already includes the correct messageKind.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 16:24:30 +01:00
David KayaandCopilot deb5c96d58 feat: render thinking process UI for intermediate agent messages
Wire message-reclassified sidecar events through the main process to
the renderer, where reclassified messages are filtered out of the main
transcript and collected into a collapsible ThinkingProcess component.

Main process changes:
- Route message-reclassified via dedicated onMessageReclassified callback
- Add applyMessageReclassified handler that sets messageKind and emits
  the session event for the renderer
- Forward assistant-intent and reasoning-delta as turn-scoped events

Renderer changes:
- Split session.messages into visibleMessages and thinkingMessages
- Render ThinkingProcess above the last assistant message
- ThinkingProcess auto-expands during active turns, collapses on finish
- Update messagePhase to skip thinking-kind messages for final detection

Tests:
- 3 new sessionWorkspace tests for reclassification apply/dedup/ignore
- 2 new messagePhase tests for thinking-kind handling
- Updated runTurnPending test fixtures for new callback

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 16:16:37 +01:00
David KayaandCopilot 56de8b7bd6 feat: add thinking protocol events
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 16:11:58 +01:00
David KayaandCopilot 38dd358755 docs: document bookmarks panel in README, ARCHITECTURE, and website
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 16:11:17 +01:00
David KayaandCopilot 770a0f3529 feat: add bookmarks panel for viewing pinned messages across sessions
Add a new BookmarksPanel accessible via Ctrl/Cmd+Shift+B or the
command palette (View Bookmarks). The panel lists all pinned messages
across all sessions globally, with:

- Click-to-navigate: switches session and scrolls to the message
- Inline unpin: remove bookmarks directly from the panel
- Keyboard navigation: arrow keys, Enter, Escape
- Empty state when no messages are pinned

New shared helper listPinnedMessages() in sessionLibrary.ts derives
pinned messages from the workspace state in the renderer.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 16:05:08 +01:00
David KayaandCopilot e37d69bd63 fix: add macOS traffic light inset to sidebar header
Position macOS traffic light buttons (trafficLightPosition) in the
BrowserWindow and add conditional left padding to the sidebar header
so the app logo and title clear the window management controls.

- Create shared platform detection utility (src/renderer/lib/platform.ts)
- Set trafficLightPosition { x: 16, y: 22 } on macOS in createMainWindow
- Apply pl-20 (80px) left padding to the sidebar header on macOS
- Consolidate navigator.platform check from keyboardShortcuts.ts

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 16:04:45 +01:00
David KayaandCopilot c01a427d8a feat(website): add OG hero preview image for link sharing
Replace the raw logo OG image with a designed 1200×630 hero card
generated at build time using satori + @resvg/resvg-js.

- Add generate-og.ts script with branded dark card design (gradient
  orbs, geometric rings, logo, title, tagline)
- Wire generation into build pipeline (runs before astro build)
- Update meta tags with absolute URLs, dimensions, and twitter:image
- Configure site URL (https://aryx.app) in astro.config.mjs

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 16:01:09 +01:00
David KayaandCopilot 01b3949557 docs: add trademark disclaimer to README and website footer
GitHub and GitHub Copilot are trademarks of Microsoft Corporation.
Aryx is an independent project, not affiliated with or endorsed by
Microsoft or GitHub.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 10:38:25 +02:00
David Kaya c01110979c fix: link in readme 2026-03-30 10:27:21 +02:00
David Kaya a034b333b3 chore: bump package.json to 0.0.16 2026-03-30 10:26:30 +02:00
David KayaandCopilot 41289c960b fix: enable update checks in dev mode via forceDevUpdateConfig
Add dev-app-update.yml so electron-updater can check GitHub releases
even when running with bun run dev. Remove the isPackaged guard from
checkForUpdates() so manual clicks always contact the update server.
Automatic periodic checks remain disabled in dev mode.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 10:24:07 +02:00
David KayaandCopilot 33b293271e fix: add up-to-date state so Check for updates gives visible feedback
When electron-updater reports no update available, the service now
transitions to 'up-to-date' instead of reverting silently to 'idle'.
The troubleshooting UI shows a green check icon, 'Up to date' label,
and 'You are running the latest version of Aryx.' description.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 10:20:05 +02:00
David KayaandCopilot cbcf239a0a fix: MCP group toggle styling and server-level approval UX
Two fixes in the auto-approval pill:

1. GroupToggle now uses brand-gradient-bg with glow shadow and matches
   ToggleSwitch sm dimensions, making MCP group toggles visually
   consistent with individual tool toggles.

2. Individual tool toggles now reflect server-level approval state.
   When a server key is approved, all tool rows show as enabled.
   Toggling a single tool OFF in a server-approved group expands the
   server key to individual tool IDs minus the excluded tool, enabling
   the 'approve all → disable one specific tool' workflow.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 10:14:13 +02:00
David KayaandCopilot c702cf88e2 fix: approval pill count mismatch with duplicate MCP tool names
When multiple MCP servers expose tools with the same name, the approval
pill showed an incorrect count (e.g. 150/300) even when everything was
approved.  The numerator used a Set<string> to deduplicate by tool ID,
so shared tools were counted once, while the denominator counted each
group occurrence independently.

Extract countApprovedToolsInGroups() into shared/domain/tooling.ts and
switch to per-group counting that mirrors the totalItemCount formula.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 10:07:41 +02:00
David KayaandCopilot 8a4d23c22a feat: add Enable all / Approve all buttons to inline pills
Add bulk action buttons to the Tools and Auto-approval pill popovers:

- Tools pill: sticky header with Enable all / Disable all toggle button
  that enables or disables every MCP server and LSP profile at once
- Approval pill: Approve all / Unapprove all button in the existing
  sticky header next to the Reset button, approving or clearing all
  tool and server approval keys

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 09:49:20 +02:00
David KayaandCopilot 042cec6065 fix: resolve hook permissions to proper categories for approval
When the pre-tool-use hook returns 'ask', the Copilot CLI creates
PermissionRequestHook instead of categorized PermissionRequestRead/
Write/Shell. This caused 'Permission: hook' labels and broke category-
based auto-approval ('Always approve read' wouldn't cover grep/glob).

Add ResolveHookToolCategory mapping in CopilotApprovalCoordinator to
map known tool names (view/grep/glob→read, edit/create→write, etc.)
to their permission categories. Wire into GetFallbackToolName,
BuildPermissionApprovalEvent, and CreateApprovalPolicyOutput so:
- Approval banner shows 'Permission: read' instead of 'Permission: hook'
- 'Always approve' stores the category key, covering all tools in it
- Hook short-circuits when category is already auto-approved
Unknown tools (MCP, custom) keep existing 'hook' behavior.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 09:41:51 +02:00
David KayaandCopilot 39fee48c0b feat: polish troubleshooting page and fix timeline icons
- Add 'Built with ❤ by Dávid Kaya' attribution footer to the
  troubleshooting settings page, matching the website footer
- Add 'Check for updates' action to troubleshooting, wired to the
  existing auto-updater IPC with live status feedback (checking,
  available, downloading, downloaded, error states)
- Fix timeline event icons: increase node circle from 15px to 18px,
  shrink icons from 14px to 10px for proper padding, and force white
  icon color on running-state gradient background to eliminate the
  purple-circle overlay clash

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 09:04:26 +02:00
David Kaya 27e784ab9b chore: bump version to 0.0.13 2026-03-30 01:10:52 +02:00
David Kaya 11a10ea53c fix: icon missing on windows 2026-03-30 01:10:33 +02:00
David KayaandCopilot 3318a14d32 docs: rewrite README and redesign website feature showcase
README:
- Full rewrite with confident, direct tone
- New structure: pitch → highlights → how-it-works → categorized feature tables
- Add 9 completed features (notifications, command palette, keyboard shortcuts,
  session search, onboarding, system tray, branching, message actions, animations)
- Update prerequisites to cross-platform (Windows, macOS, Linux)
- Drop redundant sections

Website:
- Replace flat 4x3 grid of 12 identical feature cards with 3 named categories
  (Workspace & Sessions, Agent Intelligence, Developer Tooling)
- Compact icon+title+description layout instead of heavy bordered cards
- Add 9 new completed features (22 features total, neatly organized)
- Each category has a colored accent heading with rule lines
- Hover reveals with subtle background transition

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 01:04:26 +02:00
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
180 changed files with 24327 additions and 2859 deletions
+11
View File
@@ -0,0 +1,11 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
version: 2
updates:
- package-ecosystem: "" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "daily"
+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
+32 -6
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/write operations, run change attribution, commit workflow orchestration, 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 |
@@ -89,7 +89,7 @@ sequenceDiagram
R->>P: Invoke typed API
P->>M: IPC request
M->>M: Append user message
M->>M: Create run record and mark session running
M->>M: Capture pre-run git snapshot, create run record, and mark session running
M->>S: run-turn command
S->>C: Execute workflow
C-->>S: Partial output / tool activity / handoffs / input requests
@@ -97,7 +97,7 @@ sequenceDiagram
M-->>R: Push session events and workspace updates
C-->>S: Final messages or turn boundary
S-->>M: Completion or error
M->>M: Finalize run and persist state
M->>M: Finalize run, compute post-run git summary, refresh project git state, and persist state
M-->>R: Final workspace snapshot
```
@@ -124,6 +124,10 @@ 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.
For git-backed projects, the main process also owns background git refreshes, captures a structured pre-run working-tree snapshot on each run record, and persists a post-run git change summary after project-backed turns complete. It also owns all git write operations exposed by Aryx — selective discard, staging, commit, push/pull/fetch, and branch lifecycle actions — so the renderer never shells out directly or manipulates repository state on its own.
### Patterns
Patterns describe how agents collaborate. The architecture supports:
@@ -159,6 +163,8 @@ A session is the working unit of the product. It binds together:
This is how Aryx keeps "ongoing work" first class. Sessions can survive restarts, can be organized, and can accumulate operational history over time.
Individual messages can be pinned as bookmarks. A dedicated bookmarks panel (`BookmarksPanel`) lists all pinned messages across all sessions globally, navigating to the originating session and message on selection. This data is derived renderer-side from the workspace state; there is no separate backend API.
### Runs
Each user turn becomes a **run**. A run is more than the final assistant output; it also tracks:
@@ -168,6 +174,7 @@ Each user turn becomes a **run**. A run is more than the final assistant output;
- which activity happened during the turn
- partial streaming output
- success or failure
- optional git baselines and post-run change summaries for project-backed execution
That run model is what enables the activity panel and historical timeline instead of forcing the user to infer execution from message text alone.
@@ -185,16 +192,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
@@ -206,15 +217,24 @@ 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
- **Message reclassification events**: let the sidecar retroactively mark a streamed assistant message as `thinking` once the SDK confirms that message requested tool work, so the UI can separate intermediate planning chatter from the final response without sacrificing live streaming
- **Assistant intent and reasoning-delta events**: optional Copilot SDK metadata that exposes short "what I'm doing" labels plus incremental reasoning text for richer thinking-process surfaces
- **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 +291,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
@@ -280,6 +302,8 @@ This lets the application treat tooling as reusable workspace capability while s
Project-backed sessions can carry repository context such as branch and dirty state, while scratchpad sessions omit git context but still support MCP, LSP, and runtime tooling. Scratchpad execution uses a per-session working directory instead of a single shared scratchpad folder, so file-based context and generated artifacts stay scoped to the active scratchpad session. Both session kinds share the same tooling selection and approval model. This keeps the architecture grounded in real codebases without forcing every conversation to be project-heavy, while still letting scratchpad sessions leverage configured tools when useful.
For git-backed projects, the renderer surfaces three specialized components. `RunChangeSummaryCard` appears inline in the run timeline after each completed run, showing the files changed during that run with per-file diff previews, origin attribution (run-created vs. pre-existing), and selective discard actions. `CommitComposer` is a slide-over panel for staging files, editing an AI-suggested commit message, selecting a conventional commit type, and committing (with optional push). `GitPanel` is embedded in the tabbed bottom panel (alongside the terminal) and provides branch management, push/pull/fetch network operations, working-tree change inspection, and recent commit history. The bottom panel uses a shared resize handle and tab bar so the terminal and git views coexist without competing for screen real estate. All git write operations flow through IPC to the main process; the renderer never runs git commands directly.
### Execution observability
The architecture treats execution as observable by design:
@@ -331,9 +355,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.
+128
View File
@@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
noble_pinhole.0g@icloud.com.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
+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>.
+68 -100
View File
@@ -8,126 +8,94 @@
A desktop workspace for Copilot-powered work across real projects.
</p>
Aryx is built for people who want more than a generic AI chat window. It gives you a place to ask quick questions, connect real projects, run reusable agent patterns, and keep ongoing work organized in one app.
<p align="center">
<a href="https://github.com/davidkaya/aryx/releases">Download</a>&nbsp;&nbsp;·&nbsp;&nbsp;<a href="https://aryx.app">Website</a>&nbsp;&nbsp;·&nbsp;&nbsp;<a href="https://github.com/davidkaya/aryx/issues">Issues</a>
</p>
It works especially well when you want AI help that stays grounded in an actual codebase: your folders, your repository state, your current branch, and your active work.
---
## Why use Aryx?
Aryx is a desktop app that turns GitHub Copilot into a full workspace. Connect real projects, orchestrate multi-agent workflows, and keep persistent sessions organized — instead of starting from scratch in a blank chat window every time. It runs on Windows, macOS, and Linux.
- **Start fast** with a scratchpad conversation for quick questions and ad-hoc work.
- **Work against real projects** by attaching local folders and letting Aryx stay aware of repository context.
- **Go beyond one assistant** with orchestration patterns such as single-agent, sequential, concurrent, handoff, and group-chat flows.
- **See what is happening** with live activity for each agent while a run is in progress, including sub-agent delegations, hook lifecycle, skill invocations, and context compaction.
- **Stay organized** with persistent sessions you can rename, pin, archive, delete, and return to later.
- **Steer while agents work** by sending follow-up messages mid-turn — the agent receives your input immediately.
- **Attach images** to any message for visual context the model can reason about.
- **Tune how you work** by choosing models and reusing saved patterns that fit different tasks.
## Highlights
## What you can do in the app
- **Multi-agent orchestration** — single, sequential, concurrent, handoff, and group-chat patterns with a visual graph editor.
- **Project-grounded** — attach local folders and repos so every conversation has real codebase context.
- **Live execution visibility** — watch agents think, delegate, call tools, and consume context in real time.
- **Persistent workspace** — sessions survive restarts. Search, pin, archive, branch, and return to past work.
- **Extensible tooling** — MCP servers, LSP profiles, project hooks, and fine-grained tool approval controls.
- **Keyboard-first** — command palette, rich shortcuts, mid-turn steering, and a built-in terminal.
### Ask quick questions in a scratchpad
## How it works
If you just want to think through an idea, draft something, or ask for help without connecting a project, start a scratchpad session and begin chatting.
Each scratchpad session keeps its own isolated working directory, so files created in one scratchpad do not leak into another.
1. **Launch Aryx** — the app checks your Copilot CLI connection and shows status on the home screen.
2. **Connect a project** or open a scratchpad for quick questions without any setup.
3. **Pick a pattern** — choose a single-agent chat or a saved multi-agent orchestration workflow.
4. **Work** — ask questions, steer agents mid-turn, watch live activity, and keep the session for later.
### Connect a real project
## Features
Add a local folder when you want help that is grounded in your work. Aryx is designed to feel strongest when it is attached to a real project instead of acting like a general-purpose chatbot.
### Workspace & sessions
### Choose how agents collaborate
| Feature | Description |
|---------|-------------|
| Scratchpad sessions | Quick questions with isolated working directories — no project setup needed |
| Persistent sessions | Rename, pin, archive, duplicate, and return to sessions across restarts |
| Session branching | Fork a session at any user message to explore a different direction |
| Session search | Full-text search across all session messages, not just titles |
| Message actions | Copy, pin, edit-and-resend, and regenerate individual messages |
| Bookmarks | Browse all pinned messages across sessions in one panel (`Ctrl+Shift+B`) |
| System tray | Minimize to tray, quick-launch scratchpads, and see running session count |
| Desktop notifications | Native OS alerts when runs complete, fail, or need approval |
| Onboarding | First-launch walkthrough, interactive tooltips, and a "try it" quickstart |
Aryx supports several ways of working:
### Agent intelligence
- **Single** for direct one-agent help
- **Sequential** for pipeline-style work where each agent sees the full conversation and appends its contribution
- **Concurrent** for parallel exploration where the final turn aggregates multiple independent responses
- **Handoff** for agent-to-agent delegation, with the next user turn continuing when a specialist needs more input
- **Group chat** for round-robin collaborative refinement across multiple agent turns
| Feature | Description |
|---------|-------------|
| Orchestration patterns | Single, sequential, concurrent, handoff, and group-chat agent flows |
| Visual pattern editor | Drag nodes, draw connections, and inspect each step in a graph view |
| Mid-turn steering | Send follow-up messages while an agent is running — input is injected immediately |
| Plan review & questions | Agents propose plans and ask clarifying questions before acting |
| Run timeline | Structured history of tool calls, delegations, hooks, and context usage |
| Copilot customization | Auto-discovers instructions, agent profiles, and prompt files from your repo |
| Model & effort tuning | Choose models, adjust reasoning effort, and set interaction modes per session |
### Add global MCPs and LSPs
### Developer tooling
You can define MCP servers and LSP profiles once in **Settings**, then enable the ones you want for each project-backed session from the right-side **Activity** panel.
| Feature | Description |
|---------|-------------|
| Real project context | Attach folders and repos — see branch, dirty state, and ahead/behind status |
| MCP servers | Define servers globally, enable per session, auto-discover from project configs |
| LSP profiles | Language server integration for code intelligence in agent workflows |
| Tool approval | Fine-grained approval policies with pattern-level defaults and per-session overrides |
| Project hooks | Auto-discovers `.github/hooks/*.json` and runs lifecycle hooks in the sidecar |
| Image input | Attach screenshots, diagrams, or photos for visual reasoning |
| Integrated terminal | Full PTY-backed terminal inside the workspace (`Ctrl+\``) |
| Command palette | `Ctrl+K` fuzzy search across actions, sessions, and settings |
| Keyboard shortcuts | Comprehensive keybindings with a cheat sheet via `Ctrl+/` |
This keeps machine-wide tooling reusable while still letting each session decide which external tools the agent can use.
## Prerequisites
Patterns now require tool-call approval by default. They can also store default auto-approval for known MCP and LSP tools, and each session can override those auto-approval defaults from the Activity panel before a run starts.
Project-backed sessions also honor GitHub Copilot CLI-style hook files from `.github/hooks/*.json`. Aryx discovers them automatically in the connected repository and runs the supported lifecycle hooks inside the sidecar, with `preToolUse` deny decisions applied before Aryx's own approval policy.
### Watch runs as they happen
You can follow agent activity while a session is running, which makes longer or more complex workflows easier to trust and understand. The activity panel shows sub-agent delegations, skill invocations, hook lifecycle events, and context compaction in real time. A context-usage bar below the composer shows how much of the model's context window the current session occupies.
### Steer agents mid-turn
While an agent is working, you can type a follow-up message that is delivered immediately into the current turn. This lets you redirect, refine, or add context without waiting for the turn to finish. The composer shows an amber "steering" indicator when a message will be injected into an active run.
### Attach images
You can attach images (JPEG, PNG, GIF, WebP) to any message using the clip button, drag-and-drop, or paste from clipboard. Image attachments are sent as base64-encoded blobs so the model can reason about visual content alongside your text.
### Keep important work around
Sessions are persistent, so you can return to ongoing work instead of starting from scratch every time. You can also rename, pin, archive, delete, and duplicate sessions as your workspace grows.
## Before you start
To use Aryx comfortably, make sure you have:
- a **Windows machine**
- **GitHub Copilot CLI** installed and available as `copilot`
- an active **GitHub Copilot sign-in**
- a local folder or git repository ready to connect if you want project-aware help
- any MCP servers or language servers you want to use installed and reachable from your machine
- An active **GitHub Copilot** sign-in
- Windows, macOS, or Linux
Aryx includes connection status in the app so you can quickly tell whether Copilot is ready before you start a session.
Aryx shows your Copilot connection status in the app so you know if authentication is ready before starting a session.
## Getting started
## Development
1. **Open Aryx**
Launch the app and head to settings if you want to confirm your Copilot connection first.
```sh
bun run test # typecheck + unit tests
bun run sidecar:test # backend tests
bun run build # full build (electron + sidecar)
2. **Check that Copilot is ready**
Make sure the app shows that Copilot is installed and authenticated.
bun run package # package for current platform → release/
bun run installer # create installable artifact
bun run publish-release # publish to GitHub Releases
```
3. **Choose how you want to begin**
Start a scratchpad session for quick work, or add a project if you want the conversation grounded in a local codebase.
Tagged releases use GitHub Actions to build and publish Windows (NSIS), macOS (DMG, signed + notarized), and Linux (AppImage) artifacts. The app uses `electron-updater` for in-app updates.
4. **Pick a pattern**
Use a simple single-agent setup to begin, or choose a saved multi-agent pattern when you want a more structured workflow.
## Trademarks
5. **Configure optional tooling**
If you want MCP or LSP support, add the global definitions in settings and then enable the ones you want for the current session from the Activity panel. Aryx also surfaces Copilot CLI runtime tools for approval management: tool calls require approval by default, and you can set pattern-level auto-approval defaults and override them per session.
6. **Start working**
Ask a question, describe a task, or explore a project. As the run progresses, you can watch the participating agents and keep the session for later.
## When Aryx feels most useful
Aryx shines when you want to:
- move from quick chat to deeper multi-step work without leaving the app
- keep AI conversations tied to actual projects instead of isolated prompts
- compare different ways of approaching the same task
- reuse patterns for recurring workflows
- maintain a history of meaningful sessions instead of disposable chats
## Build and release automation
For local validation, run:
- `bun run test`
- `bun run sidecar:test`
- `bun run build`
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.
## Current focus
Aryx is focused on local, project-based work with your GitHub Copilot account. It already covers the essentials for working with projects, sessions, and reusable orchestration patterns, and it is growing toward a fuller AI workstation experience over time.
If you want an AI app that feels closer to a control room for real work than a blank chat box, Aryx is built for that.
GitHub and GitHub Copilot are trademarks of Microsoft Corporation. Aryx is an independent project, not affiliated with or endorsed by Microsoft or GitHub.
+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>
+1
View File
@@ -0,0 +1 @@
ManifestDPIAware true
-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
+4
View File
@@ -0,0 +1,4 @@
provider: github
owner: davidkaya
repo: aryx
releaseType: release
+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'),
+102 -9
View File
@@ -1,15 +1,16 @@
{
"name": "aryx",
"version": "1.0.0",
"description": "Electron orchestrator for Copilot-powered agent workflows across multiple projects.",
"version": "0.0.20",
"description": "Orchestrator for Copilot-powered agent workflows across multiple projects.",
"private": true,
"main": "dist-electron/main/index.js",
"scripts": {
"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,100 @@
"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": true,
"verifyUpdateCodeSignature": false
},
"nsis": {
"oneClick": false,
"perMachine": false,
"allowToChangeInstallationDirectory": true,
"include": "assets/installer.nsh",
"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}`);
}
}
@@ -85,6 +85,7 @@ public sealed class ChatMessageDto
public string AuthorName { get; init; } = string.Empty;
public string Content { get; init; } = string.Empty;
public string CreatedAt { get; init; } = string.Empty;
public string? MessageKind { get; set; }
public IReadOnlyList<ChatMessageAttachmentDto> Attachments { get; init; } = [];
}
@@ -183,6 +184,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 +225,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; } = [];
@@ -328,6 +332,13 @@ public sealed class TurnCompleteEventDto : SidecarEventDto
public bool Cancelled { get; init; }
}
public sealed class MessageReclassifiedEventDto : SidecarEventDto
{
public string SessionId { get; init; } = string.Empty;
public string MessageId { get; init; } = string.Empty;
public string NewKind { get; init; } = string.Empty;
}
public sealed class AgentActivityEventDto : SidecarEventDto
{
public string SessionId { get; init; } = string.Empty;
@@ -337,6 +348,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
@@ -371,6 +384,23 @@ public sealed class SkillInvokedEventDto : SidecarEventDto
public string? Description { get; init; }
}
public sealed class AssistantIntentEventDto : SidecarEventDto
{
public string SessionId { get; init; } = string.Empty;
public string? AgentId { get; init; }
public string? AgentName { get; init; }
public string Intent { get; init; } = string.Empty;
}
public sealed class ReasoningDeltaEventDto : SidecarEventDto
{
public string SessionId { get; init; } = string.Empty;
public string? AgentId { get; init; }
public string? AgentName { get; init; }
public string ReasoningId { get; init; } = string.Empty;
public string ContentDelta { get; init; } = string.Empty;
}
public sealed class HookLifecycleEventDto : SidecarEventDto
{
public string SessionId { get; init; } = string.Empty;
@@ -385,6 +415,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 +530,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,25 @@ 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 static readonly Dictionary<string, string> HookToolCategories = new(StringComparer.OrdinalIgnoreCase)
{
["view"] = ReadPermissionKind,
["glob"] = ReadPermissionKind,
["grep"] = ReadPermissionKind,
["lsp"] = ReadPermissionKind,
["edit"] = WritePermissionKind,
["create"] = WritePermissionKind,
["powershell"] = ShellPermissionKind,
["read_powershell"] = ShellPermissionKind,
["write_powershell"] = ShellPermissionKind,
["stop_powershell"] = ShellPermissionKind,
["list_powershell"] = ShellPermissionKind,
["web_fetch"] = UrlPermissionKind,
["web_search"] = UrlPermissionKind,
["store_memory"] = MemoryPermissionKind,
};
private readonly ConcurrentDictionary<string, PendingApprovalRequest> _pendingApprovals = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, ConcurrentDictionary<string, byte>> _requestApprovedTools = new(StringComparer.Ordinal);
@@ -54,12 +73,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, command.Tooling?.McpServers);
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);
}
@@ -106,9 +155,8 @@ internal sealed class CopilotApprovalCoordinator
string approvalId,
string? toolName)
{
string permissionKind = string.IsNullOrWhiteSpace(request.Kind)
? "tool access"
: request.Kind.Trim();
string permissionKind = ResolvePermissionKind(request, command.Tooling?.McpServers);
string agentName = string.IsNullOrWhiteSpace(agent.Name) ? agent.Id : agent.Name;
string? sessionId = NormalizeOptionalString(invocation.SessionId);
string? normalizedToolName = NormalizeOptionalString(toolName);
@@ -149,11 +197,53 @@ internal sealed class CopilotApprovalCoordinator
PermissionKind = permissionKind,
Title = title,
Detail = detail,
PermissionDetail = BuildPermissionDetail(request),
PermissionDetail = BuildPermissionDetail(request, command.Tooling?.McpServers),
};
}
internal static PermissionDetailDto BuildPermissionDetail(PermissionRequest request)
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,
IReadOnlyList<RunTurnMcpServerConfigDto>? configuredMcpServers = null)
{
ArgumentNullException.ThrowIfNull(request);
@@ -210,12 +300,7 @@ internal sealed class CopilotApprovalCoordinator
ToolDescription = NormalizeOptionalString(customTool.ToolDescription),
Args = customTool.Args,
},
PermissionRequestHook hook => new PermissionDetailDto
{
Kind = HookPermissionKind,
Args = hook.ToolArgs,
HookMessage = NormalizeOptionalString(hook.HookMessage),
},
PermissionRequestHook hook => BuildHookPermissionDetail(hook, configuredMcpServers),
_ => new PermissionDetailDto
{
Kind = NormalizeOptionalString(request.Kind) ?? "unknown",
@@ -227,7 +312,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 +331,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 +414,49 @@ internal sealed class CopilotApprovalCoordinator
return GetFallbackToolName(request);
}
private const string McpServerApprovalPrefix = "mcp_server:";
private static string? ResolveMcpServerApprovalKey(
PermissionRequest request,
IReadOnlyList<RunTurnMcpServerConfigDto>? configuredMcpServers)
{
return request switch
{
PermissionRequestMcp mcp => BuildMcpServerApprovalKey(mcp.ServerName),
PermissionRequestHook hook => ResolveHookMcpServerApprovalKey(hook.ToolName, configuredMcpServers),
_ => null,
};
}
internal static string? BuildMcpServerApprovalKey(string? serverName)
{
string? normalizedServerName = NormalizeOptionalString(serverName);
return normalizedServerName is not null ? $"{McpServerApprovalPrefix}{normalizedServerName}" : null;
}
internal static string? ResolveHookMcpServerApprovalKey(
string? toolName,
IReadOnlyList<RunTurnMcpServerConfigDto>? configuredMcpServers)
=> BuildMcpServerApprovalKey(ResolveHookMcpServerName(toolName, configuredMcpServers));
internal static string? ResolveHookMcpServerName(
string? toolName,
IReadOnlyList<RunTurnMcpServerConfigDto>? configuredMcpServers)
{
string? normalizedToolName = NormalizeOptionalString(toolName);
if (normalizedToolName is null || configuredMcpServers is null || configuredMcpServers.Count == 0)
{
return null;
}
return configuredMcpServers
.Select(ResolveConfiguredMcpServerName)
.OfType<string>()
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderByDescending(static serverName => serverName.Length)
.FirstOrDefault(serverName => MatchesHookMcpServerToolName(normalizedToolName, serverName));
}
private static string? ResolveApprovalCacheKey(
string? toolName,
string? autoApprovedToolName)
@@ -390,10 +520,103 @@ internal sealed class CopilotApprovalCoordinator
PermissionRequestWrite => WritePermissionKind,
PermissionRequestRead => ReadPermissionKind,
PermissionRequestMemory => StoreMemoryToolName,
PermissionRequestHook hook => ResolveHookToolCategory(hook.ToolName),
_ => null,
};
}
internal static string? ResolveHookToolCategory(string? toolName)
{
string? normalized = NormalizeOptionalString(toolName);
if (normalized is null)
{
return null;
}
return HookToolCategories.TryGetValue(normalized, out string? category) ? category : null;
}
private static string ResolvePermissionKind(
PermissionRequest request,
IReadOnlyList<RunTurnMcpServerConfigDto>? configuredMcpServers)
{
string permissionKind = string.IsNullOrWhiteSpace(request.Kind)
? "tool access"
: request.Kind.Trim();
if (request is not PermissionRequestHook hook)
{
return permissionKind;
}
string? resolvedCategory = ResolveHookToolCategory(hook.ToolName);
if (resolvedCategory is not null)
{
return resolvedCategory;
}
return ResolveHookMcpServerName(hook.ToolName, configuredMcpServers) is not null
? McpPermissionKind
: permissionKind;
}
private static PermissionDetailDto BuildHookPermissionDetail(
PermissionRequestHook hook,
IReadOnlyList<RunTurnMcpServerConfigDto>? configuredMcpServers)
{
string? serverName = ResolveHookMcpServerName(hook.ToolName, configuredMcpServers);
if (serverName is null)
{
return new PermissionDetailDto
{
Kind = HookPermissionKind,
Args = hook.ToolArgs,
HookMessage = NormalizeOptionalString(hook.HookMessage),
};
}
return new PermissionDetailDto
{
Kind = McpPermissionKind,
ServerName = serverName,
ToolTitle = ResolveHookMcpToolTitle(hook.ToolName, serverName),
Args = hook.ToolArgs,
};
}
private static string? ResolveConfiguredMcpServerName(RunTurnMcpServerConfigDto configuredServer)
=> NormalizeOptionalString(configuredServer.Name) ?? NormalizeOptionalString(configuredServer.Id);
private static bool MatchesHookMcpServerToolName(string toolName, string serverName)
{
if (string.Equals(toolName, serverName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
return toolName.StartsWith($"{serverName}-", StringComparison.OrdinalIgnoreCase);
}
private static string? ResolveHookMcpToolTitle(string? toolName, string serverName)
{
string? normalizedToolName = NormalizeOptionalString(toolName);
if (normalizedToolName is null)
{
return null;
}
string prefix = $"{serverName}-";
if (!normalizedToolName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
return normalizedToolName;
}
string strippedToolName = normalizedToolName[prefix.Length..];
return string.IsNullOrWhiteSpace(strippedToolName)
? normalizedToolName
: strippedToolName;
}
private static bool MatchesAutoApprovedTool(
IReadOnlyList<string> autoApprovedToolNames,
string? toolName,
@@ -479,6 +702,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,26 @@ internal static class CopilotSessionHooks
PatternAgentDefinitionDto agentDefinition,
PreToolUseHookInput input)
{
string? toolName = Normalize(input.ToolName);
if (IsAlwaysAllowedTool(toolName))
{
return new PreToolUseHookOutput
{
PermissionDecision = AllowDecision,
};
}
string? autoApprovedToolName = CopilotApprovalCoordinator.ResolveHookToolCategory(toolName) ?? toolName;
string? mcpServerApprovalKey = CopilotApprovalCoordinator.ResolveHookMcpServerApprovalKey(
toolName,
command.Tooling?.McpServers);
bool requiresApproval = CopilotApprovalCoordinator.RequiresToolCallApproval(
command.Pattern.ApprovalPolicy,
agentDefinition.Id,
Normalize(input.ToolName),
Normalize(input.ToolName));
toolName,
autoApprovedToolName,
mcpServerApprovalKey);
return new PreToolUseHookOutput
{
@@ -262,6 +300,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)
@@ -9,11 +9,13 @@ internal sealed class CopilotTurnExecutionState
{
private readonly RunTurnCommandDto _command;
private readonly HashSet<string> _startedAgents = new(StringComparer.OrdinalIgnoreCase);
private readonly HashSet<string> _reclassifiedMessageIds = new(StringComparer.Ordinal);
private readonly ConcurrentQueue<SidecarEventDto> _pendingEvents = new();
private readonly ConcurrentQueue<McpOauthRequiredEventDto> _pendingMcpOauthRequests = new();
private readonly ConcurrentDictionary<string, AgentIdentity> _observedAgentsByMessageId = new(StringComparer.Ordinal);
private readonly StreamingTranscriptBuffer _transcriptBuffer = new();
private int _fallbackMessageIndex;
private string? _lastObservedMessageId;
public CopilotTurnExecutionState(RunTurnCommandDto command)
{
@@ -79,15 +81,34 @@ internal sealed class CopilotTurnExecutionState
case AssistantMessageEvent assistantMessage when !string.IsNullOrWhiteSpace(assistantMessage.Data?.MessageId):
RecordObservedAgentForMessage(agent, assistantMessage.Data!.MessageId);
QueueThinkingIfNeeded(agent);
if (assistantMessage.Data?.ToolRequests is { Length: > 0 })
{
QueueMessageReclassifiedIfNeeded(assistantMessage.Data.MessageId);
}
break;
case ToolExecutionStartEvent toolExecutionStart
when !string.IsNullOrWhiteSpace(toolExecutionStart.Data?.ToolCallId)
&& !string.IsNullOrWhiteSpace(toolExecutionStart.Data?.ToolName):
ToolNamesByCallId[toolExecutionStart.Data.ToolCallId.Trim()] = toolExecutionStart.Data.ToolName.Trim();
QueueMessageReclassifiedIfNeeded(_lastObservedMessageId);
break;
case AssistantReasoningDeltaEvent:
case AssistantIntentEvent intentEvent:
ActiveAgent = agent;
QueueThinkingIfNeeded(agent);
AssistantIntentEventDto? assistantIntent = CreateAssistantIntentEvent(agent, intentEvent.Data);
if (assistantIntent is not null)
{
_pendingEvents.Enqueue(assistantIntent);
}
break;
case AssistantReasoningDeltaEvent reasoningDelta:
ActiveAgent = agent;
QueueThinkingIfNeeded(agent);
ReasoningDeltaEventDto? reasoningDeltaEvent = CreateReasoningDeltaEvent(agent, reasoningDelta.Data);
if (reasoningDeltaEvent is not null)
{
_pendingEvents.Enqueue(reasoningDeltaEvent);
}
break;
case SubagentStartedEvent started:
ActiveAgent = agent;
@@ -127,6 +148,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));
@@ -214,6 +239,23 @@ internal sealed class CopilotTurnExecutionState
{
ActiveAgent = agent;
_observedAgentsByMessageId[messageId] = agent;
_lastObservedMessageId = messageId;
}
private void QueueMessageReclassifiedIfNeeded(string? messageId)
{
if (string.IsNullOrWhiteSpace(messageId))
{
return;
}
string normalizedMessageId = messageId.Trim();
if (!_reclassifiedMessageIds.Add(normalizedMessageId))
{
return;
}
_pendingEvents.Enqueue(CreateMessageReclassifiedEvent(normalizedMessageId));
}
private AgentActivityEventDto? CreateThinkingActivityIfNeeded(AgentIdentity agent)
@@ -236,6 +278,18 @@ internal sealed class CopilotTurnExecutionState
};
}
private MessageReclassifiedEventDto CreateMessageReclassifiedEvent(string messageId)
{
return new MessageReclassifiedEventDto
{
Type = "message-reclassified",
RequestId = _command.RequestId,
SessionId = _command.SessionId,
MessageId = messageId,
NewKind = "thinking",
};
}
public void UpdateCompletedMessages(
IReadOnlyList<ChatMessage> allMessages,
IReadOnlyList<ChatMessage> inputMessages)
@@ -259,6 +313,14 @@ internal sealed class CopilotTurnExecutionState
ActiveAgent);
}
foreach (ChatMessageDto message in CompletedMessages)
{
if (_reclassifiedMessageIds.Contains(message.Id))
{
message.MessageKind = "thinking";
}
}
return CompletedMessages;
}
@@ -350,6 +412,50 @@ internal sealed class CopilotTurnExecutionState
};
}
private AssistantIntentEventDto? CreateAssistantIntentEvent(
AgentIdentity agent,
AssistantIntentData? data)
{
string? intent = data?.Intent?.Trim();
if (string.IsNullOrWhiteSpace(intent))
{
return null;
}
return new AssistantIntentEventDto
{
Type = "assistant-intent",
RequestId = _command.RequestId,
SessionId = _command.SessionId,
AgentId = agent.AgentId,
AgentName = agent.AgentName,
Intent = intent,
};
}
private ReasoningDeltaEventDto? CreateReasoningDeltaEvent(
AgentIdentity agent,
AssistantReasoningDeltaData? data)
{
if (data is null
|| string.IsNullOrWhiteSpace(data.ReasoningId)
|| string.IsNullOrEmpty(data.DeltaContent))
{
return null;
}
return new ReasoningDeltaEventDto
{
Type = "reasoning-delta",
RequestId = _command.RequestId,
SessionId = _command.SessionId,
AgentId = agent.AgentId,
AgentName = agent.AgentName,
ReasoningId = data.ReasoningId,
ContentDelta = data.DeltaContent,
};
}
private SkillInvokedEventDto CreateSkillInvokedEvent(
AgentIdentity agent,
SkillInvokedData? data)
@@ -410,6 +516,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,105 @@ 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);
}
[Theory]
[InlineData("view", "read")]
[InlineData("grep", "read")]
[InlineData("edit", "write")]
[InlineData("powershell", "shell")]
public async Task Create_PreToolUseAutoAllowsWhenCategoryIsApproved(string toolName, string category)
{
RunTurnCommandDto command = CreateCommandWithAutoApprovedCategory(category);
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_PreToolUseAutoAllowsWhenMcpServerIsApproved()
{
RunTurnCommandDto command = CreateCommandWithConfiguredMcpServers(
["icm-mcp"],
["mcp_server:icm-mcp"]);
SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], ResolvedHookSet.Empty, new RecordingHookCommandRunner());
PreToolUseHookOutput? decision = await hooks.OnPreToolUse!(
new PreToolUseHookInput
{
ToolName = "icm-mcp-get_incident_details_by_id",
},
null!);
Assert.Equal("allow", decision?.PermissionDecision);
}
[Fact]
public async Task Create_PreToolUseRequiresApprovalWhenMcpServerIsNotApproved()
{
RunTurnCommandDto command = CreateCommandWithConfiguredMcpServers(["icm-mcp"]);
SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], ResolvedHookSet.Empty, new RecordingHookCommandRunner());
PreToolUseHookOutput? decision = await hooks.OnPreToolUse!(
new PreToolUseHookInput
{
ToolName = "icm-mcp-get_incident_details_by_id",
},
null!);
Assert.Equal("ask", decision?.PermissionDecision);
}
[Fact]
public async Task Create_RunsConfiguredNonPreToolHooks()
{
@@ -264,6 +363,82 @@ public sealed class CopilotSessionHooksTests
};
}
private static RunTurnCommandDto CreateCommandWithAutoApprovedCategory(string category)
{
return new RunTurnCommandDto
{
RequestId = "turn-1",
SessionId = "session-1",
ProjectPath = @"C:\workspace\project",
Pattern = new PatternDefinitionDto
{
Id = "pattern-1",
Name = "Pattern",
Mode = "single",
Availability = "available",
ApprovalPolicy = new ApprovalPolicyDto
{
Rules =
[
new ApprovalCheckpointRuleDto
{
Kind = "tool-call",
AgentIds = ["agent-1"],
},
],
AutoApprovedToolNames = [category],
},
Agents =
[
new PatternAgentDefinitionDto
{
Id = "agent-1",
Name = "Primary",
Model = "gpt-5.4",
Instructions = "Help.",
},
],
},
};
}
private static RunTurnCommandDto CreateCommandWithConfiguredMcpServers(
IReadOnlyList<string> serverNames,
IReadOnlyList<string>? autoApprovedToolNames = null)
{
RunTurnCommandDto command = CreateCommandWithToolApproval();
return new RunTurnCommandDto
{
RequestId = command.RequestId,
SessionId = command.SessionId,
ProjectPath = command.ProjectPath,
Tooling = new RunTurnToolingConfigDto
{
McpServers = [.. serverNames.Select(CreateMcpServerConfig)],
},
Pattern = new PatternDefinitionDto
{
Id = command.Pattern.Id,
Name = command.Pattern.Name,
Mode = command.Pattern.Mode,
Availability = command.Pattern.Availability,
ApprovalPolicy = new ApprovalPolicyDto
{
Rules = command.Pattern.ApprovalPolicy?.Rules ?? [],
AutoApprovedToolNames = autoApprovedToolNames ?? [],
},
Agents = command.Pattern.Agents,
},
};
}
private static RunTurnMcpServerConfigDto CreateMcpServerConfig(string serverName)
=> new()
{
Id = serverName,
Name = serverName,
};
private static HookCommandDefinition CreateHookCommand(string name)
=> new()
{
@@ -1,6 +1,7 @@
using Aryx.AgentHost.Contracts;
using Aryx.AgentHost.Services;
using GitHub.Copilot.SDK;
using Microsoft.Extensions.AI;
namespace Aryx.AgentHost.Tests;
@@ -83,6 +84,132 @@ public sealed class CopilotTurnExecutionStateTests
Assert.Equal("view", toolName);
}
[Fact]
public void ObserveSessionEvent_AssistantMessageWithToolRequests_QueuesMessageReclassifiedEvent()
{
RunTurnCommandDto command = CreateCommand();
CopilotTurnExecutionState state = new(command);
state.ObserveSessionEvent(
command.Pattern.Agents[0],
SessionEvent.FromJson(
"""
{
"type": "assistant.message",
"data": {
"messageId": "msg-2",
"content": "Let me search for that.",
"toolRequests": [
{
"toolCallId": "tool-call-1",
"name": "rg",
"arguments": {
"pattern": "identifierUri"
}
}
]
},
"id": "3f75988b-8e69-4c90-a203-6b01d1c1f90b",
"timestamp": "2026-03-27T00:00:00Z"
}
"""));
IReadOnlyList<SidecarEventDto> pending = state.DrainPendingEvents();
AgentActivityEventDto thinking = Assert.Single(pending.OfType<AgentActivityEventDto>());
Assert.Equal("thinking", thinking.ActivityType);
MessageReclassifiedEventDto reclassified = Assert.Single(pending.OfType<MessageReclassifiedEventDto>());
Assert.Equal("session-1", reclassified.SessionId);
Assert.Equal("msg-2", reclassified.MessageId);
Assert.Equal("thinking", reclassified.NewKind);
}
[Fact]
public void ObserveSessionEvent_ToolExecutionStart_ReclassifiesLastObservedMessageOnce()
{
RunTurnCommandDto command = CreateCommand();
CopilotTurnExecutionState state = new(command);
state.ObserveSessionEvent(
command.Pattern.Agents[0],
SessionEvent.FromJson(
"""
{
"type": "assistant.message_delta",
"data": {
"messageId": "msg-3",
"deltaContent": "Searching"
},
"id": "0b65f0e9-d0fb-417e-ab5c-7a3343d8581b",
"timestamp": "2026-03-27T00:00:00Z"
}
"""));
_ = state.DrainPendingEvents();
state.ObserveSessionEvent(
command.Pattern.Agents[0],
SessionEvent.FromJson(
"""
{
"type": "tool.execution_start",
"data": {
"toolCallId": "tool-call-1",
"toolName": "rg"
},
"id": "8f33240e-bd3f-475c-aeb6-a4b7908e47b0",
"timestamp": "2026-03-27T00:00:01Z"
}
"""));
state.ObserveSessionEvent(
command.Pattern.Agents[0],
SessionEvent.FromJson(
"""
{
"type": "tool.execution_start",
"data": {
"toolCallId": "tool-call-2",
"toolName": "view"
},
"id": "a23f9c9a-f947-4282-866d-f599451c3899",
"timestamp": "2026-03-27T00:00:02Z"
}
"""));
IReadOnlyList<SidecarEventDto> pending = state.DrainPendingEvents();
MessageReclassifiedEventDto reclassified = Assert.Single(pending.OfType<MessageReclassifiedEventDto>());
Assert.Equal("msg-3", reclassified.MessageId);
Assert.True(state.ToolNamesByCallId.TryGetValue("tool-call-1", out string? firstToolName));
Assert.Equal("rg", firstToolName);
Assert.True(state.ToolNamesByCallId.TryGetValue("tool-call-2", out string? secondToolName));
Assert.Equal("view", secondToolName);
}
[Fact]
public void ObserveSessionEvent_AssistantMessageWithoutToolRequests_DoesNotQueueMessageReclassifiedEvent()
{
RunTurnCommandDto command = CreateCommand();
CopilotTurnExecutionState state = new(command);
state.ObserveSessionEvent(
command.Pattern.Agents[0],
SessionEvent.FromJson(
"""
{
"type": "assistant.message",
"data": {
"messageId": "msg-4",
"content": "Final answer."
},
"id": "d07fe954-1258-4f6a-bf79-1550d6143ed0",
"timestamp": "2026-03-27T00:00:00Z"
}
"""));
Assert.Empty(state.DrainPendingEvents().OfType<MessageReclassifiedEventDto>());
}
[Fact]
public async Task EmitThinkingIfNeeded_DoesNotDuplicateQueuedThinkingActivity()
{
@@ -119,6 +246,70 @@ public sealed class CopilotTurnExecutionStateTests
Assert.Equal("agent-1", thinking.AgentId);
}
[Fact]
public void ObserveSessionEvent_AssistantIntent_QueuesIntentEvent()
{
RunTurnCommandDto command = CreateCommand();
CopilotTurnExecutionState state = new(command);
state.ObserveSessionEvent(
command.Pattern.Agents[0],
SessionEvent.FromJson(
"""
{
"type": "assistant.intent",
"data": {
"intent": "Searching incident playbooks"
},
"id": "64cf59fe-63f0-4217-adf4-9bd6b3a80452",
"timestamp": "2026-03-27T00:00:00Z"
}
"""));
IReadOnlyList<SidecarEventDto> pending = state.DrainPendingEvents();
AgentActivityEventDto thinking = Assert.Single(pending.OfType<AgentActivityEventDto>());
Assert.Equal("thinking", thinking.ActivityType);
AssistantIntentEventDto intent = Assert.Single(pending.OfType<AssistantIntentEventDto>());
Assert.Equal("session-1", intent.SessionId);
Assert.Equal("agent-1", intent.AgentId);
Assert.Equal("Searching incident playbooks", intent.Intent);
}
[Fact]
public void ObserveSessionEvent_AssistantReasoningDelta_QueuesReasoningDeltaEvent()
{
RunTurnCommandDto command = CreateCommand();
CopilotTurnExecutionState state = new(command);
state.ObserveSessionEvent(
command.Pattern.Agents[0],
SessionEvent.FromJson(
"""
{
"type": "assistant.reasoning_delta",
"data": {
"reasoningId": "reasoning-2",
"deltaContent": "Searching logs."
},
"id": "bd269258-5e5d-46b6-bf3f-bd8cba793b1a",
"timestamp": "2026-03-27T00:00:00Z"
}
"""));
IReadOnlyList<SidecarEventDto> pending = state.DrainPendingEvents();
AgentActivityEventDto thinking = Assert.Single(pending.OfType<AgentActivityEventDto>());
Assert.Equal("thinking", thinking.ActivityType);
ReasoningDeltaEventDto reasoning = Assert.Single(pending.OfType<ReasoningDeltaEventDto>());
Assert.Equal("session-1", reasoning.SessionId);
Assert.Equal("agent-1", reasoning.AgentId);
Assert.Equal("reasoning-2", reasoning.ReasoningId);
Assert.Equal("Searching logs.", reasoning.ContentDelta);
}
[Fact]
public void DrainPendingMcpOauthRequests_ReturnsQueuedRequestsAndClearsQueue()
{
@@ -251,6 +442,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()
{
@@ -348,6 +602,56 @@ public sealed class CopilotTurnExecutionStateTests
""");
}
[Fact]
public void FinalizeCompletedMessages_TagsReclassifiedMessagesAsThinking()
{
RunTurnCommandDto command = CreateCommand();
CopilotTurnExecutionState state = new(command);
// Simulate assistant message with tool requests → triggers reclassification
state.ObserveSessionEvent(
command.Pattern.Agents[0],
SessionEvent.FromJson(
"""
{
"type": "assistant.message",
"data": {
"messageId": "msg-intermediate",
"content": "Let me search...",
"toolRequests": [
{
"toolCallId": "tool-call-1",
"name": "grep",
"arguments": {}
}
]
},
"id": "11111111-1111-1111-1111-111111111111",
"timestamp": "2026-03-27T00:00:00Z"
}
"""));
state.DrainPendingEvents();
// Build completed messages with a reclassified and a non-reclassified message
ChatMessage intermediateMsg = new(ChatRole.Assistant, "Let me search...");
intermediateMsg.MessageId = "msg-intermediate";
intermediateMsg.AuthorName = "Primary";
ChatMessage finalMsg = new(ChatRole.Assistant, "Here are the results.");
finalMsg.MessageId = "msg-final";
finalMsg.AuthorName = "Primary";
state.UpdateCompletedMessages([intermediateMsg, finalMsg], []);
IReadOnlyList<ChatMessageDto> messages = state.FinalizeCompletedMessages();
ChatMessageDto intermediate = Assert.Single(messages, m => m.Id == "msg-intermediate");
Assert.Equal("thinking", intermediate.MessageKind);
ChatMessageDto final_ = Assert.Single(messages, m => m.Id == "msg-final");
Assert.Null(final_.MessageKind);
}
private static RunTurnCommandDto CreateCommand()
{
return new RunTurnCommandDto
@@ -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()
{
@@ -1295,6 +1325,223 @@ public sealed class CopilotWorkflowRunnerTests
Assert.Equal("https://example.com", args["url"]);
}
[Fact]
public void BuildPermissionDetail_MapsConfiguredMcpHookToMcpDetail()
{
PermissionDetailDto detail = CopilotApprovalCoordinator.BuildPermissionDetail(
new PermissionRequestHook
{
Kind = "hook",
ToolName = "icm-mcp-get_incident_details_by_id",
ToolArgs = new Dictionary<string, object?>
{
["incidentId"] = 769904783,
},
},
[CreateMcpServerConfig("icm-mcp")]);
Assert.Equal("mcp", detail.Kind);
Assert.Equal("icm-mcp", detail.ServerName);
Assert.Equal("get_incident_details_by_id", detail.ToolTitle);
Dictionary<string, object?> args = Assert.IsType<Dictionary<string, object?>>(detail.Args);
Assert.Equal(769904783, args["incidentId"]);
}
[Theory]
[InlineData("view", "read")]
[InlineData("glob", "read")]
[InlineData("grep", "read")]
[InlineData("lsp", "read")]
[InlineData("edit", "write")]
[InlineData("create", "write")]
[InlineData("powershell", "shell")]
[InlineData("read_powershell", "shell")]
[InlineData("write_powershell", "shell")]
[InlineData("stop_powershell", "shell")]
[InlineData("list_powershell", "shell")]
[InlineData("web_fetch", "url")]
[InlineData("web_search", "url")]
[InlineData("store_memory", "memory")]
public void ResolveHookToolCategory_ReturnsExpectedCategoryForKnownTools(string toolName, string expectedCategory)
{
Assert.Equal(expectedCategory, CopilotApprovalCoordinator.ResolveHookToolCategory(toolName));
}
[Theory]
[InlineData("icm-mcp-get_on_call_schedule")]
[InlineData("custom_tool")]
[InlineData("unknown")]
public void ResolveHookToolCategory_ReturnsNullForUnknownTools(string toolName)
{
Assert.Null(CopilotApprovalCoordinator.ResolveHookToolCategory(toolName));
}
[Fact]
public void ResolveHookToolCategory_ReturnsNullForNullOrEmpty()
{
Assert.Null(CopilotApprovalCoordinator.ResolveHookToolCategory(null));
Assert.Null(CopilotApprovalCoordinator.ResolveHookToolCategory(""));
Assert.Null(CopilotApprovalCoordinator.ResolveHookToolCategory(" "));
}
[Fact]
public void ResolveHookMcpServerApprovalKey_PrefersLongestConfiguredServerName()
{
string? approvalKey = CopilotApprovalCoordinator.ResolveHookMcpServerApprovalKey(
"icm-mcp-get_on_call_schedule",
[CreateMcpServerConfig("icm"), CreateMcpServerConfig("icm-mcp")]);
Assert.Equal("mcp_server:icm-mcp", approvalKey);
}
[Fact]
public void TryGetApprovalToolName_ResolvesHookToolToCategory()
{
Assert.True(
CopilotApprovalCoordinator.TryGetApprovalToolName(
new PermissionRequestHook
{
Kind = "hook",
ToolName = "view",
ToolArgs = """{"path":"README.md"}""",
},
out string? toolName));
Assert.Equal("view", toolName);
// But the auto-approved name (fallback) resolves to the category
PermissionRequestHook hookRequest = new()
{
Kind = "hook",
ToolName = "view",
ToolArgs = """{"path":"README.md"}""",
};
// Verify GetFallbackToolName returns category via ResolveAutoApprovedToolName path
Assert.True(
CopilotApprovalCoordinator.TryGetApprovalToolName(
hookRequest,
out _));
}
[Fact]
public void RequiresToolCallApproval_HonorsHookToolCategoryForAutoApproval()
{
ApprovalPolicyDto policy = new()
{
Rules =
[
new ApprovalCheckpointRuleDto
{
Kind = "tool-call",
AgentIds = ["agent-1"],
},
],
AutoApprovedToolNames = ["read"],
};
// "view" is a hook tool that maps to "read" category — should be auto-approved
Assert.False(CopilotApprovalCoordinator.RequiresToolCallApproval(
policy, "agent-1", "view", "read"));
// "grep" also maps to "read"
Assert.False(CopilotApprovalCoordinator.RequiresToolCallApproval(
policy, "agent-1", "grep", "read"));
// "edit" maps to "write" — not auto-approved
Assert.True(CopilotApprovalCoordinator.RequiresToolCallApproval(
policy, "agent-1", "edit", "write"));
}
[Fact]
public void BuildPermissionApprovalEvent_UsesResolvedCategoryForHookPermissionKind()
{
ApprovalRequestedEventDto approvalEvent = CopilotApprovalCoordinator.BuildPermissionApprovalEvent(
new RunTurnCommandDto
{
RequestId = "turn-1",
SessionId = "session-1",
},
CreateAgent("agent-1", "Primary"),
new PermissionRequestHook
{
Kind = "hook",
ToolName = "view",
ToolArgs = """{"path":"README.md"}""",
},
new PermissionInvocation
{
SessionId = "copilot-session-1",
},
"approval-1",
"view");
Assert.Equal("view", approvalEvent.ToolName);
Assert.Equal("read", approvalEvent.PermissionKind);
Assert.Contains("read permission", approvalEvent.Detail);
}
[Fact]
public void BuildPermissionApprovalEvent_UsesMcpKindForConfiguredMcpHookTools()
{
ApprovalRequestedEventDto approvalEvent = CopilotApprovalCoordinator.BuildPermissionApprovalEvent(
new RunTurnCommandDto
{
RequestId = "turn-1",
SessionId = "session-1",
Tooling = new RunTurnToolingConfigDto
{
McpServers = [CreateMcpServerConfig("icm-mcp")],
},
},
CreateAgent("agent-1", "Primary"),
new PermissionRequestHook
{
Kind = "hook",
ToolName = "icm-mcp-get_schedule",
ToolArgs = """{"teamIds":[91982]}""",
},
new PermissionInvocation
{
SessionId = "copilot-session-1",
},
"approval-1",
"icm-mcp-get_schedule");
Assert.Equal("mcp", approvalEvent.PermissionKind);
Assert.Contains("mcp permission", approvalEvent.Detail);
Assert.NotNull(approvalEvent.PermissionDetail);
Assert.Equal("mcp", approvalEvent.PermissionDetail!.Kind);
Assert.Equal("icm-mcp", approvalEvent.PermissionDetail.ServerName);
Assert.Equal("get_schedule", approvalEvent.PermissionDetail.ToolTitle);
}
[Fact]
public void BuildPermissionApprovalEvent_KeepsHookKindForUnknownHookTools()
{
ApprovalRequestedEventDto approvalEvent = CopilotApprovalCoordinator.BuildPermissionApprovalEvent(
new RunTurnCommandDto
{
RequestId = "turn-1",
SessionId = "session-1",
},
CreateAgent("agent-1", "Primary"),
new PermissionRequestHook
{
Kind = "hook",
ToolName = "icm-mcp-get_schedule",
ToolArgs = """{"teamIds":[91982]}""",
},
new PermissionInvocation
{
SessionId = "copilot-session-1",
},
"approval-1",
"icm-mcp-get_schedule");
Assert.Equal("hook", approvalEvent.PermissionKind);
}
[Fact]
public async Task RequestApprovalAsync_RaisesApprovalAndCompletesAfterResolution()
{
@@ -1338,6 +1585,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()
{
@@ -1370,6 +1681,43 @@ public sealed class CopilotWorkflowRunnerTests
Assert.Equal(PermissionRequestResultKind.Approved, result.Kind);
}
[Fact]
public async Task RequestApprovalAsync_AutoApprovesHookRequestsForApprovedMcpServer()
{
CopilotApprovalCoordinator coordinator = new();
bool sawApproval = false;
RunTurnCommandDto command = CreateApprovalCommand(
autoApprovedToolNames: ["mcp_server:icm-mcp"],
mcpServers: [CreateMcpServerConfig("icm-mcp")]);
PermissionRequestResult result = await coordinator.RequestApprovalAsync(
command,
command.Pattern.Agents[0],
new PermissionRequestHook
{
Kind = "hook",
ToolName = "icm-mcp-get_incident_details_by_id",
ToolArgs = new Dictionary<string, object?>
{
["incidentId"] = 769904783,
},
},
new PermissionInvocation
{
SessionId = "copilot-session-1",
},
new Dictionary<string, string>(StringComparer.Ordinal),
approval =>
{
sawApproval = true;
return Task.CompletedTask;
},
CancellationToken.None);
Assert.False(sawApproval);
Assert.Equal(PermissionRequestResultKind.Approved, result.Kind);
}
[Fact]
public async Task RequestApprovalAsync_AlwaysApproveCachesRuntimeApprovalForCurrentTurn()
{
@@ -1610,12 +1958,21 @@ public sealed class CopilotWorkflowRunnerTests
null!);
}
private static RunTurnCommandDto CreateApprovalCommand(string requestId = "turn-1")
private static RunTurnCommandDto CreateApprovalCommand(
string requestId = "turn-1",
IReadOnlyList<string>? autoApprovedToolNames = null,
IReadOnlyList<RunTurnMcpServerConfigDto>? mcpServers = null)
{
return new RunTurnCommandDto
{
RequestId = requestId,
SessionId = "session-1",
Tooling = mcpServers is null
? null
: new RunTurnToolingConfigDto
{
McpServers = [.. mcpServers],
},
Pattern = new PatternDefinitionDto
{
Id = "pattern-1",
@@ -1632,7 +1989,9 @@ public sealed class CopilotWorkflowRunnerTests
AgentIds = ["agent-1"],
},
],
AutoApprovedToolNames = ["web_fetch"],
AutoApprovedToolNames = autoApprovedToolNames is null
? ["web_fetch"]
: [.. autoApprovedToolNames],
},
Agents =
[
@@ -1642,6 +2001,13 @@ public sealed class CopilotWorkflowRunnerTests
};
}
private static RunTurnMcpServerConfigDto CreateMcpServerConfig(string serverName)
=> new()
{
Id = serverName,
Name = serverName,
};
private sealed class StubChatClient : IChatClient
{
public Task<ChatResponse> GetResponseAsync(
@@ -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);
}
}
}
+1317 -130
View File
File diff suppressed because it is too large Load Diff
+141
View File
@@ -0,0 +1,141 @@
import { basename } from 'node:path';
import type {
ProjectGitCommitMessageSuggestion,
ProjectGitConventionalCommitType,
ProjectGitRunChangeSummary,
} from '@shared/domain/project';
import type { SessionRecord } from '@shared/domain/session';
import type { SessionRunRecord } from '@shared/domain/runTimeline';
interface BuildCommitMessageSuggestionInput {
session: Pick<SessionRecord, 'messages' | 'title'>;
run: Pick<SessionRunRecord, 'triggerMessageId'>;
summary?: ProjectGitRunChangeSummary;
conventionalType?: ProjectGitConventionalCommitType;
}
const COMMIT_TYPES: readonly ProjectGitConventionalCommitType[] = [
'feat',
'fix',
'refactor',
'docs',
'test',
'chore',
];
function normalizeWhitespace(value: string): string {
return value.replace(/\s+/g, ' ').trim();
}
function isCommitType(value: string | undefined): value is ProjectGitConventionalCommitType {
return value !== undefined && COMMIT_TYPES.includes(value as ProjectGitConventionalCommitType);
}
function findTriggerMessageContent(
session: Pick<SessionRecord, 'messages'>,
triggerMessageId: string,
): string | undefined {
return session.messages.find((message) => message.id === triggerMessageId)?.content;
}
function inferCommitTypeFromSummary(
prompt: string | undefined,
summary: ProjectGitRunChangeSummary | undefined,
): ProjectGitConventionalCommitType {
const promptText = normalizeWhitespace(prompt?.toLowerCase() ?? '');
const files = summary?.files ?? [];
const filePaths = files.map((file) => file.path.toLowerCase());
if (filePaths.length > 0 && filePaths.every((path) => path.endsWith('.md') || path.includes('readme'))) {
return 'docs';
}
if (filePaths.length > 0 && filePaths.every((path) => path.includes('test') || path.endsWith('.snap'))) {
return 'test';
}
if (/\b(fix|bug|error|issue|regression|broken|failure)\b/.test(promptText)) {
return 'fix';
}
if (/\b(refactor|cleanup|restructure|rename|simplify)\b/.test(promptText)) {
return 'refactor';
}
if (/\b(doc|readme|documentation)\b/.test(promptText)) {
return 'docs';
}
if (/\b(test|coverage|assertion)\b/.test(promptText)) {
return 'test';
}
if (/\b(chore|config|build|deps|dependency|tooling)\b/.test(promptText)) {
return 'chore';
}
return 'feat';
}
function stripPromptLead(text: string): string {
return text
.replace(/^[`"'“”‘’]+|[`"'“”‘’]+$/g, '')
.replace(/^(please\s+)?(can|could|would)\s+you\s+/i, '')
.replace(/^(implement|add|create|build|make|update|improve|refactor|fix|support|handle)\s+/i, '')
.replace(/[.?!:;]+$/g, '')
.trim();
}
function summarizeFiles(summary: ProjectGitRunChangeSummary | undefined): string | undefined {
const firstFile = summary?.files[0];
if (!summary || summary.files.length === 0 || !firstFile) {
return undefined;
}
if (summary.files.length === 1) {
return basename(firstFile.path).replace(/\.[^.]+$/, '');
}
return `${summary.fileCount} files`;
}
function buildSubject(
prompt: string | undefined,
summary: ProjectGitRunChangeSummary | undefined,
): string {
const normalizedPrompt = normalizeWhitespace(prompt ?? '');
if (normalizedPrompt) {
const firstSentence = normalizedPrompt.split(/[\r\n.?!]/, 1)[0] ?? normalizedPrompt;
const stripped = stripPromptLead(firstSentence);
if (stripped) {
return stripped
.replace(/\b(the|a|an)\s+/gi, '')
.replace(/\s+/g, ' ')
.trim()
.toLowerCase();
}
}
const fallback = summarizeFiles(summary);
if (fallback) {
return `update ${fallback}`.toLowerCase();
}
return 'update project changes';
}
export function buildProjectGitCommitMessageSuggestion(
input: BuildCommitMessageSuggestionInput,
): ProjectGitCommitMessageSuggestion {
const prompt = findTriggerMessageContent(input.session, input.run.triggerMessageId);
const type = isCommitType(input.conventionalType)
? input.conventionalType
: inferCommitTypeFromSummary(prompt, input.summary);
const subject = buildSubject(prompt, input.summary);
return {
type,
subject,
message: `${type}: ${subject}`,
};
}
+327
View File
@@ -0,0 +1,327 @@
import { Buffer } from 'node:buffer';
import { isUtf8 } from 'node:buffer';
import type {
ProjectGitBaselineFile,
ProjectGitDiffPreview,
ProjectGitRunChangeCounts,
ProjectGitRunChangeKind,
ProjectGitRunChangeSummary,
ProjectGitRunChangedFile,
ProjectGitWorkingTreeFile,
ProjectGitWorkingTreeSnapshot,
} from '@shared/domain/project';
interface DiffStats {
additions: number;
deletions: number;
}
interface BuildProjectGitRunChangeSummaryInput {
generatedAt: string;
preRunSnapshot?: ProjectGitWorkingTreeSnapshot;
preRunBaselineFiles?: readonly ProjectGitBaselineFile[];
postRunSnapshot?: ProjectGitWorkingTreeSnapshot;
postRunBaselineFiles?: readonly ProjectGitBaselineFile[];
}
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 += 1;
} else if (line.startsWith('-') && !line.startsWith('---')) {
deletions += 1;
}
}
return { additions, deletions };
}
function isBinaryDiff(diff: string | undefined): boolean {
if (!diff) {
return false;
}
return diff.includes('GIT binary patch') || diff.includes('Binary files ');
}
function decodeUtf8FromBase64(value: string | undefined): string | undefined {
if (value === undefined) {
return undefined;
}
const buffer = Buffer.from(value, 'base64');
return isUtf8(buffer) ? buffer.toString('utf8') : undefined;
}
function canRestoreBaseline(
baseline: ProjectGitBaselineFile | undefined,
): baseline is ProjectGitBaselineFile {
return baseline !== undefined
&& (baseline.untrackedContentBase64 !== undefined || baseline.combinedDiff !== undefined);
}
function previewFromBaselineFile(
file: Pick<ProjectGitWorkingTreeFile, 'path'>,
baseline: ProjectGitBaselineFile | undefined,
): ProjectGitDiffPreview | undefined {
if (!baseline) {
return undefined;
}
if (baseline.untrackedContentBase64 !== undefined) {
return {
path: file.path,
previousPath: baseline.previousPath,
newFileContents: decodeUtf8FromBase64(baseline.untrackedContentBase64),
...(baseline.isBinary ? { isBinary: true } : {}),
};
}
if (baseline.combinedDiff === undefined && baseline.isBinary !== true) {
return undefined;
}
return {
path: file.path,
previousPath: baseline.previousPath,
...(baseline.combinedDiff && !isBinaryDiff(baseline.combinedDiff)
? { diff: baseline.combinedDiff }
: {}),
...(baseline.isBinary || isBinaryDiff(baseline.combinedDiff) ? { isBinary: true } : {}),
};
}
function sameWorkingTreeFile(
left: ProjectGitWorkingTreeFile,
right: ProjectGitWorkingTreeFile,
): boolean {
return (
left.path === right.path
&& left.previousPath === right.previousPath
&& left.stagedStatus === right.stagedStatus
&& left.unstagedStatus === right.unstagedStatus
&& left.isConflicted === right.isConflicted
);
}
function sameBaselineFile(
left: ProjectGitBaselineFile | undefined,
right: ProjectGitBaselineFile | undefined,
): boolean {
if (!left && !right) {
return true;
}
if (!left || !right) {
return false;
}
return (
left.path === right.path
&& left.previousPath === right.previousPath
&& left.combinedDiff === right.combinedDiff
&& left.untrackedContentBase64 === right.untrackedContentBase64
&& left.isBinary === right.isBinary
);
}
function createRunChangeCounts(): ProjectGitRunChangeCounts {
return {
added: 0,
modified: 0,
deleted: 0,
renamed: 0,
copied: 0,
typeChanged: 0,
unmerged: 0,
untracked: 0,
cleaned: 0,
};
}
function incrementRunChangeCount(
counts: ProjectGitRunChangeCounts,
kind: ProjectGitRunChangeKind,
): void {
switch (kind) {
case 'added':
counts.added += 1;
break;
case 'modified':
counts.modified += 1;
break;
case 'deleted':
counts.deleted += 1;
break;
case 'renamed':
counts.renamed += 1;
break;
case 'copied':
counts.copied += 1;
break;
case 'type-changed':
counts.typeChanged += 1;
break;
case 'unmerged':
counts.unmerged += 1;
break;
case 'untracked':
counts.untracked += 1;
break;
case 'cleaned':
counts.cleaned += 1;
break;
}
}
function resolveRunChangeKind(file: ProjectGitWorkingTreeFile): ProjectGitRunChangeKind {
if (file.isConflicted) {
return 'unmerged';
}
return file.unstagedStatus ?? file.stagedStatus ?? 'modified';
}
function sortRunChangedFiles(
left: ProjectGitRunChangedFile,
right: ProjectGitRunChangedFile,
): number {
if (left.origin !== right.origin) {
return left.origin === 'run-created' ? -1 : 1;
}
return left.path.localeCompare(right.path);
}
export function buildProjectGitRunChangeSummary(
input: BuildProjectGitRunChangeSummaryInput,
): ProjectGitRunChangeSummary | undefined {
const {
generatedAt,
preRunSnapshot,
preRunBaselineFiles,
postRunSnapshot,
postRunBaselineFiles,
} = input;
if (!preRunSnapshot || !postRunSnapshot) {
return undefined;
}
const preRunFilesByPath = new Map(
preRunSnapshot.files.map((file) => [file.path, file] satisfies [string, ProjectGitWorkingTreeFile]),
);
const preRunBaselineByPath = new Map(
(preRunBaselineFiles ?? []).map((file) => [file.path, file] satisfies [string, ProjectGitBaselineFile]),
);
const postRunBaselineByPath = new Map(
(postRunBaselineFiles ?? []).map((file) => [file.path, file] satisfies [string, ProjectGitBaselineFile]),
);
const matchedPreRunPaths = new Set<string>();
const files: ProjectGitRunChangedFile[] = [];
for (const postRunFile of postRunSnapshot.files) {
const matchedPreRunFile = preRunFilesByPath.get(postRunFile.path)
?? (postRunFile.previousPath ? preRunFilesByPath.get(postRunFile.previousPath) : undefined);
const matchedPreRunPath = matchedPreRunFile?.path;
const postRunBaseline = postRunBaselineByPath.get(postRunFile.path);
if (!matchedPreRunFile || !matchedPreRunPath) {
const preview = previewFromBaselineFile(postRunFile, postRunBaseline);
const stats = parseDiffStats(preview?.diff);
files.push({
path: postRunFile.path,
previousPath: postRunFile.previousPath,
kind: resolveRunChangeKind(postRunFile),
origin: 'run-created',
stagedStatus: postRunFile.stagedStatus,
unstagedStatus: postRunFile.unstagedStatus,
...(postRunFile.isConflicted ? { isConflicted: true } : {}),
additions: stats.additions,
deletions: stats.deletions,
canRevert: true,
...(preview ? { preview } : {}),
});
continue;
}
matchedPreRunPaths.add(matchedPreRunPath);
const preRunBaseline = preRunBaselineByPath.get(matchedPreRunPath);
if (sameWorkingTreeFile(matchedPreRunFile, postRunFile) && sameBaselineFile(preRunBaseline, postRunBaseline)) {
continue;
}
const preview = previewFromBaselineFile(postRunFile, postRunBaseline);
const stats = parseDiffStats(preview?.diff);
files.push({
path: postRunFile.path,
previousPath: postRunFile.previousPath,
kind: resolveRunChangeKind(postRunFile),
origin: 'pre-existing',
stagedStatus: postRunFile.stagedStatus,
unstagedStatus: postRunFile.unstagedStatus,
...(postRunFile.isConflicted ? { isConflicted: true } : {}),
additions: stats.additions,
deletions: stats.deletions,
canRevert: canRestoreBaseline(preRunBaseline),
...(preview ? { preview } : {}),
});
}
for (const preRunFile of preRunSnapshot.files) {
if (matchedPreRunPaths.has(preRunFile.path)) {
continue;
}
const preRunBaseline = preRunBaselineByPath.get(preRunFile.path);
const preview = previewFromBaselineFile(preRunFile, preRunBaseline);
const stats = parseDiffStats(preview?.diff);
files.push({
path: preRunFile.path,
previousPath: preRunFile.previousPath,
kind: 'cleaned',
origin: 'pre-existing',
stagedStatus: preRunFile.stagedStatus,
unstagedStatus: preRunFile.unstagedStatus,
...(preRunFile.isConflicted ? { isConflicted: true } : {}),
additions: stats.additions,
deletions: stats.deletions,
canRevert: canRestoreBaseline(preRunBaseline),
...(preview ? { preview } : {}),
});
}
const branchChanged = preRunSnapshot.branch !== postRunSnapshot.branch;
if (files.length === 0 && !branchChanged) {
return undefined;
}
files.sort(sortRunChangedFiles);
const counts = createRunChangeCounts();
let additions = 0;
let deletions = 0;
for (const file of files) {
incrementRunChangeCount(counts, file.kind);
additions += file.additions;
deletions += file.deletions;
}
return {
generatedAt,
branchAtStart: preRunSnapshot.branch,
branchAtEnd: postRunSnapshot.branch,
...(branchChanged ? { branchChanged: true } : {}),
fileCount: files.length,
additions,
deletions,
counts,
files,
};
}
+604 -7
View File
@@ -1,9 +1,30 @@
import { isUtf8 } from 'node:buffer';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { promisify } from 'node:util';
import type { ProjectGitChangeSummary, ProjectGitCommitSummary, ProjectGitContext } from '@shared/domain/project';
import type {
ProjectGitBaselineFile,
ProjectGitBranchSummary,
ProjectGitChangeSummary,
ProjectGitCommitLogEntry,
ProjectGitCommitSummary,
ProjectGitContext,
ProjectGitDetails,
ProjectGitDiffPreview,
ProjectGitFileReference,
ProjectGitRunChangeSummary,
ProjectGitRunChangedFile,
ProjectGitWorkingTreeFile,
ProjectGitWorkingTreeFileStatus,
ProjectGitWorkingTreeSnapshot,
} from '@shared/domain/project';
import { nowIso } from '@shared/utils/ids';
import { buildProjectGitRunChangeSummary } from '@main/git/gitRunChangeSummary';
type ExecFileException = import('node:child_process').ExecFileException;
const require = createRequire(import.meta.url);
@@ -73,6 +94,11 @@ function isNotRepository(error: GitCommandFailure): boolean {
return detail.includes('not a git repository');
}
function isUnknownPathspec(error: GitCommandFailure): boolean {
const detail = `${error.message}\n${error.stderr ?? ''}`.toLowerCase();
return detail.includes('did not match any file') || detail.includes('pathspec');
}
function summarizeGitFailure(error: GitCommandFailure): string {
return error.stderr?.trim() || error.message;
}
@@ -102,9 +128,46 @@ function isConflictedStatus(x: string, y: string): boolean {
);
}
function parseChangeSummary(stdout: string): {
function parseWorkingTreeFileStatus(value: string): ProjectGitWorkingTreeFileStatus | undefined {
switch (value) {
case 'A':
return 'added';
case 'M':
return 'modified';
case 'D':
return 'deleted';
case 'R':
return 'renamed';
case 'C':
return 'copied';
case 'T':
return 'type-changed';
case 'U':
return 'unmerged';
case '?':
return 'untracked';
default:
return undefined;
}
}
function parseWorkingTreePath(rawPath: string): Pick<ProjectGitWorkingTreeFile, 'path' | 'previousPath'> {
const separator = ' -> ';
const separatorIndex = rawPath.indexOf(separator);
if (separatorIndex < 0) {
return { path: rawPath };
}
return {
previousPath: rawPath.slice(0, separatorIndex).trim(),
path: rawPath.slice(separatorIndex + separator.length).trim(),
};
}
function parseWorkingTree(stdout: string): {
changedFileCount: number;
changes: ProjectGitChangeSummary;
files: ProjectGitWorkingTreeFile[];
} {
const summary: ProjectGitChangeSummary = {
staged: 0,
@@ -112,6 +175,7 @@ function parseChangeSummary(stdout: string): {
untracked: 0,
conflicted: 0,
};
const files: ProjectGitWorkingTreeFile[] = [];
const lines = stdout
.split(/\r?\n/)
@@ -122,20 +186,42 @@ function parseChangeSummary(stdout: string): {
for (const line of lines) {
if (line.startsWith('??')) {
const path = line.slice(3).trim();
if (!path) {
continue;
}
summary.untracked += 1;
changedFileCount += 1;
files.push({
path,
unstagedStatus: 'untracked',
});
continue;
}
if (line.length < 2) {
if (line.length < 3) {
continue;
}
const x = line[0];
const y = line[1];
changedFileCount += 1;
const rawPath = line.slice(3).trim();
if (!rawPath) {
continue;
}
if (isConflictedStatus(x, y)) {
changedFileCount += 1;
const isConflicted = isConflictedStatus(x, y);
const pathInfo = parseWorkingTreePath(rawPath);
files.push({
...pathInfo,
stagedStatus: parseWorkingTreeFileStatus(x),
unstagedStatus: parseWorkingTreeFileStatus(y),
...(isConflicted ? { isConflicted: true } : {}),
});
if (isConflicted) {
summary.conflicted += 1;
continue;
}
@@ -152,6 +238,7 @@ function parseChangeSummary(stdout: string): {
return {
changedFileCount,
changes: summary,
files,
};
}
@@ -173,6 +260,122 @@ function parseHead(stdout: string): ProjectGitCommitSummary | undefined {
};
}
function parseBranchList(stdout: string): ProjectGitBranchSummary[] {
return stdout
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean)
.flatMap((line) => {
const [name, currentMarker, upstream] = line.split('\0');
const trimmedName = name?.trim();
if (!trimmedName) {
return [];
}
return [{
name: trimmedName,
isCurrent: currentMarker?.trim() === '*',
upstream: upstream?.trim() || undefined,
}];
});
}
function parseCommitLog(stdout: string): ProjectGitCommitLogEntry[] {
return stdout
.split('\x1e')
.map((record) => record.trim())
.filter(Boolean)
.flatMap((record) => {
const [hash, shortHash, authorName, subject, committedAt, refNames] = record.split('\0');
if (!hash || !shortHash || !authorName || !subject || !committedAt) {
return [];
}
return [{
hash: hash.trim(),
shortHash: shortHash.trim(),
authorName: authorName.trim(),
subject: subject.trim(),
committedAt: committedAt.trim(),
refNames: refNames?.trim() || undefined,
}];
});
}
function isPureUntrackedFile(file: ProjectGitWorkingTreeFile): boolean {
return file.stagedStatus === undefined && file.unstagedStatus === 'untracked';
}
function buildGitPaths(file: ProjectGitFileReference): string[] {
const paths = new Set<string>();
if (file.previousPath?.trim()) {
paths.add(file.previousPath.trim());
}
if (file.path.trim()) {
paths.add(file.path.trim());
}
return [...paths];
}
function uniqueGitPaths(files: readonly ProjectGitFileReference[]): string[] {
const paths = new Set<string>();
for (const file of files) {
for (const path of buildGitPaths(file)) {
paths.add(path);
}
}
return [...paths];
}
function isBinaryDiff(diff: string | undefined): boolean {
if (!diff) {
return false;
}
return diff.includes('GIT binary patch') || diff.includes('Binary files ');
}
function canRestoreBaseline(
baseline: ProjectGitBaselineFile | undefined,
): baseline is ProjectGitBaselineFile {
return baseline !== undefined
&& (baseline.untrackedContentBase64 !== undefined || baseline.combinedDiff !== undefined);
}
function baselineToPreview(
file: Pick<ProjectGitFileReference, 'path' | 'previousPath'>,
baseline: ProjectGitBaselineFile | undefined,
): ProjectGitDiffPreview | undefined {
if (!baseline) {
return undefined;
}
if (baseline.untrackedContentBase64 !== undefined) {
const contentBuffer = Buffer.from(baseline.untrackedContentBase64, 'base64');
return {
path: file.path,
previousPath: file.previousPath,
...(isUtf8(contentBuffer) ? { newFileContents: contentBuffer.toString('utf8') } : {}),
...(baseline.isBinary ? { isBinary: true } : {}),
};
}
if (baseline.combinedDiff === undefined && baseline.isBinary !== true) {
return undefined;
}
return {
path: file.path,
previousPath: file.previousPath,
...(baseline.combinedDiff && !isBinaryDiff(baseline.combinedDiff)
? { diff: baseline.combinedDiff }
: {}),
...(baseline.isBinary || isBinaryDiff(baseline.combinedDiff) ? { isBinary: true } : {}),
};
}
export class GitService {
constructor(private readonly runGitCommand: GitCommandRunner = defaultGitCommandRunner) {}
@@ -219,7 +422,7 @@ export class GitService {
this.tryRun(projectPath, ['log', '-1', '--format=%H%n%h%n%s%n%cI']),
]);
const { changedFileCount, changes } = parseChangeSummary(statusResult.stdout);
const { changedFileCount, changes } = parseWorkingTree(statusResult.stdout);
const upstream = upstreamResult.ok ? upstreamResult.stdout.trim() || undefined : undefined;
const aheadBehind = countsResult.ok ? parseAheadBehind(countsResult.stdout) : {};
@@ -238,11 +441,405 @@ export class GitService {
};
}
async describeProjectGitDetails(
projectPath: string,
scannedAt = nowIso(),
commitLimit = 20,
): Promise<ProjectGitDetails> {
const context = await this.describeProject(projectPath, scannedAt);
if (context.status !== 'ready') {
return {
scannedAt,
context,
branches: [],
recentCommits: [],
};
}
const [workingTree, branches, recentCommits] = await Promise.all([
this.captureWorkingTreeSnapshot(projectPath, scannedAt),
this.listBranches(projectPath),
this.listRecentCommits(projectPath, commitLimit),
]);
return {
scannedAt,
context,
workingTree: workingTree ?? undefined,
branches,
recentCommits,
};
}
async captureWorkingTreeSnapshot(
projectPath: string,
scannedAt = nowIso(),
): Promise<ProjectGitWorkingTreeSnapshot | undefined> {
const repoRootResult = await this.tryRun(projectPath, ['rev-parse', '--show-toplevel']);
if (!repoRootResult.ok) {
return undefined;
}
const statusResult = await this.tryRun(projectPath, ['status', '--porcelain=1', '--untracked-files=all']);
if (!statusResult.ok) {
return undefined;
}
const branchResult = await this.tryRun(projectPath, ['branch', '--show-current']);
const { changedFileCount, changes, files } = parseWorkingTree(statusResult.stdout);
return {
scannedAt,
repoRoot: repoRootResult.stdout.trim(),
branch: branchResult.ok ? parseBranch(branchResult.stdout) : undefined,
changedFileCount,
changes,
files,
};
}
async captureWorkingTreeBaseline(
projectPath: string,
snapshot?: ProjectGitWorkingTreeSnapshot,
): Promise<ProjectGitBaselineFile[]> {
const effectiveSnapshot = snapshot ?? await this.captureWorkingTreeSnapshot(projectPath);
if (!effectiveSnapshot || effectiveSnapshot.files.length === 0) {
return [];
}
const baselineFiles = await Promise.all(
effectiveSnapshot.files.map((file) => this.captureBaselineFile(projectPath, file)),
);
return baselineFiles.flatMap((file) => (file ? [file] : []));
}
async computeRunChangeSummary(
projectPath: string,
options: {
generatedAt?: string;
preRunSnapshot?: ProjectGitWorkingTreeSnapshot;
preRunBaselineFiles?: readonly ProjectGitBaselineFile[];
},
): Promise<ProjectGitRunChangeSummary | undefined> {
const generatedAt = options.generatedAt ?? nowIso();
const postRunSnapshot = await this.captureWorkingTreeSnapshot(projectPath, generatedAt);
if (!options.preRunSnapshot || !postRunSnapshot) {
return undefined;
}
const postRunBaselineFiles = await this.captureWorkingTreeBaseline(projectPath, postRunSnapshot);
return buildProjectGitRunChangeSummary({
generatedAt,
preRunSnapshot: options.preRunSnapshot,
preRunBaselineFiles: options.preRunBaselineFiles,
postRunSnapshot,
postRunBaselineFiles,
});
}
async getWorkingTreeFilePreview(
projectPath: string,
file: ProjectGitFileReference,
): Promise<ProjectGitDiffPreview | undefined> {
const snapshot = await this.captureWorkingTreeSnapshot(projectPath);
if (!snapshot) {
return undefined;
}
const matchedFile = snapshot.files.find((candidate) =>
candidate.path === file.path
|| candidate.previousPath === file.path
|| (file.previousPath !== undefined && candidate.path === file.previousPath)
|| (file.previousPath !== undefined && candidate.previousPath === file.previousPath));
if (!matchedFile) {
return undefined;
}
const baseline = await this.captureBaselineFile(projectPath, matchedFile);
return baselineToPreview(matchedFile, baseline);
}
async stageFiles(projectPath: string, files: readonly ProjectGitFileReference[]): Promise<void> {
const paths = uniqueGitPaths(files);
if (paths.length === 0) {
return;
}
await this.run(projectPath, ['add', '--', ...paths]);
}
async unstageFiles(projectPath: string, files: readonly ProjectGitFileReference[]): Promise<void> {
const paths = uniqueGitPaths(files);
if (paths.length === 0) {
return;
}
await this.run(projectPath, ['restore', '--staged', '--', ...paths]);
}
async commit(projectPath: string, message: string): Promise<ProjectGitCommitSummary> {
await this.run(projectPath, ['commit', '-m', message]);
const head = await this.getHeadCommit(projectPath);
if (!head) {
throw new Error('Git commit completed, but the new HEAD commit could not be resolved.');
}
return head;
}
async push(projectPath: string): Promise<void> {
await this.run(projectPath, ['push']);
}
async fetch(projectPath: string): Promise<void> {
await this.run(projectPath, ['fetch', '--all', '--prune']);
}
async pull(projectPath: string, rebase = false): Promise<void> {
await this.run(projectPath, rebase ? ['pull', '--rebase'] : ['pull']);
}
async createBranch(
projectPath: string,
name: string,
startPoint?: string,
checkout = true,
): Promise<void> {
const trimmedName = name.trim();
if (!trimmedName) {
throw new Error('A branch name is required.');
}
if (checkout) {
await this.run(
projectPath,
['switch', '-c', trimmedName, ...(startPoint?.trim() ? [startPoint.trim()] : [])],
);
return;
}
await this.run(
projectPath,
['branch', trimmedName, ...(startPoint?.trim() ? [startPoint.trim()] : [])],
);
}
async switchBranch(projectPath: string, name: string): Promise<void> {
const trimmedName = name.trim();
if (!trimmedName) {
throw new Error('A branch name is required.');
}
await this.run(projectPath, ['switch', trimmedName]);
}
async deleteBranch(projectPath: string, name: string, force = false): Promise<void> {
const trimmedName = name.trim();
if (!trimmedName) {
throw new Error('A branch name is required.');
}
await this.run(projectPath, ['branch', force ? '-D' : '-d', trimmedName]);
}
async listBranches(projectPath: string): Promise<ProjectGitBranchSummary[]> {
const result = await this.tryRun(projectPath, [
'for-each-ref',
'--format=%(refname:short)%00%(HEAD)%00%(upstream:short)',
'refs/heads',
]);
return result.ok ? parseBranchList(result.stdout) : [];
}
async listRecentCommits(projectPath: string, limit = 20): Promise<ProjectGitCommitLogEntry[]> {
const result = await this.tryRun(projectPath, [
'log',
`-n${Math.max(1, Math.round(limit))}`,
'--format=%H%x00%h%x00%an%x00%s%x00%cI%x00%D%x1e',
]);
return result.ok ? parseCommitLog(result.stdout) : [];
}
async discardRunChanges(
projectPath: string,
options: {
summary: ProjectGitRunChangeSummary;
preRunBaselineFiles?: readonly ProjectGitBaselineFile[];
files?: readonly ProjectGitFileReference[];
},
): Promise<void> {
const selectedFiles = options.files && options.files.length > 0
? options.summary.files.filter((candidate) =>
options.files?.some((selected) =>
selected.path === candidate.path
|| selected.path === candidate.previousPath
|| (selected.previousPath !== undefined && selected.previousPath === candidate.previousPath)))
: options.summary.files;
if (selectedFiles.length === 0) {
return;
}
const baselinesByPath = new Map(
(options.preRunBaselineFiles ?? []).map((file) => [file.path, file] satisfies [string, ProjectGitBaselineFile]),
);
for (const file of selectedFiles) {
if (file.origin === 'pre-existing') {
if (!file.canRevert) {
throw new Error(`Cannot restore "${file.path}" to its pre-run state because no restorable baseline was captured.`);
}
const baseline = baselinesByPath.get(file.previousPath ?? file.path) ?? baselinesByPath.get(file.path);
if (!canRestoreBaseline(baseline)) {
throw new Error(`Cannot restore "${file.path}" to its pre-run state because no restorable baseline was captured.`);
}
await this.restorePreExistingChange(projectPath, file, baseline);
continue;
}
await this.restoreRunCreatedChange(projectPath, file);
}
}
private async captureBaselineFile(
projectPath: string,
file: ProjectGitWorkingTreeFile,
): Promise<ProjectGitBaselineFile | undefined> {
if (!file.path.trim()) {
return undefined;
}
if (isPureUntrackedFile(file)) {
try {
const contents = await readFile(join(projectPath, file.path));
return {
path: file.path,
previousPath: file.previousPath,
untrackedContentBase64: contents.toString('base64'),
...(isUtf8(contents) ? {} : { isBinary: true }),
};
} catch {
return {
path: file.path,
previousPath: file.previousPath,
};
}
}
const diffPaths = buildGitPaths(file);
const diffResult = await this.tryRun(projectPath, [
'diff',
'--binary',
'--no-ext-diff',
'--no-renames',
'HEAD',
'--',
...diffPaths,
]);
if (!diffResult.ok) {
return {
path: file.path,
previousPath: file.previousPath,
};
}
return {
path: file.path,
previousPath: file.previousPath,
combinedDiff: diffResult.stdout.trim() ? diffResult.stdout : undefined,
...(isBinaryDiff(diffResult.stdout) ? { isBinary: true } : {}),
};
}
private async getHeadCommit(projectPath: string): Promise<ProjectGitCommitSummary | undefined> {
const result = await this.tryRun(projectPath, ['log', '-1', '--format=%H%n%h%n%s%n%cI']);
return result.ok ? parseHead(result.stdout) : undefined;
}
private async restoreRunCreatedChange(
projectPath: string,
file: ProjectGitRunChangedFile,
): Promise<void> {
if (file.kind === 'renamed' && file.previousPath) {
await this.restorePathFromHead(projectPath, file.previousPath);
await this.removePath(projectPath, file.path);
return;
}
if (file.kind === 'added' || file.kind === 'untracked' || file.kind === 'copied') {
await this.removePath(projectPath, file.path);
return;
}
await this.restorePathFromHead(projectPath, file.path);
}
private async restorePreExistingChange(
projectPath: string,
file: ProjectGitRunChangedFile,
baseline: ProjectGitBaselineFile,
): Promise<void> {
await this.restorePathFromHead(projectPath, baseline.path);
if (file.path !== baseline.path) {
await this.removePath(projectPath, file.path);
}
if (baseline.untrackedContentBase64 !== undefined) {
const contents = Buffer.from(baseline.untrackedContentBase64, 'base64');
await mkdir(dirname(join(projectPath, baseline.path)), { recursive: true });
await writeFile(join(projectPath, baseline.path), contents);
return;
}
if (baseline.combinedDiff) {
await this.applyPatch(projectPath, baseline.combinedDiff);
}
}
private async restorePathFromHead(projectPath: string, path: string): Promise<void> {
const result = await this.tryRun(projectPath, ['restore', '--source=HEAD', '--staged', '--worktree', '--', path]);
if (!result.ok && !isUnknownPathspec(result.error)) {
throw result.error;
}
}
private async removePath(projectPath: string, path: string): Promise<void> {
const unstageResult = await this.tryRun(projectPath, ['rm', '--cached', '--force', '--ignore-unmatch', '--', path]);
if (!unstageResult.ok && !isUnknownPathspec(unstageResult.error)) {
throw unstageResult.error;
}
await rm(join(projectPath, path), { force: true });
}
private async applyPatch(projectPath: string, diff: string): Promise<void> {
const tempDirectory = await mkdtemp(join(tmpdir(), 'aryx-git-patch-'));
const patchPath = join(tempDirectory, 'restore.diff');
try {
await writeFile(patchPath, diff, 'utf8');
await this.run(projectPath, ['apply', '--whitespace=nowarn', '--recount', patchPath]);
} finally {
await rm(tempDirectory, { force: true, recursive: true });
}
}
private async run(projectPath: string, args: string[]): Promise<string> {
try {
return await this.runGitCommand(projectPath, args);
} catch (error) {
throw createGitCommandFailure(projectPath, args, error);
}
}
private async tryRun(projectPath: string, args: string[]): Promise<GitCommandResult> {
try {
return {
ok: true,
stdout: await this.runGitCommand(projectPath, args),
stdout: await this.run(projectPath, args),
};
} catch (error) {
return {
+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();
});
+170 -6
View File
@@ -3,40 +3,72 @@ import type { BrowserWindow } from 'electron';
import { ipcChannels } from '@shared/contracts/channels';
import type {
BranchSessionInput,
CancelSessionTurnInput,
CreateSessionInput,
ResolveProjectDiscoveredToolingInput,
ResolveWorkspaceDiscoveredToolingInput,
DismissSessionPlanReviewInput,
CreateProjectGitBranchInput,
DismissSessionMcpAuthInput,
DismissSessionPlanReviewInput,
DeleteProjectGitBranchInput,
DeleteSessionInput,
DiscardSessionRunGitChangesInput,
EditAndResendSessionMessageInput,
CommitProjectGitChangesInput,
ProjectGitDetailsInput,
ProjectGitFilePreviewInput,
ProjectGitFileSelectionInput,
ProjectGitInput,
PullProjectGitInput,
RegenerateSessionMessageInput,
StartSessionMcpAuthInput,
SuggestProjectGitCommitMessageInput,
SwitchProjectGitBranchInput,
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 {
window.on('focus', () => {
if (service.isGitAutoRefreshEnabled()) {
service.scheduleProjectGitRefresh();
}
});
ipcMain.handle(ipcChannels.describeSidecarCapabilities, () => service.describeSidecarCapabilities());
ipcMain.handle(ipcChannels.refreshSidecarCapabilities, () => service.refreshSidecarCapabilities());
ipcMain.handle(ipcChannels.loadWorkspace, () => service.loadWorkspace());
@@ -50,14 +82,30 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
ipcMain.handle(ipcChannels.refreshProjectGitContext, (_event, projectId?: string) =>
service.refreshProjectGitContext(projectId),
);
ipcMain.handle(ipcChannels.getProjectGitDetails, (_event, input: ProjectGitDetailsInput) =>
service.getProjectGitDetails(input.projectId, input.commitLimit),
);
ipcMain.handle(ipcChannels.getProjectGitFilePreview, (_event, input: ProjectGitFilePreviewInput) =>
service.getProjectGitFilePreview(input.projectId, input.file),
);
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 +116,26 @@ 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.setGitAutoRefreshEnabled,
(_event, enabled: boolean) => service.setGitAutoRefreshEnabled(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 +148,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 +176,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 +194,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),
);
@@ -134,17 +224,65 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
ipcMain.handle(ipcChannels.startSessionMcpAuth, (_event, input: StartSessionMcpAuthInput) =>
service.startSessionMcpAuth(input.sessionId),
);
ipcMain.handle(
ipcChannels.discardSessionRunGitChanges,
(_event, input: DiscardSessionRunGitChangesInput) =>
service.discardSessionRunGitChanges(input.sessionId, input.runId, input.files),
);
ipcMain.handle(
ipcChannels.suggestProjectGitCommitMessage,
(_event, input: SuggestProjectGitCommitMessageInput) =>
service.suggestProjectGitCommitMessage(input.sessionId, input.runId, input.conventionalType),
);
ipcMain.handle(
ipcChannels.updateSessionModelConfig,
(_event, input: UpdateSessionModelConfigInput) =>
service.updateSessionModelConfig(input.sessionId, input.model, input.reasoningEffort),
);
ipcMain.handle(
ipcChannels.stageProjectGitFiles,
(_event, input: ProjectGitFileSelectionInput) => service.stageProjectGitFiles(input.projectId, input.files),
);
ipcMain.handle(
ipcChannels.unstageProjectGitFiles,
(_event, input: ProjectGitFileSelectionInput) => service.unstageProjectGitFiles(input.projectId, input.files),
);
ipcMain.handle(
ipcChannels.commitProjectGitChanges,
(_event, input: CommitProjectGitChangesInput) =>
service.commitProjectGitChanges(input.projectId, input.message, input.files, input.push),
);
ipcMain.handle(ipcChannels.pushProjectGit, (_event, input: ProjectGitInput) =>
service.pushProjectGit(input.projectId),
);
ipcMain.handle(ipcChannels.fetchProjectGit, (_event, input: ProjectGitInput) =>
service.fetchProjectGit(input.projectId),
);
ipcMain.handle(ipcChannels.pullProjectGit, (_event, input: PullProjectGitInput) =>
service.pullProjectGit(input.projectId, input.rebase),
);
ipcMain.handle(
ipcChannels.createProjectGitBranch,
(_event, input: CreateProjectGitBranchInput) =>
service.createProjectGitBranch(input.projectId, input.name, input.startPoint, input.checkout),
);
ipcMain.handle(
ipcChannels.switchProjectGitBranch,
(_event, input: SwitchProjectGitBranchInput) =>
service.switchProjectGitBranch(input.projectId, input.name),
);
ipcMain.handle(
ipcChannels.deleteProjectGitBranch,
(_event, input: DeleteProjectGitBranchInput) =>
service.deleteProjectGitBranch(input.projectId, input.name, input.force),
);
ipcMain.handle(ipcChannels.querySessions, (_event, input: QuerySessionsInput) => service.querySessions(input));
ipcMain.handle(ipcChannels.selectProject, (_event, projectId?: string) => service.selectProject(projectId));
ipcMain.handle(ipcChannels.selectPattern, (_event, patternId?: string) => service.selectPattern(patternId));
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 +291,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(),
});
}
+279
View File
@@ -0,0 +1,279 @@
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;
forceDevUpdateConfig: 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: 'up-to-date' });
};
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.forceDevUpdateConfig = !options.isPackaged;
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) {
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.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();
}
+9 -1
View File
@@ -3,6 +3,7 @@ import type {
ApprovalRequestedEvent,
ExitPlanModeRequestedEvent,
McpOauthRequiredEvent,
MessageReclassifiedEvent,
TurnDeltaEvent,
UserInputRequestedEvent,
SubagentEvent,
@@ -11,6 +12,9 @@ import type {
SessionUsageEvent,
SessionCompactionEvent,
PendingMessagesModifiedEvent,
AssistantUsageEvent,
AssistantIntentEvent,
ReasoningDeltaEvent,
} from '@shared/contracts/sidecar';
import type { ChatMessageRecord } from '@shared/domain/session';
@@ -20,7 +24,10 @@ export type TurnScopedEvent =
| HookLifecycleEvent
| SessionUsageEvent
| SessionCompactionEvent
| PendingMessagesModifiedEvent;
| PendingMessagesModifiedEvent
| AssistantUsageEvent
| AssistantIntentEvent
| ReasoningDeltaEvent;
export interface RunTurnPendingCommand {
kind: 'run-turn';
@@ -32,6 +39,7 @@ export interface RunTurnPendingCommand {
onUserInput: (event: UserInputRequestedEvent) => void | Promise<void>;
onMcpOAuthRequired: (event: McpOauthRequiredEvent) => void | Promise<void>;
onExitPlanMode: (event: ExitPlanModeRequestedEvent) => void | Promise<void>;
onMessageReclassified: (event: MessageReclassifiedEvent) => void | Promise<void>;
onTurnScopedEvent: (event: TurnScopedEvent) => void | Promise<void>;
errored: boolean;
}
+40 -1
View File
@@ -9,6 +9,7 @@ import type {
SidecarCapabilities,
SidecarEvent,
TurnDeltaEvent,
MessageReclassifiedEvent,
UserInputRequestedEvent,
McpOauthRequiredEvent,
ExitPlanModeRequestedEvent,
@@ -16,6 +17,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 +82,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);
@@ -127,9 +135,10 @@ export class SidecarClient {
onUserInput: (event: UserInputRequestedEvent) => void | Promise<void>,
onMcpOAuthRequired: (event: McpOauthRequiredEvent) => void | Promise<void>,
onExitPlanMode: (event: ExitPlanModeRequestedEvent) => void | Promise<void>,
onMessageReclassified: (event: MessageReclassifiedEvent) => void | Promise<void>,
onTurnScopedEvent: (event: TurnScopedEvent) => void | Promise<void>,
): Promise<ChatMessageRecord[]> {
return this.dispatch<ChatMessageRecord[]>(command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, onTurnScopedEvent);
return this.dispatch<ChatMessageRecord[]>(command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, onMessageReclassified, onTurnScopedEvent);
}
async resolveUserInput(userInputId: string, answer: string, wasFreeform: boolean): Promise<void> {
@@ -185,6 +194,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) {
@@ -272,6 +288,7 @@ export class SidecarClient {
onUserInput?: (event: UserInputRequestedEvent) => void | Promise<void>,
onMcpOAuthRequired?: (event: McpOauthRequiredEvent) => void | Promise<void>,
onExitPlanMode?: (event: ExitPlanModeRequestedEvent) => void | Promise<void>,
onMessageReclassified?: (event: MessageReclassifiedEvent) => void | Promise<void>,
onTurnScopedEvent?: (event: TurnScopedEvent) => void | Promise<void>,
): Promise<TResult> {
const state = await this.ensureProcess();
@@ -289,6 +306,7 @@ export class SidecarClient {
onUserInput: onUserInput ?? (() => undefined),
onMcpOAuthRequired: onMcpOAuthRequired ?? (() => undefined),
onExitPlanMode: onExitPlanMode ?? (() => undefined),
onMessageReclassified: onMessageReclassified ?? (() => undefined),
onTurnScopedEvent: onTurnScopedEvent ?? (() => undefined),
errored: false,
});
@@ -341,6 +359,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,
@@ -418,16 +443,30 @@ export class SidecarClient {
this.invokeRunTurnHandler(event.requestId, pending, () => pending.onExitPlanMode(event));
}
return;
case 'message-reclassified':
if (pending.kind === 'run-turn' && shouldHandleRunTurnEvent(pending)) {
this.invokeRunTurnHandler(event.requestId, pending, () => pending.onMessageReclassified(event));
}
return;
case 'subagent-event':
case 'skill-invoked':
case 'hook-lifecycle':
case 'session-usage':
case 'session-compaction':
case 'pending-messages-modified':
case 'assistant-usage':
case 'assistant-intent':
case 'reasoning-delta':
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);
+3
View File
@@ -21,6 +21,9 @@ export function createMainWindow(): BrowserWindowType {
}),
backgroundColor: '#09090b',
titleBarStyle: 'hidden',
...(process.platform === 'darwin' && {
trafficLightPosition: { x: 16, y: 22 },
}),
titleBarOverlay: {
color: '#09090b',
symbolColor: '#a1a1aa',
+65
View File
@@ -14,26 +14,52 @@ const api: ElectronApi = {
resolveWorkspaceDiscoveredTooling: (input) =>
ipcRenderer.invoke(ipcChannels.resolveWorkspaceDiscoveredTooling, input),
refreshProjectGitContext: (projectId) => ipcRenderer.invoke(ipcChannels.refreshProjectGitContext, projectId),
getProjectGitDetails: (input) => ipcRenderer.invoke(ipcChannels.getProjectGitDetails, input),
getProjectGitFilePreview: (input) => ipcRenderer.invoke(ipcChannels.getProjectGitFilePreview, input),
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),
setGitAutoRefreshEnabled: (enabled) => ipcRenderer.invoke(ipcChannels.setGitAutoRefreshEnabled, 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),
@@ -42,14 +68,40 @@ const api: ElectronApi = {
dismissSessionPlanReview: (input) => ipcRenderer.invoke(ipcChannels.dismissSessionPlanReview, input),
dismissSessionMcpAuth: (input) => ipcRenderer.invoke(ipcChannels.dismissSessionMcpAuth, input),
startSessionMcpAuth: (input) => ipcRenderer.invoke(ipcChannels.startSessionMcpAuth, input),
discardSessionRunGitChanges: (input) => ipcRenderer.invoke(ipcChannels.discardSessionRunGitChanges, input),
suggestProjectGitCommitMessage: (input) => ipcRenderer.invoke(ipcChannels.suggestProjectGitCommitMessage, input),
updateSessionModelConfig: (input) =>
ipcRenderer.invoke(ipcChannels.updateSessionModelConfig, input),
querySessions: (input) => ipcRenderer.invoke(ipcChannels.querySessions, input),
stageProjectGitFiles: (input) => ipcRenderer.invoke(ipcChannels.stageProjectGitFiles, input),
unstageProjectGitFiles: (input) => ipcRenderer.invoke(ipcChannels.unstageProjectGitFiles, input),
commitProjectGitChanges: (input) => ipcRenderer.invoke(ipcChannels.commitProjectGitChanges, input),
pushProjectGit: (input) => ipcRenderer.invoke(ipcChannels.pushProjectGit, input),
fetchProjectGit: (input) => ipcRenderer.invoke(ipcChannels.fetchProjectGit, input),
pullProjectGit: (input) => ipcRenderer.invoke(ipcChannels.pullProjectGit, input),
createProjectGitBranch: (input) => ipcRenderer.invoke(ipcChannels.createProjectGitBranch, input),
switchProjectGitBranch: (input) => ipcRenderer.invoke(ipcChannels.switchProjectGitBranch, input),
deleteProjectGitBranch: (input) => ipcRenderer.invoke(ipcChannels.deleteProjectGitBranch, input),
selectProject: (projectId) => ipcRenderer.invoke(ipcChannels.selectProject, projectId),
selectPattern: (patternId) => ipcRenderer.invoke(ipcChannels.selectPattern, patternId),
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 +116,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);
+478 -9
View File
@@ -1,24 +1,37 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { CommitComposer } from '@renderer/components/chat/CommitComposer';
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 { SettingsPanel } from '@renderer/components/SettingsPanel';
import { ProjectSettingsPanel } from '@renderer/components/ProjectSettingsPanel';
import { BookmarksPanel } from '@renderer/components/BookmarksPanel';
import { SessionSearchPanel } from '@renderer/components/SessionSearchPanel';
import { SettingsPanel, type SettingsSection } from '@renderer/components/SettingsPanel';
import { Sidebar } from '@renderer/components/Sidebar';
import { BottomPanel, DEFAULT_HEIGHT as DEFAULT_BOTTOM_HEIGHT, MIN_HEIGHT as MIN_BOTTOM_HEIGHT, type BottomPanelTab } from '@renderer/components/BottomPanel';
import { GitPanel } from '@renderer/components/GitPanel';
import { TerminalPanel } 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';
@@ -33,9 +46,11 @@ import { createDefaultToolApprovalPolicy } from '@shared/domain/approval';
import { listPendingDiscoveredMcpServers } from '@shared/domain/discoveredTooling';
import { syncPatternGraph, type PatternDefinition } from '@shared/domain/pattern';
import { isScratchpadProject, SCRATCHPAD_PROJECT_ID } from '@shared/domain/project';
import type { ProjectGitFileReference } from '@shared/domain/project';
import { applySessionModelConfig } from '@shared/domain/session';
import type { AppearanceTheme, LspProfileDefinition, McpServerDefinition } from '@shared/domain/tooling';
import type { WorkspaceState } from '@shared/domain/workspace';
import type { UpdateStatus } from '@shared/contracts/ipc';
import { createId, nowIso } from '@shared/utils/ids';
function createDraftPattern(defaultModelId: string, defaultReasoningEffort: PatternDefinition['agents'][0]['reasoningEffort']): PatternDefinition {
@@ -98,11 +113,32 @@ 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 [settingsSection, setSettingsSection] = useState<SettingsSection>();
const [updateStatus, setUpdateStatus] = useState<UpdateStatus>({ state: 'idle' });
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);
const [showBookmarks, setShowBookmarks] = useState(false);
// Commit composer state
const [commitComposerCtx, setCommitComposerCtx] = useState<{ projectId: string; sessionId: string; runId?: string }>();
// Bottom panel state (terminal + git)
const [bottomPanelOpen, setBottomPanelOpen] = useState(false);
const [bottomPanelTab, setBottomPanelTab] = useState<BottomPanelTab>('terminal');
const [bottomPanelHeight, setBottomPanelHeight] = useState(
() => workspace?.settings.terminalHeight ?? DEFAULT_BOTTOM_HEIGHT,
);
const [terminalRunning, setTerminalRunning] = useState(false);
const [gitDirty, setGitDirty] = useState(false);
// Load workspace on mount
useEffect(() => {
@@ -128,19 +164,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 () => {
@@ -150,6 +200,12 @@ export default function App() {
};
}, [api]);
// Subscribe to auto-update status pushes from the main process
useEffect(() => {
const off = api.onUpdateStatus((status) => setUpdateStatus(status));
return off;
}, [api]);
// Apply theme to the document root
const themeSetting: AppearanceTheme = workspace?.settings.theme ?? 'dark';
useTheme(themeSetting);
@@ -195,6 +251,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 +290,215 @@ 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();
handleTerminalToggle();
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+Shift+B — Bookmarks ──
if (mod && e.shiftKey && e.key === 'B') {
e.preventDefault();
setShowBookmarks((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 bottom panel height from workspace settings when workspace loads
useEffect(() => {
if (workspace?.settings.terminalHeight) {
setBottomPanelHeight(workspace.settings.terminalHeight);
}
}, [workspace?.settings.terminalHeight]);
const handleBottomPanelHeightChange = useCallback((newHeight: number) => {
const clamped = Math.max(MIN_BOTTOM_HEIGHT, Math.round(newHeight));
setBottomPanelHeight(clamped);
void api.setTerminalHeight({ height: clamped });
}, [api]);
const handleBottomPanelClose = useCallback(() => {
setBottomPanelOpen(false);
}, []);
const handleTerminalToggle = useCallback(() => {
setBottomPanelOpen((prev) => {
if (prev && bottomPanelTab === 'terminal') return false;
return true;
});
setBottomPanelTab('terminal');
}, [bottomPanelTab]);
const handleGitToggle = useCallback(() => {
setBottomPanelOpen((prev) => {
if (prev && bottomPanelTab === 'git') return false;
return true;
});
setBottomPanelTab('git');
}, [bottomPanelTab]);
const jumpToMessage = useCallback((messageId: string) => {
const element = document.querySelector(`[data-message-id="${CSS.escape(messageId)}"]`);
if (element) {
@@ -235,6 +508,20 @@ export default function App() {
}
}, []);
const handleDiscardRunChanges = useCallback(
(sessionId: string, runId: string, files?: ProjectGitFileReference[]) =>
api.discardSessionRunGitChanges({ sessionId, runId, files }),
[api],
);
const handleOpenCommitComposer = useCallback(() => {
if (!selectedSession) return;
setCommitComposerCtx({
projectId: selectedSession.projectId,
sessionId: selectedSession.id,
});
}, [selectedSession]);
const handleCreateScratchpad = useCallback(() => {
if (!workspace) return;
const singlePatterns = workspace.patterns
@@ -251,6 +538,32 @@ export default function App() {
}
}, [api, workspace]);
const handleOpenSettingsAt = useCallback((section?: SettingsSection) => {
setSettingsSection(section);
setShowSettings(true);
}, []);
const handleInstallUpdate = useCallback(() => {
void api.installUpdate();
}, [api]);
// 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,21 +633,49 @@ 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}
onGitToggle={!isScratchpadProject(selectedSession.projectId) ? handleGitToggle : undefined}
pattern={patternForSession}
project={projectForSession}
runtimeTools={sidecarCapabilities?.runtimeTools}
session={selectedSession}
sessionUsage={usageForSession}
activeSubagents={subagentsForSession}
terminalOpen={bottomPanelOpen && bottomPanelTab === 'terminal'}
terminalRunning={terminalRunning}
gitPanelOpen={bottomPanelOpen && bottomPanelTab === 'git'}
gitDirty={gitDirty}
toolingSettings={chatToolingSettings ?? workspace.settings.tooling}
/>
);
detailPanel = (
<ActivityPanel
activity={activityForSession}
onDiscard={handleDiscardRunChanges}
onJumpToMessage={jumpToMessage}
onOpenCommitComposer={handleOpenCommitComposer}
pattern={patternForSession}
session={selectedSession}
sessionRequestUsage={requestUsageForSession}
turnEvents={turnEventsForSession}
/>
);
@@ -342,6 +683,7 @@ export default function App() {
content = (
<WelcomePane
hasProjects={hasUserProjects}
connectionStatus={sidecarCapabilities?.connection.status}
onAddProject={() => void api.addProject()}
onNewScratchpad={() => handleCreateScratchpad()}
onOpenSettings={() => setShowSettings(true)}
@@ -353,8 +695,9 @@ export default function App() {
const overlay = showSettings ? (
<SettingsPanel
availableModels={availableModels}
initialSection={settingsSection}
isRefreshingCapabilities={isRefreshingCapabilities}
onClose={() => setShowSettings(false)}
onClose={() => { setShowSettings(false); setSettingsSection(undefined); }}
onDeleteLspProfile={async (id) => {
await api.deleteLspProfile(id);
}}
@@ -385,6 +728,12 @@ 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)}
gitAutoRefreshEnabled={workspace.settings.gitAutoRefreshEnabled !== false}
onSetGitAutoRefreshEnabled={(enabled) => void api.setGitAutoRefreshEnabled(enabled)}
onOpenAppDataFolder={() => void api.openAppDataFolder()}
onResetLocalWorkspace={async () => {
const fresh = await api.resetLocalWorkspace();
@@ -397,15 +746,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 +759,33 @@ export default function App() {
content={content}
detailPanel={detailPanel}
overlay={overlay}
bottomPanel={
bottomPanelOpen ? (
<BottomPanel
activeTab={bottomPanelTab}
gitContent={
selectedSession && !isScratchpadProject(selectedSession.projectId) ? (
<GitPanel
onDirtyChange={setGitDirty}
projectId={selectedSession.projectId}
/>
) : (
<div className="flex items-center justify-center py-8 text-[11px] text-[var(--color-text-muted)]">
Git is not available for scratchpad sessions
</div>
)
}
gitDirty={gitDirty}
height={bottomPanelHeight}
onClose={handleBottomPanelClose}
onHeightChange={handleBottomPanelHeightChange}
onTabChange={setBottomPanelTab}
showGitTab={!!selectedSession && !isScratchpadProject(selectedSession.projectId)}
terminalContent={<TerminalPanel onRunningChange={setTerminalRunning} />}
terminalRunning={terminalRunning}
/>
) : undefined
}
sidebar={
<Sidebar
onAddProject={() => void api.addProject()}
@@ -423,6 +794,7 @@ export default function App() {
setNewSessionProjectId(projectId);
}}
onOpenSettings={() => setShowSettings(true)}
onOpenProjectSettings={(projectId) => setProjectSettingsId(projectId)}
onProjectSelect={(projectId) => {
void api.selectProject(projectId);
}}
@@ -447,6 +819,9 @@ export default function App() {
onRefreshGitContext={(projectId) => {
void api.refreshProjectGitContext(projectId);
}}
updateStatus={updateStatus}
onViewUpdateDetails={() => handleOpenSettingsAt('troubleshooting')}
onInstallUpdate={handleInstallUpdate}
workspace={workspace}
/>
}
@@ -484,6 +859,100 @@ 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)}
onShowBookmarks={() => setShowBookmarks(true)}
/>
)}
{showShortcuts && (
<KeyboardShortcutsPanel onClose={() => setShowShortcuts(false)} />
)}
{showSearch && workspace && (
<SessionSearchPanel
workspace={workspace}
onClose={() => setShowSearch(false)}
onSelectSession={(sessionId) => {
void api.selectSession(sessionId);
}}
/>
)}
{showBookmarks && workspace && (
<BookmarksPanel
workspace={workspace}
onClose={() => setShowBookmarks(false)}
onSelectSession={(sessionId) => {
void api.selectSession(sessionId);
}}
onUnpinMessage={(sessionId, messageId) => {
void api.setSessionMessagePinned({ sessionId, messageId, isPinned: false });
}}
/>
)}
{commitComposerCtx && (
<CommitComposer
onClose={() => setCommitComposerCtx(undefined)}
projectId={commitComposerCtx.projectId}
runId={commitComposerCtx.runId}
sessionId={commitComposerCtx.sessionId}
/>
)}
</>
);
}
+136 -48
View File
@@ -1,30 +1,36 @@
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';
import { inferProvider } from '@shared/domain/models';
import type { OrchestrationMode, PatternAgentDefinition, PatternDefinition } from '@shared/domain/pattern';
import type { ProjectGitFileReference } from '@shared/domain/project';
import type { SessionRecord } from '@shared/domain/session';
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 +63,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 +76,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 +97,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 +110,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 +125,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 +142,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 +183,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)]`} />;
}
}
@@ -180,16 +209,22 @@ function formatTurnEventTimestamp(iso: string): string {
interface ActivityPanelProps {
activity?: SessionActivityState;
onJumpToMessage?: (messageId: string) => void;
onDiscard?: (sessionId: string, runId: string, files?: ProjectGitFileReference[]) => Promise<unknown>;
onOpenCommitComposer?: () => void;
pattern: PatternDefinition;
session: SessionRecord;
sessionRequestUsage?: SessionRequestUsageState;
turnEvents?: TurnEventLog;
}
export function ActivityPanel({
activity,
onJumpToMessage,
onDiscard,
onOpenCommitComposer,
pattern,
session,
sessionRequestUsage,
turnEvents,
}: ActivityPanelProps) {
const activityRows = useMemo(
@@ -208,19 +243,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 +266,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,35 +275,88 @@ 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>
)}
</SectionHeader>
<RunTimeline onJumpToMessage={onJumpToMessage} runs={session.runs} />
<RunTimeline
onDiscard={onDiscard}
onJumpToMessage={onJumpToMessage}
onOpenCommitComposer={onOpenCommitComposer}
runs={session.runs}
sessionId={session.id}
/>
</div>
{/* ── Turn events section ─────────────────────────── */}
@@ -277,12 +365,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 +378,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;
bottomPanel?: ReactNode;
overlay?: ReactNode;
}
export function AppShell({ sidebar, content, detailPanel, overlay }: AppShellProps) {
export function AppShell({ sidebar, content, detailPanel, bottomPanel, 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 + bottom panel */}
<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>
{bottomPanel}
</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>
);
+195
View File
@@ -0,0 +1,195 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Bookmark, BookmarkMinus, ArrowRight } from 'lucide-react';
import type { WorkspaceState } from '@shared/domain/workspace';
import { listPinnedMessages, type PinnedMessageHit } from '@shared/domain/sessionLibrary';
export interface BookmarksPanelProps {
workspace: WorkspaceState;
onClose: () => void;
onSelectSession: (sessionId: string) => void;
onUnpinMessage: (sessionId: string, messageId: string) => void;
}
export function BookmarksPanel({ workspace, onClose, onSelectSession, onUnpinMessage }: BookmarksPanelProps) {
const [selectedIndex, setSelectedIndex] = useState(0);
const listRef = useRef<HTMLDivElement>(null);
// 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]);
const hits = useMemo<PinnedMessageHit[]>(
() => listPinnedMessages(workspace),
[workspace],
);
// Clamp selected index when items are removed
useEffect(() => {
if (hits.length > 0 && selectedIndex >= hits.length) {
setSelectedIndex(hits.length - 1);
}
}, [hits.length, selectedIndex]);
const handleSelect = useCallback((hit: PinnedMessageHit) => {
onClose();
onSelectSession(hit.session.id);
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 handleUnpin = useCallback((e: React.MouseEvent, hit: PinnedMessageHit) => {
e.stopPropagation();
onUnpinMessage(hit.session.id, hit.message.id);
}, [onUnpinMessage]);
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-bookmark-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="Bookmarks"
>
<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}
tabIndex={-1}
ref={(el) => el?.focus()}
>
{/* Header */}
<div className="flex items-center gap-3 border-b border-[var(--color-border)] px-4 py-3.5">
<Bookmark className="size-4 shrink-0 text-[var(--color-text-accent)]" />
<span className="text-[14px] font-medium text-[var(--color-text-primary)]">
Bookmarks
</span>
<span className="text-[11px] text-[var(--color-text-muted)]">
{hits.length} {hits.length === 1 ? 'message' : 'messages'}
</span>
</div>
{/* List */}
<div ref={listRef} className="flex-1 overflow-y-auto py-1.5" role="listbox">
{hits.length === 0 ? (
<div className="flex flex-col items-center gap-2 px-4 py-10 text-center">
<Bookmark className="size-6 text-[var(--color-text-muted)]/40" />
<span className="text-[13px] text-[var(--color-text-muted)]">
No bookmarked messages yet
</span>
<span className="text-[11px] text-[var(--color-text-muted)]/60">
Pin messages from any session to save them here
</span>
</div>
) : (
hits.map((hit, index) => {
const isSelected = index === selectedIndex;
return (
<button
key={`${hit.session.id}-${hit.message.id}`}
data-bookmark-index={index}
className={`group/row flex w-full items-start gap-3 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"
>
<div className="flex min-w-0 flex-1 flex-col gap-1">
{/* Session title row */}
<div className="flex items-center gap-2">
<Bookmark
className={`size-3.5 shrink-0 fill-[var(--color-accent-sky)] text-[var(--color-accent-sky)]`}
/>
<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 */}
<div className="pl-5.5 text-[12px] leading-relaxed text-[var(--color-text-muted)]">
<span className="line-clamp-2">{hit.snippet}</span>
</div>
<div className="pl-5.5 text-[10px] text-[var(--color-text-muted)]">
{hit.message.role === 'user' ? 'You' : hit.message.authorName}
</div>
</div>
{/* Unpin button */}
<button
className="mt-1 flex size-6 shrink-0 items-center justify-center rounded-md text-[var(--color-text-muted)] opacity-0 transition-all duration-100 hover:bg-[var(--color-surface-2)] hover:text-[var(--color-status-error)] group-hover/row:opacity-100"
onClick={(e) => handleUnpin(e, hit)}
aria-label={`Unpin message from ${hit.session.title}`}
title="Remove bookmark"
type="button"
>
<BookmarkMinus className="size-3.5" />
</button>
</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>
);
}
+168
View File
@@ -0,0 +1,168 @@
import { useCallback, useRef, useState, type ReactNode } from 'react';
import { GitBranch, Minus, TerminalSquare, X } from 'lucide-react';
/* ── Constants ────────────────────────────────────────────── */
const MIN_HEIGHT = 120;
const MAX_HEIGHT_FRACTION = 0.7;
const DEFAULT_HEIGHT = 280;
/* ── Types ────────────────────────────────────────────────── */
export type BottomPanelTab = 'terminal' | 'git';
/* ── BottomPanel ──────────────────────────────────────────── */
interface BottomPanelProps {
activeTab: BottomPanelTab;
onTabChange: (tab: BottomPanelTab) => void;
onClose: () => void;
height: number;
onHeightChange: (height: number) => void;
terminalContent: ReactNode;
gitContent: ReactNode;
showGitTab: boolean;
terminalRunning?: boolean;
gitDirty?: boolean;
}
export function BottomPanel({
activeTab,
onTabChange,
onClose,
height,
onHeightChange,
terminalContent,
gitContent,
showGitTab,
terminalRunning,
gitDirty,
}: BottomPanelProps) {
const [isDragging, setIsDragging] = useState(false);
const dragStartRef = useRef<{ y: number; height: number } | null>(null);
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]);
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 panel"
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));
}
}}
/>
{/* Tab bar */}
<div className="flex h-8 shrink-0 items-center border-b border-[var(--color-border)] px-1">
{/* Terminal tab */}
<button
className={`flex items-center gap-1.5 rounded-md px-2.5 py-1 text-[11px] font-medium transition-colors duration-100 ${
activeTab === 'terminal'
? 'bg-[var(--color-surface-2)] text-[var(--color-text-primary)]'
: 'text-[var(--color-text-muted)] hover:bg-[var(--color-surface-2)]/50 hover:text-[var(--color-text-secondary)]'
}`}
onClick={() => onTabChange('terminal')}
type="button"
role="tab"
aria-selected={activeTab === 'terminal'}
>
{terminalRunning && <span className="size-1.5 shrink-0 rounded-full bg-emerald-400" />}
<TerminalSquare className="size-3" />
Terminal
</button>
{/* Git tab */}
{showGitTab && (
<button
className={`flex items-center gap-1.5 rounded-md px-2.5 py-1 text-[11px] font-medium transition-colors duration-100 ${
activeTab === 'git'
? 'bg-[var(--color-surface-2)] text-[var(--color-text-primary)]'
: 'text-[var(--color-text-muted)] hover:bg-[var(--color-surface-2)]/50 hover:text-[var(--color-text-secondary)]'
}`}
onClick={() => onTabChange('git')}
type="button"
role="tab"
aria-selected={activeTab === 'git'}
>
{gitDirty && <span className="size-1.5 shrink-0 rounded-full bg-[var(--color-status-warning)]" />}
<GitBranch className="size-3" />
Git
</button>
)}
<div className="flex-1" />
{/* Minimize */}
<button
aria-label="Minimize panel"
className="rounded p-1 text-[var(--color-text-muted)] transition hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]"
onClick={onClose}
type="button"
>
<Minus className="size-3" />
</button>
{/* Close */}
<button
aria-label="Close panel"
className="rounded p-1 text-[var(--color-text-muted)] transition hover:bg-[var(--color-surface-3)] hover:text-red-400"
onClick={onClose}
type="button"
>
<X className="size-3" />
</button>
</div>
{/* Tab content — both always mounted, only active one visible */}
<div className="relative min-h-0 flex-1">
<div className={`absolute inset-0 flex flex-col ${activeTab === 'terminal' ? '' : 'invisible'}`}>
{terminalContent}
</div>
{showGitTab && (
<div className={`absolute inset-0 flex flex-col overflow-y-auto ${activeTab === 'git' ? '' : 'hidden'}`}>
{gitContent}
</div>
)}
</div>
</div>
);
}
export { DEFAULT_HEIGHT, MIN_HEIGHT };
+368 -132
View File
@@ -1,20 +1,26 @@
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, InlineGitPill, InlineModelPill, InlineTerminalPill, InlineThinkingPill, InlineToolsPill } from '@renderer/components/chat/InlinePills';
import { InlinePromptPill } from '@renderer/components/chat/InlinePromptPill';
import { ThinkingDots } from '@renderer/components/chat/ThinkingDots';
import { ThinkingProcess } from '@renderer/components/chat/ThinkingProcess';
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 +29,10 @@ 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 ChatMessageRecord, type SessionBranchOriginAction, type SessionRecord } from '@shared/domain/session';
import {
countApprovedToolsInGroups,
groupApprovalToolsByProvider,
listApprovalToolDefinitions,
type RuntimeToolDefinition,
type SessionToolingSelection,
@@ -33,14 +41,24 @@ import {
/* ── ChatPane ──────────────────────────────────────────────── */
type DisplayItem =
| { type: 'message'; message: ChatMessageRecord }
| { type: 'thinking-group'; messages: ChatMessageRecord[]; turnStartedAt?: string };
interface ChatPaneProps {
project: ProjectRecord;
pattern: PatternDefinition;
session: SessionRecord;
availableModels: ReadonlyArray<ModelDefinition>;
toolingSettings: WorkspaceToolingSettings;
mcpProbingServerIds?: string[];
runtimeTools?: ReadonlyArray<RuntimeToolDefinition>;
sessionUsage?: SessionUsageState;
activeSubagents?: ReadonlyArray<ActiveSubagent>;
terminalOpen?: boolean;
terminalRunning?: boolean;
gitPanelOpen?: boolean;
gitDirty?: boolean;
onSend: (content: string, attachments?: ChatMessageAttachment[], messageMode?: MessageMode) => Promise<void>;
onCancelTurn?: () => void;
onResolveApproval?: (approvalId: string, decision: ApprovalDecision, alwaysApprove?: boolean) => Promise<unknown>;
@@ -49,12 +67,19 @@ interface ChatPaneProps {
onDismissPlanReview?: () => void;
onDismissMcpAuth?: () => void;
onAuthenticateMcp?: () => void;
onTerminalToggle?: () => void;
onGitToggle?: () => 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 +88,14 @@ export function ChatPane({
session,
availableModels,
toolingSettings,
mcpProbingServerIds,
runtimeTools,
sessionUsage,
activeSubagents,
terminalOpen,
terminalRunning,
gitPanelOpen,
gitDirty,
onSend,
onCancelTurn,
onResolveApproval,
@@ -73,9 +104,16 @@ export function ChatPane({
onDismissPlanReview,
onDismissMcpAuth,
onAuthenticateMcp,
onTerminalToggle,
onGitToggle,
onUpdateSessionModelConfig,
onUpdateSessionTooling,
onUpdateSessionApprovalSettings,
onBranchFromMessage,
onPinMessage,
onRegenerateMessage,
onEditAndResendMessage,
branchOriginLabel,
}: ChatPaneProps) {
const [hasComposerContent, setHasComposerContent] = useState(false);
const [configError, setConfigError] = useState<string>();
@@ -83,10 +121,56 @@ 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 displayItems = useMemo(() => {
const runsByTrigger = new Map(session.runs.map((r) => [r.triggerMessageId, r]));
const items: DisplayItem[] = [];
let pendingThinking: ChatMessageRecord[] = [];
let lastUserMessageId: string | undefined;
for (const message of session.messages) {
if (message.messageKind === 'thinking') {
pendingThinking.push(message);
} else {
if (pendingThinking.length > 0) {
const run = lastUserMessageId ? runsByTrigger.get(lastUserMessageId) : undefined;
items.push({ type: 'thinking-group', messages: pendingThinking, turnStartedAt: run?.startedAt });
pendingThinking = [];
}
items.push({ type: 'message', message });
if (message.role === 'user') {
lastUserMessageId = message.id;
}
}
}
if (pendingThinking.length > 0) {
const run = lastUserMessageId ? runsByTrigger.get(lastUserMessageId) : undefined;
items.push({ type: 'thinking-group', messages: pendingThinking, turnStartedAt: run?.startedAt });
}
return items;
}, [session.messages, session.runs]);
const lastThinkingGroupIndex = useMemo(() => {
for (let i = displayItems.length - 1; i >= 0; i--) {
if (displayItems[i].type === 'thinking-group') return i;
}
return -1;
}, [displayItems]);
const lastAssistantId = useMemo(() => {
for (let i = session.messages.length - 1; i >= 0; i--) {
const m = session.messages[i];
if (m.role === 'assistant' && m.messageKind !== 'thinking') return m.id;
}
return undefined;
}, [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 +191,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 +211,12 @@ 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);
return countApprovedToolsInGroups(groups, effectiveAutoApproved);
}, [approvalTools, effectiveAutoApproved, toolingSettings]);
const isProbingMcp = (mcpProbingServerIds?.length ?? 0) > 0;
const hasApprovalContent = approvalTools.length > 0 || isProbingMcp;
useEffect(() => {
transcriptRef.current?.scrollTo({
@@ -143,6 +230,7 @@ export function ChatPane({
setApprovalError(undefined);
setIsResolvingApproval(false);
setIsUpdatingSessionModelConfig(false);
setEditingMessageId(undefined);
}, [session.id]);
function handleComposerSubmit(content: string) {
@@ -152,6 +240,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,54 +323,71 @@ 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">
<GitBranch className="inline size-2.5" />
{project.git.branch ?? project.git.head?.shortHash ?? 'HEAD'}
{project.git.isDirty && (
<Circle className="inline size-1.5 fill-amber-500 text-amber-500" />
)}
{(project.git.ahead ?? 0) > 0 && <span>{project.git.ahead}</span>}
{(project.git.behind ?? 0) > 0 && <span>{project.git.behind}</span>}
</span>
)}
{!isScratchpad && project.git?.status === 'ready' && (() => {
const git = project.git;
const tipLines: string[] = [git.branch ?? git.head?.shortHash ?? 'HEAD'];
if (git.changes) {
const bd: string[] = [];
if (git.changes.staged > 0) bd.push(`${git.changes.staged} staged`);
if (git.changes.unstaged > 0) bd.push(`${git.changes.unstaged} modified`);
if (git.changes.untracked > 0) bd.push(`${git.changes.untracked} untracked`);
if (bd.length > 0) tipLines.push(bd.join(', '));
}
if (git.ahead || git.behind) {
const sync: string[] = [];
if (git.ahead) sync.push(`${git.ahead} ahead`);
if (git.behind) sync.push(`${git.behind} behind`);
tipLines.push(sync.join(', '));
}
return (
<span className="ml-2 inline-flex items-center gap-1 text-[var(--color-text-muted)]" title={tipLines.join('\n')}>
<GitBranch className="inline size-2.5" />
{git.branch ?? git.head?.shortHash ?? 'HEAD'}
{git.isDirty && (
<Circle className="inline size-1.5 fill-amber-500 text-amber-500" />
)}
{(git.ahead ?? 0) > 0 && <span>{git.ahead}</span>}
{(git.behind ?? 0) > 0 && <span>{git.behind}</span>}
</span>
);
})()}
</p>
</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,133 +399,190 @@ 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) => {
{displayItems.map((item, itemIndex) => {
if (item.type === 'thinking-group') {
const isLastThinkingGroup = itemIndex === lastThinkingGroupIndex;
return (
<div key={`thinking-${item.messages[0].id}`} className="py-2">
<ThinkingProcess
messages={item.messages}
isActive={isSessionBusy && isLastThinkingGroup}
turnStartedAt={item.turnStartedAt}
/>
</div>
);
}
const message = item.message;
const isUser = message.role === 'user';
const phase = getAssistantMessagePhase(session, message, index);
const isEditing = editingMessageId === message.id;
const isLastAssistant = message.id === lastAssistantId;
const phase = getAssistantMessagePhase(session, message);
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="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 ? <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">
<span>{message.authorName}</span>
{!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}`}
>
{phaseLabel}
</span>
)}
</div>
<div key={message.id}>
<div className="message-enter group py-3" data-message-id={message.id}>
<div className="flex gap-3">
<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}`
}
className={`mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-full ${
isUser ? 'brand-gradient-bg text-white' : 'bg-[var(--color-surface-2)] text-[var(--color-text-secondary)]'
}`}
>
{/* 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>
),
{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-[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}`}
>
{phaseLabel}
</span>
)}
{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>
)}
</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>
)}
{!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" />
)}
{message.pending && !message.content && <ThinkingDots />}
</div>
{message.pending && !message.content && <ThinkingDots />}
</div>
</div>
</div>
);
})}
</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 +590,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 +648,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 +686,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 +705,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 +726,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 +743,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 +767,40 @@ 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}
/>
)}
{onGitToggle && !isScratchpad && (
<InlineGitPill
isDirty={!!gitDirty}
isOpen={!!gitPanelOpen}
onToggle={onGitToggle}
/>
)}
{!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 +834,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 +849,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 +885,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 +909,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 +933,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>
);
}
+510
View File
@@ -0,0 +1,510 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
Archive,
Bookmark,
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;
onShowBookmarks: () => 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,
onShowBookmarks,
}: 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: 'view-bookmarks',
label: 'View Bookmarks',
category: 'General',
keywords: 'pin pinned bookmark bookmarked saved',
shortcut: shortcutKeys('bookmarks'),
icon: <Bookmark className={ICON} />,
action: onShowBookmarks,
});
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, onShowBookmarks,
]);
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>
);
}
+207 -50
View File
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useEffect, useState } from 'react';
import {
CheckCircle2,
XCircle,
@@ -12,12 +12,16 @@ import {
ArrowUpCircle,
User,
Building2,
BarChart3,
Loader2,
} from 'lucide-react';
import { CliInstallGuide } from '@renderer/components/settings/CliInstallGuide';
import type {
SidecarConnectionDiagnostics,
SidecarConnectionStatus,
SidecarCopilotCliVersionStatus,
QuotaSnapshot,
} from '@shared/contracts/sidecar';
interface CopilotStatusCardProps {
@@ -25,6 +29,7 @@ interface CopilotStatusCardProps {
modelCount: number;
isRefreshing: boolean;
onRefresh: () => void;
onGetQuota?: () => Promise<Record<string, QuotaSnapshot>>;
}
interface StatusConfig {
@@ -40,35 +45,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 +109,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 +277,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 +318,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 +348,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 +360,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 +379,31 @@ export function CopilotStatusCard({
<AccountSection connection={connection} />
)}
{/* 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">
{/* 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>
)}
{/* Installation guide for missing CLI */}
{connection.status === 'copilot-cli-missing' && (
<div className="rounded-lg border border-[var(--color-border)] bg-[var(--color-glass)] p-4">
<CliInstallGuide isRefreshing={isRefreshing} onRefresh={onRefresh} />
</div>
)}
{/* Action hint for other non-ready states */}
{!isHealthy && connection.status !== 'copilot-cli-missing' && config.actionLabel && (
<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 +411,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 +420,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 +450,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"
+616
View File
@@ -0,0 +1,616 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import {
AlertTriangle,
ArrowDownToLine,
ArrowUpFromLine,
Check,
ChevronDown,
ChevronRight,
Cloud,
FileCode2,
FileMinus2,
FilePlus2,
GitBranch,
GitCommitHorizontal,
History,
Loader2,
Plus,
RefreshCw,
Trash2,
X,
} from 'lucide-react';
import { getElectronApi } from '@renderer/lib/electronApi';
import type {
ProjectGitBranchSummary,
ProjectGitCommitLogEntry,
ProjectGitDetails,
ProjectGitDiffPreview,
ProjectGitWorkingTreeFile,
} from '@shared/domain/project';
/* ── Helpers ───────────────────────────────────────────────── */
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) : '';
}
function relativeTime(iso: string): string {
const diff = Date.now() - new Date(iso).getTime();
const secs = Math.floor(diff / 1000);
if (secs < 60) return 'just now';
const mins = Math.floor(secs / 60);
if (mins < 60) return `${mins}m ago`;
const hrs = Math.floor(mins / 60);
if (hrs < 24) return `${hrs}h ago`;
const days = Math.floor(hrs / 24);
if (days === 1) return 'yesterday';
if (days < 7) return `${days}d ago`;
return new Date(iso).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}
/* ── Section header ────────────────────────────────────────── */
function SectionHeader({
icon,
label,
count,
expanded,
onToggle,
}: {
icon: React.ReactNode;
label: string;
count?: number;
expanded: boolean;
onToggle: () => void;
}) {
return (
<button
className="flex w-full items-center gap-2 border-b border-[var(--color-border-subtle)] px-3 py-2 text-left transition-colors duration-100 hover:bg-[var(--color-surface-2)]/30"
onClick={onToggle}
type="button"
aria-expanded={expanded}
>
{expanded
? <ChevronDown className="size-2.5 text-[var(--color-text-muted)]" />
: <ChevronRight className="size-2.5 text-[var(--color-text-muted)]" />}
{icon}
<span className="font-display text-[10px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
{label}
</span>
{count !== undefined && count > 0 && (
<span className="rounded-full bg-[var(--color-surface-3)] px-1.5 py-0.5 text-[8px] font-semibold tabular-nums text-[var(--color-text-muted)]">
{count}
</span>
)}
</button>
);
}
/* ── File status icon ──────────────────────────────────────── */
function fileIcon(file: ProjectGitWorkingTreeFile) {
if (file.stagedStatus === 'added' || file.unstagedStatus === 'untracked') {
return <FilePlus2 className="size-3 shrink-0 text-[var(--color-status-success)]" />;
}
if (file.stagedStatus === 'deleted' || file.unstagedStatus === 'deleted') {
return <FileMinus2 className="size-3 shrink-0 text-[var(--color-status-error)]" />;
}
return <FileCode2 className="size-3 shrink-0 text-[var(--color-accent-sky)]" />;
}
/* ── Changed file row ──────────────────────────────────────── */
function ChangedFileEntry({
file,
projectId,
}: {
file: ProjectGitWorkingTreeFile;
projectId: string;
}) {
const api = getElectronApi();
const [expanded, setExpanded] = useState(false);
const [preview, setPreview] = useState<ProjectGitDiffPreview>();
const dir = fileDir(file.path);
const base = fileBaseName(file.path);
const status = file.stagedStatus ?? file.unstagedStatus ?? 'modified';
const handleToggle = useCallback(async () => {
if (expanded) {
setExpanded(false);
return;
}
setExpanded(true);
if (!preview) {
try {
const result = await api.getProjectGitFilePreview({
projectId,
file: { path: file.path, previousPath: file.previousPath },
});
if (result) setPreview(result);
} catch {
// Preview is best-effort
}
}
}, [api, expanded, file.path, file.previousPath, preview, projectId]);
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-3 py-[5px] text-left text-[10px] transition-colors duration-150 hover:bg-[var(--color-surface-2)]/40"
onClick={() => void handleToggle()}
type="button"
aria-expanded={expanded}
>
<ChevronRight
className={`size-2 shrink-0 text-[var(--color-text-muted)] transition-transform duration-150 ${expanded ? 'rotate-90' : ''}`}
/>
{fileIcon(file)}
<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>
<span className="shrink-0 rounded px-1 py-px text-[7px] font-semibold uppercase tracking-wider bg-[var(--color-surface-3)] text-[var(--color-text-muted)]">
{status}
</span>
</button>
{expanded && preview && (
<div className="border-t border-[var(--color-border-subtle)]">
<pre className="max-h-40 overflow-auto bg-[var(--color-surface-0)] px-3 py-1 font-mono text-[9px] leading-relaxed">
{preview.diff
? preview.diff.split('\n').map((line, i) => {
let cls = 'text-[var(--color-text-secondary)]';
if (line.startsWith('+') && !line.startsWith('+++')) cls = 'text-[var(--color-status-success)]';
else if (line.startsWith('-') && !line.startsWith('---')) cls = 'text-[var(--color-status-error)]';
else if (line.startsWith('@@')) cls = 'text-[var(--color-accent-sky)]';
return <div key={i} className={cls}>{line || '\u00A0'}</div>;
})
: preview.newFileContents
? preview.newFileContents.split('\n').map((line, i) => (
<div key={i} className="text-[var(--color-text-secondary)]">{line || '\u00A0'}</div>
))
: <div className="text-[var(--color-text-muted)] italic">Binary file</div>}
</pre>
</div>
)}
</div>
);
}
/* ── Branch row ────────────────────────────────────────────── */
function BranchRow({
branch,
onSwitch,
onDelete,
isSwitching,
}: {
branch: ProjectGitBranchSummary;
onSwitch: () => void;
onDelete: () => void;
isSwitching: boolean;
}) {
return (
<div className="flex items-center gap-1.5 px-3 py-[5px] text-[10px]">
<GitBranch className={`size-3 shrink-0 ${branch.isCurrent ? 'text-[var(--color-status-success)]' : 'text-[var(--color-text-muted)]'}`} />
<span className={`min-w-0 flex-1 truncate font-mono ${branch.isCurrent ? 'font-medium text-[var(--color-text-primary)]' : 'text-[var(--color-text-secondary)]'}`}>
{branch.name}
</span>
{branch.isCurrent && (
<span className="rounded px-1 py-px text-[7px] font-semibold uppercase tracking-wider bg-[var(--color-status-success)]/10 text-[var(--color-status-success)]">
current
</span>
)}
{!branch.isCurrent && (
<>
<button
className="rounded p-0.5 text-[var(--color-text-muted)] transition-colors duration-100 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]"
onClick={onSwitch}
type="button"
title={`Switch to ${branch.name}`}
disabled={isSwitching}
>
{isSwitching ? <Loader2 className="size-2.5 animate-spin" /> : <Check className="size-2.5" />}
</button>
<button
className="rounded p-0.5 text-[var(--color-text-muted)] transition-colors duration-100 hover:bg-[var(--color-status-error)]/10 hover:text-[var(--color-status-error)]"
onClick={onDelete}
type="button"
title={`Delete ${branch.name}`}
>
<Trash2 className="size-2.5" />
</button>
</>
)}
</div>
);
}
/* ── Commit log row ────────────────────────────────────────── */
function CommitRow({ commit }: { commit: ProjectGitCommitLogEntry }) {
return (
<div className="flex items-start gap-2 px-3 py-[5px] text-[10px]">
<GitCommitHorizontal className="mt-0.5 size-3 shrink-0 text-[var(--color-text-muted)]" />
<div className="min-w-0 flex-1">
<p className="truncate text-[var(--color-text-secondary)]">
{commit.subject}
</p>
<p className="flex items-center gap-1.5 text-[9px] text-[var(--color-text-muted)]">
<span className="font-mono">{commit.shortHash}</span>
<span>·</span>
<span>{commit.authorName}</span>
<span>·</span>
<span>{relativeTime(commit.committedAt)}</span>
</p>
</div>
</div>
);
}
/* ── Create branch dialog ──────────────────────────────────── */
function CreateBranchForm({
onSubmit,
onCancel,
}: {
onSubmit: (name: string) => void;
onCancel: () => void;
}) {
const [name, setName] = useState('');
return (
<div className="flex items-center gap-1.5 border-b border-[var(--color-border-subtle)] px-3 py-1.5">
<input
autoFocus
className="min-w-0 flex-1 rounded border border-[var(--color-border)] bg-[var(--color-surface-0)] px-2 py-1 font-mono text-[10px] text-[var(--color-text-primary)] placeholder:text-[var(--color-text-muted)] focus:border-[var(--color-accent)] focus:outline-none"
onChange={(e) => setName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && name.trim()) {
e.preventDefault();
onSubmit(name.trim());
} else if (e.key === 'Escape') {
e.preventDefault();
onCancel();
}
}}
placeholder="Branch name…"
value={name}
/>
<button
className="rounded p-1 text-[var(--color-status-success)] transition-colors duration-100 hover:bg-[var(--color-status-success)]/10 disabled:opacity-40"
disabled={!name.trim()}
onClick={() => onSubmit(name.trim())}
type="button"
>
<Check className="size-3" />
</button>
<button
className="rounded p-1 text-[var(--color-text-muted)] transition-colors duration-100 hover:bg-[var(--color-surface-3)]"
onClick={onCancel}
type="button"
>
<X className="size-3" />
</button>
</div>
);
}
/* ── Main export ───────────────────────────────────────────── */
interface GitPanelProps {
projectId: string;
onDirtyChange?: (isDirty: boolean) => void;
}
export function GitPanel({ projectId, onDirtyChange }: GitPanelProps) {
const api = getElectronApi();
const [details, setDetails] = useState<ProjectGitDetails>();
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [showChanges, setShowChanges] = useState(true);
const [showBranches, setShowBranches] = useState(false);
const [showHistory, setShowHistory] = useState(false);
const [showCreateBranch, setShowCreateBranch] = useState(false);
const [switchingBranch, setSwitchingBranch] = useState<string>();
const [operationError, setOperationError] = useState<string>();
const [networkBusy, setNetworkBusy] = useState<'push' | 'pull' | 'fetch'>();
const loadDetails = useCallback(async (quiet = false) => {
if (!quiet) setLoading(true);
else setRefreshing(true);
try {
const result = await api.getProjectGitDetails({ projectId });
setDetails(result);
setOperationError(undefined);
onDirtyChange?.(result.context.isDirty ?? false);
} catch (error) {
setOperationError(error instanceof Error ? error.message : String(error));
} finally {
setLoading(false);
setRefreshing(false);
}
}, [api, projectId]);
useEffect(() => {
void loadDetails();
}, [loadDetails]);
const ctx = details?.context;
const workingTree = details?.workingTree;
const branches = details?.branches ?? [];
const commits = details?.recentCommits ?? [];
const changedFiles = workingTree?.files ?? [];
const handlePush = useCallback(async () => {
setNetworkBusy('push');
setOperationError(undefined);
try {
await api.pushProjectGit({ projectId });
await loadDetails(true);
} catch (error) {
setOperationError(error instanceof Error ? error.message : String(error));
} finally {
setNetworkBusy(undefined);
}
}, [api, loadDetails, projectId]);
const handlePull = useCallback(async () => {
setNetworkBusy('pull');
setOperationError(undefined);
try {
await api.pullProjectGit({ projectId });
await loadDetails(true);
} catch (error) {
setOperationError(error instanceof Error ? error.message : String(error));
} finally {
setNetworkBusy(undefined);
}
}, [api, loadDetails, projectId]);
const handleFetch = useCallback(async () => {
setNetworkBusy('fetch');
setOperationError(undefined);
try {
await api.fetchProjectGit({ projectId });
await loadDetails(true);
} catch (error) {
setOperationError(error instanceof Error ? error.message : String(error));
} finally {
setNetworkBusy(undefined);
}
}, [api, loadDetails, projectId]);
const handleSwitchBranch = useCallback(async (name: string) => {
setSwitchingBranch(name);
setOperationError(undefined);
try {
await api.switchProjectGitBranch({ projectId, name });
await loadDetails(true);
} catch (error) {
setOperationError(error instanceof Error ? error.message : String(error));
} finally {
setSwitchingBranch(undefined);
}
}, [api, loadDetails, projectId]);
const handleDeleteBranch = useCallback(async (name: string) => {
setOperationError(undefined);
try {
await api.deleteProjectGitBranch({ projectId, name });
await loadDetails(true);
} catch (error) {
setOperationError(error instanceof Error ? error.message : String(error));
}
}, [api, loadDetails, projectId]);
const handleCreateBranch = useCallback(async (name: string) => {
setShowCreateBranch(false);
setOperationError(undefined);
try {
await api.createProjectGitBranch({ projectId, name, checkout: true });
await loadDetails(true);
} catch (error) {
setOperationError(error instanceof Error ? error.message : String(error));
}
}, [api, loadDetails, projectId]);
if (loading) {
return (
<div className="flex items-center justify-center py-8">
<Loader2 className="size-4 animate-spin text-[var(--color-text-muted)]" aria-label="Loading git status" />
</div>
);
}
if (!ctx || ctx.status !== 'ready') {
return (
<div className="px-3 py-4 text-center text-[11px] text-[var(--color-text-muted)]">
{ctx?.status === 'not-repository'
? 'Not a git repository'
: ctx?.status === 'git-missing'
? 'Git is not installed'
: ctx?.errorMessage ?? 'Unable to read git status'}
</div>
);
}
return (
<div className="flex flex-col">
{/* Branch header + network actions */}
<div className="border-b border-[var(--color-border-subtle)] px-3 py-2">
<div className="flex items-center gap-1.5">
<GitBranch className="size-3 text-[var(--color-accent-sky)]" />
<span className="font-mono text-[11px] font-medium text-[var(--color-text-primary)]">
{ctx.branch ?? 'detached HEAD'}
</span>
{ctx.upstream && (
<span className="text-[9px] text-[var(--color-text-muted)]">
{ctx.ahead !== undefined && ctx.ahead > 0 && <span className="text-[var(--color-status-success)]">{ctx.ahead}</span>}
{ctx.behind !== undefined && ctx.behind > 0 && <span className="ml-0.5 text-[var(--color-status-warning)]">{ctx.behind}</span>}
</span>
)}
<div className="flex-1" />
{/* Network buttons */}
<button
className="rounded p-1 text-[var(--color-text-muted)] transition-colors duration-100 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)] disabled:opacity-40"
disabled={!!networkBusy}
onClick={() => void handleFetch()}
title="Fetch"
type="button"
>
{networkBusy === 'fetch' ? <Loader2 className="size-3 animate-spin" /> : <Cloud className="size-3" />}
</button>
<button
className="rounded p-1 text-[var(--color-text-muted)] transition-colors duration-100 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)] disabled:opacity-40"
disabled={!!networkBusy}
onClick={() => void handlePull()}
title="Pull"
type="button"
>
{networkBusy === 'pull' ? <Loader2 className="size-3 animate-spin" /> : <ArrowDownToLine className="size-3" />}
</button>
<button
className="rounded p-1 text-[var(--color-text-muted)] transition-colors duration-100 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)] disabled:opacity-40"
disabled={!!networkBusy}
onClick={() => void handlePush()}
title="Push"
type="button"
>
{networkBusy === 'push' ? <Loader2 className="size-3 animate-spin" /> : <ArrowUpFromLine className="size-3" />}
</button>
<button
className="rounded p-1 text-[var(--color-text-muted)] transition-colors duration-100 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]"
onClick={() => void loadDetails(true)}
title="Refresh"
type="button"
>
<RefreshCw className={`size-3 ${refreshing ? 'animate-spin' : ''}`} />
</button>
</div>
{ctx.isDirty && (
<div className="mt-1 text-[9px] text-[var(--color-status-warning)]">
{ctx.changedFileCount} uncommitted {ctx.changedFileCount === 1 ? 'change' : 'changes'}
</div>
)}
</div>
{/* Error */}
{operationError && (
<div className="flex items-start gap-1.5 border-b border-[var(--color-status-error)]/20 bg-[var(--color-status-error)]/5 px-3 py-1.5 text-[9px] text-[var(--color-status-error)]" role="alert">
<AlertTriangle className="mt-0.5 size-3 shrink-0" />
<span className="min-w-0 flex-1">{operationError}</span>
<button
className="shrink-0 rounded p-0.5 transition-colors duration-100 hover:bg-[var(--color-status-error)]/10"
onClick={() => setOperationError(undefined)}
type="button"
aria-label="Dismiss error"
>
<X className="size-2.5" />
</button>
</div>
)}
{/* Changed files */}
<SectionHeader
count={changedFiles.length}
expanded={showChanges}
icon={<FileCode2 className="size-3 text-[var(--color-accent-sky)]" />}
label="Changes"
onToggle={() => setShowChanges(!showChanges)}
/>
{showChanges && (
<div>
{changedFiles.length === 0 ? (
<p className="px-3 py-2 text-[10px] text-[var(--color-text-muted)]">Working tree clean</p>
) : (
changedFiles.map((file) => (
<ChangedFileEntry
file={file}
key={file.path}
projectId={projectId}
/>
))
)}
</div>
)}
{/* Branches */}
<SectionHeader
count={branches.length}
expanded={showBranches}
icon={<GitBranch className="size-3 text-[var(--color-status-success)]" />}
label="Branches"
onToggle={() => setShowBranches(!showBranches)}
/>
{showBranches && (
<div>
{/* New branch button */}
{!showCreateBranch && (
<button
className="flex w-full items-center gap-1.5 px-3 py-[5px] text-[10px] text-[var(--color-text-muted)] transition-colors duration-100 hover:bg-[var(--color-surface-2)]/40 hover:text-[var(--color-text-accent)]"
onClick={() => setShowCreateBranch(true)}
type="button"
>
<Plus className="size-3" />
New branch
</button>
)}
{showCreateBranch && (
<CreateBranchForm
onCancel={() => setShowCreateBranch(false)}
onSubmit={(name) => void handleCreateBranch(name)}
/>
)}
{branches.map((branch) => (
<BranchRow
branch={branch}
isSwitching={switchingBranch === branch.name}
key={branch.name}
onDelete={() => void handleDeleteBranch(branch.name)}
onSwitch={() => void handleSwitchBranch(branch.name)}
/>
))}
</div>
)}
{/* Commit history */}
<SectionHeader
count={commits.length}
expanded={showHistory}
icon={<History className="size-3 text-[var(--color-text-muted)]" />}
label="Recent Commits"
onToggle={() => setShowHistory(!showHistory)}
/>
{showHistory && (
<div>
{commits.length === 0 ? (
<p className="px-3 py-2 text-[10px] text-[var(--color-text-muted)]">No commit history</p>
) : (
commits.map((commit) => (
<CommitRow commit={commit} key={commit.hash} />
))
)}
</div>
)}
</div>
);
}
@@ -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) {
+179 -86
View File
@@ -8,6 +8,7 @@ import {
ChevronDown,
ChevronRight,
CircleDot,
GitBranch,
MessageSquare,
Play,
Wrench,
@@ -25,51 +26,71 @@ import {
type CollapsedTimelineEvent,
} from '@renderer/lib/runTimelineFormatting';
import type { OrchestrationMode } from '@shared/domain/pattern';
import type { ProjectGitFileReference, ProjectGitWorkingTreeSnapshot } from '@shared/domain/project';
import type { RunTimelineEventRecord, SessionRunRecord } from '@shared/domain/runTimeline';
import { FileChangePreview } from '@renderer/components/chat/FileChangePreview';
import { RunChangeSummaryCard } from '@renderer/components/chat/RunChangeSummaryCard';
/* ── 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 ───────────────────────────────────────── */
function EventIcon({ kind, status }: { kind: RunTimelineEventRecord['kind']; status: RunTimelineEventRecord['status'] }) {
const base = 'size-3.5';
const isRunning = status === 'running';
const base = 'size-2.5';
// Running events use white icons to contrast with the brand-gradient circle
if (isRunning) {
const pulse = 'animate-pulse';
switch (kind) {
case 'thinking':
return <Brain className={`${base} ${pulse} text-white`} />;
case 'approval':
return <AlertTriangle className={`${base} ${pulse} text-white`} />;
case 'message':
return <MessageSquare className={`${base} ${pulse} text-white`} />;
default:
return <Play className={`${base} text-white`} />;
}
}
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} 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 === '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 === '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 +112,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-[9px] 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-[18px] 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 +199,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-[9px] 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-[18px] items-center justify-center rounded-full bg-[var(--color-surface-2)]">
<Brain className="size-2.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>
@@ -202,6 +232,39 @@ function CollapsedEventRow({
return <TimelineEventRow event={item.event} isLast={isLast} onJumpToMessage={onJumpToMessage} />;
}
/* ── Git baseline snapshot ──────────────────────────────────── */
function RunGitBaseline({ snapshot }: { snapshot: ProjectGitWorkingTreeSnapshot }) {
const { branch, changes, changedFileCount } = snapshot;
const parts: string[] = [];
if (changes.staged > 0) parts.push(`${changes.staged} staged`);
if (changes.unstaged > 0) parts.push(`${changes.unstaged} modified`);
if (changes.untracked > 0) parts.push(`${changes.untracked} untracked`);
if (changes.conflicted > 0) parts.push(`${changes.conflicted} conflicted`);
return (
<div className="mb-1.5 flex items-center gap-1.5 text-[9px] text-[var(--color-text-muted)]">
<GitBranch className="size-2.5 shrink-0" />
{branch && <span className="font-mono text-[var(--color-text-secondary)]">{branch}</span>}
{changedFileCount > 0 ? (
<>
<span>·</span>
<span className="text-[var(--color-status-warning)]">{changedFileCount} changed</span>
{parts.length > 0 && (
<span className="text-[var(--color-text-muted)]">({parts.join(', ')})</span>
)}
</>
) : (
<>
<span>·</span>
<span className="text-[var(--color-status-success)]">clean</span>
</>
)}
</div>
);
}
/* ── Run card ──────────────────────────────────────────────── */
function RunCard({
@@ -209,11 +272,17 @@ function RunCard({
expanded,
onToggle,
onJumpToMessage,
sessionId,
onDiscard,
onOpenCommitComposer,
}: {
run: SessionRunRecord;
expanded: boolean;
onToggle: () => void;
onJumpToMessage?: (messageId: string) => void;
sessionId: string;
onDiscard?: (sessionId: string, runId: string, files?: ProjectGitFileReference[]) => Promise<unknown>;
onOpenCommitComposer?: () => void;
}) {
const accent = modeAccent[run.patternMode] ?? modeAccent.single;
const statusStyle = runStatusStyles[run.status];
@@ -225,26 +294,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 +321,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}
@@ -267,6 +336,11 @@ function RunCard({
</div>
)}
{/* Git baseline */}
{run.preRunGitSnapshot && (
<RunGitBaseline snapshot={run.preRunGitSnapshot} />
)}
{/* Timeline events */}
<div>
{collapsedEvents.map((item, index) => (
@@ -281,10 +355,23 @@ 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>
)}
{/* Post-run git changes */}
{run.postRunGitSummary && run.status !== 'running' && onDiscard && (
<div className="mt-2">
<RunChangeSummaryCard
onDiscard={onDiscard}
onOpenCommitComposer={onOpenCommitComposer}
runId={run.requestId}
sessionId={sessionId}
summary={run.postRunGitSummary}
/>
</div>
)}
</div>
)}
</div>
@@ -295,7 +382,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>
);
@@ -305,10 +392,13 @@ function EmptyTimeline() {
interface RunTimelineProps {
runs: readonly SessionRunRecord[];
sessionId: string;
onJumpToMessage?: (messageId: string) => void;
onDiscard?: (sessionId: string, runId: string, files?: ProjectGitFileReference[]) => Promise<unknown>;
onOpenCommitComposer?: () => void;
}
export function RunTimeline({ runs, onJumpToMessage }: RunTimelineProps) {
export function RunTimeline({ runs, sessionId, onJumpToMessage, onDiscard, onOpenCommitComposer }: RunTimelineProps) {
const latestRunId = runs.length > 0 ? runs[0].id : undefined;
const [expandedRunId, setExpandedRunId] = useState<string | undefined>(latestRunId);
@@ -327,9 +417,12 @@ export function RunTimeline({ runs, onJumpToMessage }: RunTimelineProps) {
<RunCard
expanded={expandedRunId === run.id}
key={run.id}
onDiscard={onDiscard}
onJumpToMessage={onJumpToMessage}
onOpenCommitComposer={onOpenCommitComposer}
onToggle={() => setExpandedRunId(expandedRunId === run.id ? undefined : run.id)}
run={run}
sessionId={sessionId}
/>
))}
</div>
@@ -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>
);
}
+351 -170
View File
@@ -1,15 +1,17 @@
import { useState, type ReactNode } from 'react';
import { ChevronLeft, ChevronRight, Code, Cpu, FolderOpen, Palette, Plus, RefreshCw, Server, TriangleAlert, Workflow, Wrench } from 'lucide-react';
import { useEffect, useState, type ReactNode } from 'react';
import { ChevronLeft, ChevronRight, CircleCheck, Code, Cpu, FolderOpen, Palette, Plus, RefreshCw, 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';
import type { UpdateStatus, UpdateStatusState } from '@shared/contracts/ipc';
import {
normalizeLspProfileDefinition,
normalizeMcpServerDefinition,
@@ -26,9 +28,8 @@ interface SettingsPanelProps {
theme: AppearanceTheme;
toolingSettings: WorkspaceToolingSettings;
discoveredUserTooling: DiscoveredToolingState;
discoveredProjectTooling?: ProjectDiscoveredTooling;
selectedProjectName?: string;
isRefreshingCapabilities: boolean;
initialSection?: SettingsSection;
onRefreshCapabilities: () => void;
onClose: () => void;
onSavePattern: (pattern: PatternDefinition) => Promise<void>;
@@ -41,14 +42,19 @@ 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;
gitAutoRefreshEnabled: boolean;
onSetGitAutoRefreshEnabled: (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';
export type SettingsSection = 'appearance' | 'connection' | 'patterns' | 'mcp-servers' | 'lsp-profiles' | 'troubleshooting';
interface NavItem {
id: SettingsSection;
@@ -96,8 +102,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,9 +113,8 @@ export function SettingsPanel({
theme,
toolingSettings,
discoveredUserTooling,
discoveredProjectTooling,
selectedProjectName,
isRefreshingCapabilities,
initialSection,
onRefreshCapabilities,
onClose,
onSavePattern,
@@ -122,13 +127,18 @@ export function SettingsPanel({
onDeleteLspProfile,
onNewLspProfile,
onSetTheme,
notificationsEnabled,
onSetNotificationsEnabled,
minimizeToTray,
onSetMinimizeToTray,
gitAutoRefreshEnabled,
onSetGitAutoRefreshEnabled,
onOpenAppDataFolder,
onResetLocalWorkspace,
onRescanProjectConfigs,
onResolveUserDiscoveredTooling,
onResolveProjectDiscoveredTooling,
onGetQuota,
}: SettingsPanelProps) {
const [activeSection, setActiveSection] = useState<SettingsSection>('appearance');
const [activeSection, setActiveSection] = useState<SettingsSection>(initialSection ?? 'appearance');
const [editingPattern, setEditingPattern] = useState<PatternDefinition | null>(null);
const [editingMcpServer, setEditingMcpServer] = useState<McpServerDefinition | null>(null);
const [editingLspProfile, setEditingLspProfile] = useState<LspProfileDefinition | null>(null);
@@ -213,16 +223,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 +240,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 +248,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 +271,16 @@ 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}
gitAutoRefreshEnabled={gitAutoRefreshEnabled}
onSetGitAutoRefreshEnabled={onSetGitAutoRefreshEnabled}
/>
)}
{activeSection === 'connection' && (
<ConnectionSection
@@ -269,6 +288,7 @@ export function SettingsPanel({
isRefreshing={isRefreshingCapabilities}
modelCount={sidecarCapabilities?.models.length ?? 0}
onRefresh={onRefreshCapabilities}
onGetQuota={onGetQuota}
/>
)}
{activeSection === 'patterns' && (
@@ -287,12 +307,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 +340,27 @@ const themeOptions: { value: AppearanceTheme; label: string; description: string
function AppearanceSection({
theme,
onSetTheme,
notificationsEnabled,
onSetNotificationsEnabled,
minimizeToTray,
onSetMinimizeToTray,
gitAutoRefreshEnabled,
onSetGitAutoRefreshEnabled,
}: {
theme: AppearanceTheme;
onSetTheme: (theme: AppearanceTheme) => void;
}) {
notificationsEnabled: boolean;
onSetNotificationsEnabled: (enabled: boolean) => void;
minimizeToTray: boolean;
onSetMinimizeToTray: (enabled: boolean) => void;
gitAutoRefreshEnabled: boolean;
onSetGitAutoRefreshEnabled: (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 +370,104 @@ 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>
{/* Git */}
<div className="mt-8 mb-1">
<h3 className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">Git</h3>
<p className="mt-0.5 text-[12px] text-[var(--color-text-muted)]">
Control how Aryx monitors your repositories
</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={() => onSetGitAutoRefreshEnabled(!gitAutoRefreshEnabled)}
type="button"
>
<div>
<span className="text-[13px] font-medium text-[var(--color-text-primary)]">
Auto-refresh git status
</span>
<p className="text-[12px] text-[var(--color-text-muted)]">
Periodically poll repository status in the background and refresh on window focus
</p>
</div>
<ToggleSwitch enabled={gitAutoRefreshEnabled} />
</button>
</div>
);
}
@@ -377,25 +477,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 +527,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 +646,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 +657,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 +680,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 +710,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 +757,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 +801,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 +833,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"
>
@@ -787,6 +854,30 @@ function TroubleshootingSection({
}) {
const [isResetting, setIsResetting] = useState(false);
const [confirmingReset, setConfirmingReset] = useState(false);
const [updateStatus, setUpdateStatus] = useState<UpdateStatus>({ state: 'idle' });
const [isCheckingManually, setIsCheckingManually] = useState(false);
useEffect(() => {
const unsubscribe = window.aryxApi.onUpdateStatus((status) => {
setUpdateStatus(status);
if (status.state !== 'checking') setIsCheckingManually(false);
});
return unsubscribe;
}, []);
async function handleCheckForUpdates() {
setIsCheckingManually(true);
try {
const status = await window.aryxApi.checkForUpdates();
setUpdateStatus(status);
} finally {
setIsCheckingManually(false);
}
}
async function handleInstallUpdate() {
await window.aryxApi.installUpdate();
}
async function handleReset() {
setIsResetting(true);
@@ -798,64 +889,154 @@ function TroubleshootingSection({
}
}
const isChecking = isCheckingManually || updateStatus.state === 'checking';
function getUpdateLabel(): string {
switch (updateStatus.state) {
case 'checking':
return 'Checking for updates…';
case 'up-to-date':
return 'Up to date';
case 'available':
return `Update available: v${updateStatus.version ?? 'unknown'}`;
case 'downloading':
return `Downloading update${updateStatus.downloadProgress ? ` (${Math.round(updateStatus.downloadProgress.percent)}%)` : '…'}`;
case 'downloaded':
return `Update ready: v${updateStatus.version ?? 'unknown'}`;
case 'error':
return 'Update check failed';
default:
return 'Check for updates';
}
}
function getUpdateDescription(): string {
switch (updateStatus.state) {
case 'checking':
return 'Contacting the update server…';
case 'up-to-date':
return 'You are running the latest version of Aryx.';
case 'available':
case 'downloading':
return 'A new version is being downloaded and will be installed automatically.';
case 'downloaded':
return 'Restart Aryx to apply the update.';
case 'error':
return updateStatus.error ?? 'Could not reach the update server. Try again later.';
default:
return 'Manually check whether a newer version of Aryx is available.';
}
}
return (
<div>
<SectionHeader
description="Diagnose issues and manage local application data"
title="Troubleshooting"
/>
<div className="space-y-2">
<TroubleshootingAction
description="Reveal the folder where Aryx stores workspace data, scratchpad files, and configuration."
icon={<FolderOpen className="size-4" />}
label="Open App Data Folder"
onClick={onOpenAppDataFolder}
<div className="flex min-h-full flex-col">
<div className="flex-1">
<SectionHeader
description="Diagnose issues and manage local application data"
title="Troubleshooting"
/>
</div>
<div className="mt-8 rounded-xl border border-red-500/20 bg-red-500/5 p-5">
<div className="flex items-start gap-3">
<TriangleAlert className="mt-0.5 size-4 shrink-0 text-red-400" />
<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">
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.
</p>
{!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"
onClick={() => setConfirmingReset(true)}
type="button"
>
Reset workspace
</button>
) : (
<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"
disabled={isResetting}
onClick={() => void handleReset()}
type="button"
>
{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"
disabled={isResetting}
onClick={() => setConfirmingReset(false)}
type="button"
>
Cancel
</button>
<div className="space-y-2">
{/* Check for updates */}
{updateStatus.state === 'downloaded' ? (
<button
className="group flex w-full items-center gap-3 rounded-xl border border-[var(--color-status-success)]/20 bg-[var(--color-status-success)]/5 px-4 py-3 text-left transition-all duration-200 hover:border-[var(--color-status-success)]/40 hover:bg-[var(--color-status-success)]/10"
onClick={() => void handleInstallUpdate()}
type="button"
>
<span className="text-[var(--color-status-success)]">
<RefreshCw className="size-4" />
</span>
<div className="min-w-0 flex-1">
<span className="text-[13px] font-medium text-[var(--color-status-success)]">{getUpdateLabel()}</span>
<p className="mt-0.5 text-[12px] text-[var(--color-text-muted)]">{getUpdateDescription()}</p>
</div>
)}
<span className="rounded-lg bg-[var(--color-status-success)]/15 px-2.5 py-1 text-[11px] font-semibold text-[var(--color-status-success)]">
Restart
</span>
</button>
) : (
<button
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)] ${isChecking ? 'pointer-events-none opacity-70' : ''}`}
disabled={isChecking}
onClick={() => void handleCheckForUpdates()}
type="button"
>
<span className={`transition-all duration-200 ${updateStatus.state === 'up-to-date' ? 'text-[var(--color-status-success)]' : 'text-[var(--color-text-muted)] group-hover:text-[var(--color-text-secondary)]'}`}>
{updateStatus.state === 'up-to-date'
? <CircleCheck className="size-4" />
: <RefreshCw className={`size-4 ${isChecking ? 'animate-spin' : ''}`} />}
</span>
<div className="min-w-0 flex-1">
<span className={`text-[13px] font-medium ${updateStatus.state === 'error' ? 'text-[var(--color-status-error)]' : updateStatus.state === 'up-to-date' ? 'text-[var(--color-status-success)]' : 'text-[var(--color-text-primary)]'}`}>
{getUpdateLabel()}
</span>
<p className="mt-0.5 text-[12px] text-[var(--color-text-muted)]">{getUpdateDescription()}</p>
</div>
<ChevronRight className="size-4 text-[var(--color-text-muted)] transition-all duration-200 group-hover:text-[var(--color-text-muted)]" />
</button>
)}
<TroubleshootingAction
description="Reveal the folder where Aryx stores workspace data, scratchpad files, and configuration."
icon={<FolderOpen className="size-4" />}
label="Open App Data Folder"
onClick={onOpenAppDataFolder}
/>
</div>
<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-[var(--color-status-error)]" />
<div className="min-w-0 flex-1">
<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.
</p>
{!confirmingReset ? (
<button
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"
>
Reset workspace
</button>
) : (
<div className="mt-3 flex items-center gap-2">
<button
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"
>
{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-[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"
>
Cancel
</button>
</div>
)}
</div>
</div>
</div>
</div>
{/* Attribution footer */}
<div className="mt-12 flex items-center justify-center gap-1.5 pb-2 text-[11px] text-[var(--color-text-muted)]">
<span>Built with</span>
<svg aria-hidden="true" className="size-3 text-[var(--color-status-error)]" fill="currentColor" viewBox="0 0 24 24">
<path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" />
</svg>
<span>by Dávid Kaya</span>
</div>
</div>
);
}
@@ -873,16 +1054,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>
);
}
+192 -98
View File
@@ -1,5 +1,6 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import appIconUrl from '../../../assets/icons/icon.png';
import { isMac } from '@renderer/lib/platform';
import {
AlertTriangle,
Archive,
@@ -32,7 +33,9 @@ import { isScratchpadProject, type ProjectRecord, type ProjectGitContext } from
import { listPendingDiscoveredMcpServers } from '@shared/domain/discoveredTooling';
import type { SessionRecord } from '@shared/domain/session';
import { querySessions } from '@shared/domain/sessionLibrary';
import type { UpdateStatus } from '@shared/contracts/ipc';
import type { WorkspaceState } from '@shared/domain/workspace';
import { UpdateBanner } from '@renderer/components/ui';
interface SidebarProps {
workspace: WorkspaceState;
@@ -42,23 +45,27 @@ 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;
onSetSessionArchived: (sessionId: string, isArchived: boolean) => void;
onDeleteSession: (sessionId: string) => void;
onRefreshGitContext: (projectId: string) => void;
updateStatus?: UpdateStatus;
onViewUpdateDetails?: () => void;
onInstallUpdate?: () => void;
}
/* ── 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 +89,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>
);
@@ -115,10 +122,27 @@ function GitContextBadge({ git }: { git: ProjectGitContext }) {
if (git.ahead) parts.push(`${git.ahead}`);
if (git.behind) parts.push(`${git.behind}`);
const tooltipLines: string[] = [branchLabel];
if (git.changes) {
const breakdown: string[] = [];
if (git.changes.staged > 0) breakdown.push(`${git.changes.staged} staged`);
if (git.changes.unstaged > 0) breakdown.push(`${git.changes.unstaged} modified`);
if (git.changes.untracked > 0) breakdown.push(`${git.changes.untracked} untracked`);
if (git.changes.conflicted > 0) breakdown.push(`${git.changes.conflicted} conflicted`);
if (breakdown.length > 0) tooltipLines.push(breakdown.join(', '));
}
if (git.ahead || git.behind) {
const sync: string[] = [];
if (git.ahead) sync.push(`${git.ahead} ahead`);
if (git.behind) sync.push(`${git.behind} behind`);
tooltipLines.push(sync.join(', '));
}
if (git.upstream) tooltipLines.push(`${git.upstream}`);
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={tooltipLines.join('\n')}>
<GitBranch className="size-2.5 shrink-0" />
<span className="max-w-[80px] truncate">{branchLabel}</span>
<span className="max-w-[140px] truncate font-mono">{branchLabel}</span>
{git.isDirty && <Circle className="size-1.5 shrink-0 fill-amber-500 text-amber-500" />}
</span>
);
@@ -139,7 +163,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 +236,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 +248,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 +270,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 +280,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 +290,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 +347,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 +371,7 @@ function ProjectGroup({
onRenameSubmit,
onRenameCancel,
onRefreshGitContext,
onOpenProjectSettings,
onNewSession,
newSessionLabel,
}: {
@@ -341,6 +385,7 @@ function ProjectGroup({
onRenameSubmit: (sessionId: string, title: string) => void;
onRenameCancel: () => void;
onRefreshGitContext?: (projectId: string) => void;
onOpenProjectSettings?: (projectId: string) => void;
onNewSession?: () => void;
newSessionLabel?: string;
}){
@@ -373,62 +418,97 @@ 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 flex-col gap-0.5 rounded-lg px-2 py-2 text-left transition-all duration-150 hover:bg-[var(--color-surface-2)]/40"
onClick={() => setExpanded(!expanded)}
type="button"
title={`${project.name}\n${project.path}`}
>
{expanded ? (
<ChevronDown className="size-3 shrink-0 text-zinc-500" />
) : (
<ChevronRight className="size-3 shrink-0 text-zinc-500" />
)}
{isScratchpad ? (
<MessageSquare className="size-3.5 shrink-0 text-zinc-500 transition group-hover:text-indigo-400" />
) : (
<FolderOpen className="size-3.5 shrink-0 text-zinc-500 transition group-hover:text-indigo-400" />
)}
<span className="truncate">{project.name}</span>
{/* Row 1 — project identity + hover actions */}
<div className="flex w-full items-center gap-2 text-[13px] font-semibold text-[var(--color-text-secondary)] group-hover:text-[var(--color-text-primary)]">
{expanded ? (
<ChevronDown className="size-3 shrink-0 text-[var(--color-text-muted)]" />
) : (
<ChevronRight className="size-3 shrink-0 text-[var(--color-text-muted)]" />
)}
{isScratchpad ? (
<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-[var(--color-text-muted)] transition group-hover:text-[var(--color-accent)]" />
)}
<span className="min-w-0 flex-1 truncate">{project.name}</span>
{!isScratchpad && project.git && (
<GitContextBadge git={project.git} />
)}
{isScratchpad && (
<span className="shrink-0 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 className="ml-auto flex items-center gap-1.5">
{!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"
onClick={(e) => {
e.stopPropagation();
onRefreshGitContext(project.id);
}}
role="button"
title="Refresh git status"
>
<RefreshCw className="size-3" />
</span>
{!isScratchpad && (onOpenProjectSettings || onRefreshGitContext) && (
<div className="flex shrink-0 items-center gap-0.5">
{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>
)}
{onRefreshGitContext && (
<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();
onRefreshGitContext(project.id);
}}
role="button"
title="Refresh git status"
>
<RefreshCw className="size-3" />
</span>
)}
</div>
)}
{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" />
{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`}
>
{pendingDiscoveryCount} new
</span>
)}
<span className="rounded-full bg-zinc-800 px-1.5 py-0.5 text-[10px] font-medium text-zinc-500">
{visibleSessions.length}
</span>
</div>
{/* Row 2 — metadata strip: branch, status badges, session count */}
{!isScratchpad && (project.git || runningCount > 0 || pendingDiscoveryCount > 0 || visibleSessions.length > 0) && (
<div className="ml-[26px] flex items-center gap-2">
{project.git && <GitContextBadge git={project.git} />}
{runningCount > 0 && (
<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 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="ml-auto 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 +525,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 +534,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,12 +555,16 @@ export function Sidebar({
onProjectSelect,
onSessionSelect,
onOpenSettings,
onOpenProjectSettings,
onRenameSession,
onDuplicateSession,
onSetSessionPinned,
onSetSessionArchived,
onDeleteSession,
onRefreshGitContext,
updateStatus,
onViewUpdateDetails,
onInstallUpdate,
}: SidebarProps) {
const scratchpadProject = workspace.projects.find((project) => isScratchpadProject(project));
const userProjects = workspace.projects.filter((project) => !isScratchpadProject(project));
@@ -540,19 +624,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)] pb-3 pt-3 pr-4 ${isMac ? 'pl-20' : 'pl-4'}`}>
<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 +649,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 +677,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 +705,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 +728,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 +751,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 +762,7 @@ export function Sidebar({
onRenameSubmit={handleRenameSubmit}
onRenameCancel={() => setRenamingSessionId(undefined)}
onRefreshGitContext={onRefreshGitContext}
onOpenProjectSettings={onOpenProjectSettings}
renamingSessionId={renamingSessionId}
patterns={workspace.patterns}
project={project}
@@ -692,11 +777,20 @@ export function Sidebar({
)}
</div>
{/* Update notification banner */}
{updateStatus && onViewUpdateDetails && onInstallUpdate && (
<UpdateBanner
status={updateStatus}
onViewDetails={onViewUpdateDetails}
onInstallUpdate={onInstallUpdate}
/>
)}
{/* 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 +805,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 +842,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={() => {
+198
View File
@@ -0,0 +1,198 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { RotateCcw } 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 {
onRunningChange?: (running: boolean) => void;
}
export function TerminalPanel({
onRunningChange,
}: 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);
// Create or recover terminal on mount
useEffect(() => {
let disposed = false;
void api.describeTerminal().then((existing) => {
if (disposed) return;
if (existing) {
setSnapshot(existing);
setIsRunning(true);
onRunningChange?.(true);
} else {
void api.createTerminal().then((created) => {
if (disposed) return;
setSnapshot(created);
setIsRunning(true);
onRunningChange?.(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);
onRunningChange?.(false);
terminalRef.current?.write('\r\n\x1b[90m[Process exited]\x1b[0m\r\n');
});
return () => {
offData();
offExit();
};
}, [api]);
// ResizeObserver for container size changes (width or height from parent)
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]);
const handleRestart = useCallback(() => {
void api.restartTerminal().then((restarted) => {
setSnapshot(restarted);
setIsRunning(true);
onRunningChange?.(true);
terminalRef.current?.clear();
});
}, [api]);
return (
<div className="flex min-h-0 flex-1 flex-col">
{/* 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>
<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>
</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 };
+228 -38
View File
@@ -1,61 +1,251 @@
import { MessageSquare, Plus, Settings } from 'lucide-react';
import { CheckCircle2, Circle, Download, FolderPlus, MessageSquarePlus, Settings, Zap } from 'lucide-react';
import { motion } from 'motion/react';
import type { SidecarConnectionStatus } from '@shared/contracts/sidecar';
import { detectedPlatform } from '@renderer/lib/platform';
import { getInstallInfoForPlatform } from '@renderer/lib/cliInstallInstructions';
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>
);
}
function CliMissingCard({ onOpenSettings }: { onOpenSettings: () => void }) {
const info = getInstallInfoForPlatform(detectedPlatform);
const recommended = info.methods.find((m) => m.recommended) ?? info.methods[0];
return (
<button
type="button"
onClick={onOpenSettings}
className="group flex w-full cursor-pointer items-start gap-4 rounded-xl border border-[var(--color-border-glow)] bg-[var(--color-accent-muted)] px-5 py-4 text-left shadow-[0_0_24px_rgba(36,92,249,0.1)] backdrop-blur-sm transition-all duration-200 hover:shadow-[0_0_32px_rgba(36,92,249,0.15)]"
>
<div className="brand-gradient-bg flex size-9 shrink-0 items-center justify-center rounded-full">
<Download className="size-4 text-white" />
</div>
<div className="min-w-0 space-y-1.5">
<span className="block text-[13px] font-medium text-[var(--color-text-primary)]">
Install the Copilot CLI
</span>
<code className="block truncate rounded-md bg-[var(--color-surface-1)] px-2 py-1 font-mono text-[11px] text-[var(--color-text-secondary)]">
{recommended.command}
</code>
<span className="block text-[11px] text-[var(--color-text-muted)]">
View full instructions for {info.displayName}
</span>
</div>
</button>
);
}
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 */}
{connectionStatus === 'copilot-cli-missing' && (
<CliMissingCard onOpenSettings={onOpenSettings} />
)}
<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"
{!isConnected && connectionStatus !== 'copilot-cli-missing' && (
<ActionCard
icon={<Zap className="size-4 text-white" />}
title="Connect GitHub Copilot"
description="Check connection status and configure your CLI"
onClick={onOpenSettings}
highlight
/>
)}
<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,551 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import {
ArrowUpFromLine,
Check,
ChevronRight,
FileCode2,
FileMinus2,
FilePlus2,
GitBranch,
Loader2,
Sparkles,
X,
} from 'lucide-react';
import { getElectronApi } from '@renderer/lib/electronApi';
import type {
ProjectGitCommitMessageSuggestion,
ProjectGitConventionalCommitType,
ProjectGitDetails,
ProjectGitDiffPreview,
ProjectGitFileReference,
ProjectGitWorkingTreeFile,
} from '@shared/domain/project';
/* ── Helpers ───────────────────────────────────────────────── */
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) : '';
}
function fileIcon(file: ProjectGitWorkingTreeFile) {
if (file.stagedStatus === 'added' || file.unstagedStatus === 'untracked') {
return <FilePlus2 className="size-3 shrink-0 text-[var(--color-status-success)]" />;
}
if (file.stagedStatus === 'deleted' || file.unstagedStatus === 'deleted') {
return <FileMinus2 className="size-3 shrink-0 text-[var(--color-status-error)]" />;
}
return <FileCode2 className="size-3 shrink-0 text-[var(--color-accent-sky)]" />;
}
function statusLabel(file: ProjectGitWorkingTreeFile): string {
return file.stagedStatus ?? file.unstagedStatus ?? 'modified';
}
const CONVENTIONAL_TYPES: { value: ProjectGitConventionalCommitType; label: string }[] = [
{ value: 'feat', label: 'feat' },
{ value: 'fix', label: 'fix' },
{ value: 'refactor', label: 'refactor' },
{ value: 'docs', label: 'docs' },
{ value: 'test', label: 'test' },
{ value: 'chore', label: 'chore' },
];
/* ── 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>;
}
/* ── File row with staging checkbox ────────────────────────── */
function CommitFileRow({
file,
isStaged,
onToggle,
onPreview,
preview,
previewExpanded,
}: {
file: ProjectGitWorkingTreeFile;
isStaged: boolean;
onToggle: () => void;
onPreview: () => void;
preview?: ProjectGitDiffPreview;
previewExpanded: boolean;
}) {
const dir = fileDir(file.path);
const base = fileBaseName(file.path);
const hasPreview = !!preview?.diff || !!preview?.newFileContents;
return (
<div className="border-b border-[var(--color-border-subtle)] last:border-b-0">
<div className="flex items-center gap-1 px-2.5 py-[5px] text-[10px]">
{/* Staging checkbox */}
<button
className={`flex size-3.5 shrink-0 items-center justify-center rounded border transition-colors duration-100 ${
isStaged
? 'border-[var(--color-status-success)] bg-[var(--color-status-success)] text-white'
: 'border-[var(--color-border)] bg-transparent hover:border-[var(--color-text-muted)]'
}`}
onClick={onToggle}
type="button"
aria-label={`${isStaged ? 'Unstage' : 'Stage'} ${file.path}`}
aria-pressed={isStaged}
>
{isStaged && <Check className="size-2" />}
</button>
{/* File path + expand */}
<button
className="flex min-w-0 flex-1 items-center gap-1.5 text-left transition-colors duration-150 hover:text-[var(--color-text-primary)]"
onClick={onPreview}
type="button"
aria-expanded={previewExpanded}
>
{hasPreview || previewExpanded ? (
<ChevronRight
className={`size-2.5 shrink-0 text-[var(--color-text-muted)] transition-transform duration-150 ${previewExpanded ? 'rotate-90' : ''}`}
/>
) : (
<span className="w-2.5 shrink-0" />
)}
{fileIcon(file)}
<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>
<span className="shrink-0 rounded px-1 py-px text-[8px] font-semibold uppercase tracking-wider bg-[var(--color-surface-3)] text-[var(--color-text-muted)]">
{statusLabel(file)}
</span>
</button>
</div>
{/* Diff preview */}
{previewExpanded && preview && (
<div className="border-t border-[var(--color-border-subtle)]">
<pre className="max-h-52 overflow-auto bg-[var(--color-surface-0)] px-3 py-1.5 font-mono text-[10px] leading-relaxed">
{preview.diff
? preview.diff.split('\n').map((line, i) => <DiffLine key={i} line={line} />)
: preview.newFileContents
? preview.newFileContents.split('\n').map((line, i) => (
<div key={i} className="text-[var(--color-text-secondary)]">{line || '\u00A0'}</div>
))
: preview.isBinary
? <div className="text-[var(--color-text-muted)] italic">Binary file</div>
: <div className="text-[var(--color-text-muted)] italic">Loading</div>}
</pre>
</div>
)}
</div>
);
}
/* ── Main export ───────────────────────────────────────────── */
interface CommitComposerProps {
projectId: string;
sessionId: string;
runId?: string;
onClose: () => void;
}
export function CommitComposer({
projectId,
sessionId,
runId,
onClose,
}: CommitComposerProps) {
const api = getElectronApi();
const [details, setDetails] = useState<ProjectGitDetails>();
const [loading, setLoading] = useState(true);
const [commitMessage, setCommitMessage] = useState('');
const [commitType, setCommitType] = useState<ProjectGitConventionalCommitType>('feat');
const [stagedPaths, setStagedPaths] = useState<Set<string>>(new Set());
const [previews, setPreviews] = useState<Record<string, ProjectGitDiffPreview>>({});
const [expandedPath, setExpandedPath] = useState<string>();
const [committing, setCommitting] = useState(false);
const [pushAfterCommit, setPushAfterCommit] = useState(false);
const [commitError, setCommitError] = useState<string>();
const [commitSuccess, setCommitSuccess] = useState(false);
// Load git details on mount
useEffect(() => {
let cancelled = false;
async function load() {
setLoading(true);
try {
const result = await api.getProjectGitDetails({ projectId });
if (!cancelled) {
setDetails(result);
// Pre-stage files that are already in the index
if (result.workingTree) {
const preStaged = new Set<string>();
for (const file of result.workingTree.files) {
if (file.stagedStatus && file.stagedStatus !== 'unmerged') {
preStaged.add(file.path);
}
}
setStagedPaths(preStaged);
}
}
} finally {
if (!cancelled) setLoading(false);
}
}
void load();
return () => { cancelled = true; };
}, [api, projectId]);
// Load commit message suggestion
useEffect(() => {
let cancelled = false;
async function suggest() {
try {
const suggestion = await api.suggestProjectGitCommitMessage({
sessionId,
runId,
conventionalType: commitType,
});
if (!cancelled && suggestion) {
setCommitMessage(suggestion.message);
setCommitType(suggestion.type);
}
} catch {
// Suggestion is best-effort
}
}
if (!commitMessage) {
void suggest();
}
return () => { cancelled = true; };
}, [api, sessionId, runId]); // Deliberately omitting commitType/commitMessage to avoid re-triggering
const files = useMemo(
() => details?.workingTree?.files ?? [],
[details?.workingTree?.files],
);
const stagedFiles = useMemo(
() => files.filter((f) => stagedPaths.has(f.path)),
[files, stagedPaths],
);
const toggleStaged = useCallback((path: string) => {
setStagedPaths((prev) => {
const next = new Set(prev);
if (next.has(path)) {
next.delete(path);
} else {
next.add(path);
}
return next;
});
}, []);
const toggleAll = useCallback(() => {
if (stagedPaths.size === files.length) {
setStagedPaths(new Set());
} else {
setStagedPaths(new Set(files.map((f) => f.path)));
}
}, [files, stagedPaths.size]);
const handlePreview = useCallback(async (file: ProjectGitWorkingTreeFile) => {
if (expandedPath === file.path) {
setExpandedPath(undefined);
return;
}
setExpandedPath(file.path);
if (!previews[file.path]) {
try {
const preview = await api.getProjectGitFilePreview({
projectId,
file: { path: file.path, previousPath: file.previousPath },
});
if (preview) {
setPreviews((prev) => ({ ...prev, [file.path]: preview }));
}
} catch {
// Preview is best-effort
}
}
}, [api, expandedPath, previews, projectId]);
const handleSuggestMessage = useCallback(async () => {
try {
const suggestion = await api.suggestProjectGitCommitMessage({
sessionId,
runId,
conventionalType: commitType,
});
if (suggestion) {
setCommitMessage(suggestion.message);
setCommitType(suggestion.type);
}
} catch {
// Best-effort
}
}, [api, sessionId, runId, commitType]);
const handleCommit = useCallback(async () => {
if (!commitMessage.trim() || stagedFiles.length === 0) return;
setCommitting(true);
setCommitError(undefined);
try {
const filesToCommit: ProjectGitFileReference[] = stagedFiles.map((f) => ({
path: f.path,
previousPath: f.previousPath,
}));
await api.commitProjectGitChanges({
projectId,
message: commitMessage.trim(),
files: filesToCommit,
push: pushAfterCommit,
});
setCommitSuccess(true);
setTimeout(() => onClose(), 1200);
} catch (error) {
setCommitError(error instanceof Error ? error.message : String(error));
} finally {
setCommitting(false);
}
}, [api, commitMessage, onClose, projectId, pushAfterCommit, stagedFiles]);
// Keyboard: Escape to close
useEffect(() => {
const handleKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
e.preventDefault();
e.stopPropagation();
onClose();
}
};
window.addEventListener('keydown', handleKey, true);
return () => window.removeEventListener('keydown', handleKey, true);
}, [onClose]);
return (
<div
className="fixed inset-0 z-50 flex items-stretch justify-end"
role="dialog"
aria-modal="true"
aria-labelledby="commit-composer-title"
>
{/* Backdrop */}
<div
className="absolute inset-0 bg-black/40 backdrop-blur-[2px]"
onClick={onClose}
/>
{/* Panel */}
<div className="relative z-10 flex w-[420px] max-w-full flex-col border-l border-[var(--color-border)] bg-[var(--color-surface-1)] shadow-2xl">
{/* Header */}
<div className="flex items-center gap-2 border-b border-[var(--color-border-subtle)] px-4 py-3">
<GitBranch className="size-4 text-[var(--color-accent-sky)]" />
<h2 id="commit-composer-title" className="font-display text-sm font-semibold text-[var(--color-text-primary)]">
Commit Changes
</h2>
{details?.context.branch && (
<span className="font-mono text-[10px] text-[var(--color-text-muted)]">
on {details.context.branch}
</span>
)}
<div className="flex-1" />
<button
className="rounded-md p-1 text-[var(--color-text-muted)] transition-colors duration-100 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]"
onClick={onClose}
type="button"
aria-label="Close commit composer"
>
<X className="size-4" />
</button>
</div>
{/* Loading */}
{loading && (
<div className="flex flex-1 items-center justify-center">
<Loader2 className="size-5 animate-spin text-[var(--color-text-muted)]" aria-label="Loading git details" />
</div>
)}
{/* Success state */}
{commitSuccess && (
<div className="flex flex-1 flex-col items-center justify-center gap-3 px-6">
<div className="flex size-12 items-center justify-center rounded-full bg-[var(--color-status-success)]/10">
<Check className="size-6 text-[var(--color-status-success)]" />
</div>
<p className="text-sm font-medium text-[var(--color-status-success)]">
Changes committed{pushAfterCommit ? ' and pushed' : ''}
</p>
</div>
)}
{/* Content */}
{!loading && !commitSuccess && (
<>
{/* Commit message */}
<div className="border-b border-[var(--color-border-subtle)] px-4 py-3">
{/* Type selector */}
<div className="mb-2 flex items-center gap-1">
{CONVENTIONAL_TYPES.map((ct) => (
<button
key={ct.value}
className={`rounded-md px-2 py-0.5 text-[10px] font-medium transition-colors duration-100 ${
commitType === ct.value
? 'bg-[var(--color-accent)]/15 text-[var(--color-text-accent)]'
: 'text-[var(--color-text-muted)] hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]'
}`}
onClick={() => setCommitType(ct.value)}
type="button"
>
{ct.label}
</button>
))}
<div className="flex-1" />
<button
className="flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[9px] font-medium text-[var(--color-text-muted)] transition-colors duration-100 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-accent)]"
onClick={() => void handleSuggestMessage()}
type="button"
title="Suggest commit message"
>
<Sparkles className="size-3" />
Suggest
</button>
</div>
<textarea
className="w-full resize-none rounded-md border border-[var(--color-border)] bg-[var(--color-surface-0)] px-3 py-2 font-mono text-[11px] leading-relaxed text-[var(--color-text-primary)] placeholder:text-[var(--color-text-muted)] focus:border-[var(--color-accent)] focus:outline-none"
placeholder="Commit message…"
rows={3}
value={commitMessage}
onChange={(e) => setCommitMessage(e.target.value)}
/>
</div>
{/* File list */}
<div className="min-h-0 flex-1 overflow-y-auto">
{/* Select all header */}
<div className="flex items-center gap-2 border-b border-[var(--color-border-subtle)] px-2.5 py-1.5">
<button
className={`flex size-3.5 shrink-0 items-center justify-center rounded border transition-colors duration-100 ${
stagedPaths.size === files.length && files.length > 0
? 'border-[var(--color-status-success)] bg-[var(--color-status-success)] text-white'
: 'border-[var(--color-border)] bg-transparent hover:border-[var(--color-text-muted)]'
}`}
onClick={toggleAll}
type="button"
aria-label={stagedPaths.size === files.length ? 'Unstage all' : 'Stage all'}
>
{stagedPaths.size === files.length && files.length > 0 && <Check className="size-2" />}
</button>
<span className="text-[10px] font-medium text-[var(--color-text-muted)]">
{stagedPaths.size} of {files.length} staged
</span>
</div>
{files.length === 0 ? (
<p className="px-4 py-6 text-center text-[11px] text-[var(--color-text-muted)]">
Working tree is clean nothing to commit.
</p>
) : (
files.map((file) => (
<CommitFileRow
file={file}
isStaged={stagedPaths.has(file.path)}
key={file.path}
onPreview={() => void handlePreview(file)}
onToggle={() => toggleStaged(file.path)}
preview={previews[file.path]}
previewExpanded={expandedPath === file.path}
/>
))
)}
</div>
{/* Error */}
{commitError && (
<div className="border-t border-[var(--color-status-error)]/20 bg-[var(--color-status-error)]/5 px-4 py-2 text-[10px] text-[var(--color-status-error)]" role="alert">
{commitError}
</div>
)}
{/* Footer actions */}
<div className="flex items-center gap-2 border-t border-[var(--color-border-subtle)] px-4 py-3">
{/* Push toggle */}
<label className="flex cursor-pointer items-center gap-1.5 text-[10px] text-[var(--color-text-muted)]">
<input
type="checkbox"
checked={pushAfterCommit}
onChange={(e) => setPushAfterCommit(e.target.checked)}
className="accent-[var(--color-accent)]"
/>
Push after commit
</label>
<div className="flex-1" />
<button
className="rounded-md px-3 py-1.5 text-[11px] font-medium text-[var(--color-text-muted)] transition-colors duration-100 hover:bg-[var(--color-surface-3)]"
onClick={onClose}
type="button"
>
Cancel
</button>
<button
className="flex items-center gap-1.5 rounded-md bg-[var(--color-accent)] px-3 py-1.5 text-[11px] font-medium text-white transition-colors duration-150 hover:bg-[var(--color-accent-hover)] disabled:cursor-not-allowed disabled:opacity-50"
disabled={committing || !commitMessage.trim() || stagedFiles.length === 0}
onClick={() => void handleCommit()}
type="button"
>
{committing ? (
<Loader2 className="size-3 animate-spin" />
) : (
<ArrowUpFromLine className="size-3" />
)}
{committing ? 'Committing…' : pushAfterCommit ? 'Commit & Push' : 'Commit'}
</button>
</div>
</>
)}
</div>
</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>
);
}
+424 -87
View File
@@ -1,10 +1,11 @@
import { useState } from 'react';
import { ChevronDown, Sparkles } from 'lucide-react';
import { useCallback, useMemo, useState } from 'react';
import { ChevronDown, ChevronRight, GitBranch, 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,27 @@ 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 max-h-[28rem] w-64 overflow-y-auto rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] shadow-2xl">
{/* Header: enable / disable all */}
<div className="sticky top-0 z-10 border-b border-[var(--color-border)] bg-[var(--color-surface-1)]">
<div className="flex items-center justify-end px-3 py-1.5">
<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={() => {
const allEnabled = enabledCount === totalCount;
onToggle({
enabledMcpServerIds: allEnabled ? [] : mcpServers.map((s) => s.id),
enabledLspProfileIds: allEnabled ? [] : lspProfiles.map((p) => p.id),
});
}}
type="button"
>
{enabledCount === totalCount ? 'Disable all' : 'Enable all'}
</button>
</div>
</div>
<div className="py-1">
{workspaceMcpServers.length > 0 && (
<McpServerGroup
label="Workspace MCP"
@@ -276,7 +297,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) => (
@@ -295,6 +316,7 @@ export function InlineToolsPill({
))}
</div>
)}
</div>
</div>
)}
</div>
@@ -314,7 +336,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,35 +359,78 @@ 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);
function toggleTool(toolId: string) {
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, group: ApprovalToolGroup) {
const next = new Set(effectiveAutoApproved);
if (next.has(toolId)) {
// If the group has server-level approval, expand it to individual tools
// so the user can selectively disable one tool.
if (group.serverApprovalKey && next.has(group.serverApprovalKey)) {
next.delete(group.serverApprovalKey);
for (const tool of group.tools) {
if (tool.id !== toolId) {
next.add(tool.id);
}
}
} else if (next.has(toolId)) {
next.delete(toolId);
} else {
next.add(toolId);
@@ -373,79 +438,351 @@ 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);
}
function isToolEffectivelyApproved(toolId: string, group: ApprovalToolGroup): boolean {
if (effectiveAutoApproved.has(toolId)) return true;
if (group.serverApprovalKey && effectiveAutoApproved.has(group.serverApprovalKey)) return true;
return false;
}
const allApprovedGlobal = effectiveAutoApprovedCount === totalItemCount && totalItemCount > 0;
const approveAll = useCallback(() => {
const next = new Set<string>();
for (const group of groups) {
if (group.serverApprovalKey) {
next.add(group.serverApprovalKey);
}
for (const tool of group.tools) {
next.add(tool.id);
}
}
onUpdate({ autoApprovedToolNames: [...next] });
}, [groups, onUpdate]);
const unapproveAll = useCallback(() => {
onUpdate({ autoApprovedToolNames: [] });
}, [onUpdate]);
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>
<span className="ml-auto flex items-center gap-1">
{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>
)}
<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={allApprovedGlobal ? unapproveAll : approveAll}
type="button"
>
{allApprovedGlobal ? 'Unapprove all' : 'Approve all'}
</button>
</span>
</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={isToolEffectivelyApproved(tool.id, group)}
label={tool.label}
onToggle={() => toggleTool(tool.id, group)}
/>
</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-[14px] w-[24px] shrink-0 items-center rounded-full transition-all duration-200 ${
allApproved ? 'brand-gradient-bg shadow-[0_0_8px_rgba(36,92,249,0.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-[10px] rounded-full bg-white shadow-sm transition-transform ${
allApproved ? 'translate-x-[12px]' : '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>
);
}
/* ── InlineGitPill ─────────────────────────────────────────── */
export function InlineGitPill({
isDirty,
isOpen,
onToggle,
}: {
isDirty: 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)]'
}`}
onClick={onToggle}
type="button"
>
{isDirty && <span className="size-1.5 shrink-0 rounded-full bg-[var(--color-status-warning)]" />}
<GitBranch className="size-3" />
<span>Git</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>
);
}
@@ -8,7 +8,6 @@ import {
FileText,
Globe,
Server,
Terminal,
} from 'lucide-react';
import type { PermissionDetail } from '@shared/contracts/sidecar';
@@ -61,6 +60,37 @@ export function permissionDetailSummary(detail: PermissionDetail): string | unde
}
}
/* ── Display helpers ─────────────────────────────────────────── */
/** Recursively parse string values that contain JSON objects or arrays (display-time only). */
function deepParseJsonStrings(value: unknown): unknown {
if (typeof value === 'string') {
const trimmed = value.trim();
if (
(trimmed.startsWith('{') && trimmed.endsWith('}')) ||
(trimmed.startsWith('[') && trimmed.endsWith(']'))
) {
try {
return deepParseJsonStrings(JSON.parse(trimmed));
} catch {
return value;
}
}
return value;
}
if (Array.isArray(value)) {
return value.map(deepParseJsonStrings);
}
if (value !== null && typeof value === 'object') {
const result: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
result[k] = deepParseJsonStrings(v);
}
return result;
}
return value;
}
/* ── Kind-specific renderers ────────────────────────────────── */
function ShellDetail({ detail }: { detail: PermissionDetail }) {
@@ -68,7 +98,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 +119,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 +137,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,20 +151,20 @@ 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>
)}
</div>
{detail.args && Object.keys(detail.args).length > 0 && (
<CollapsibleCode label="Arguments" text={JSON.stringify(detail.args, null, 2)} />
<CollapsibleCode label="Arguments" text={JSON.stringify(deepParseJsonStrings(detail.args), null, 2)} />
)}
</div>
);
@@ -145,10 +175,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 +190,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,10 +212,10 @@ 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)} />
<CollapsibleCode label="Arguments" text={JSON.stringify(deepParseJsonStrings(detail.args), null, 2)} />
)}
</div>
);
@@ -195,27 +225,27 @@ 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>
)}
{detail.args && Object.keys(detail.args).length > 0 && (
<CollapsibleCode label="Arguments" text={JSON.stringify(detail.args, null, 2)} />
<CollapsibleCode label="Arguments" text={JSON.stringify(deepParseJsonStrings(detail.args), null, 2)} />
)}
</div>
);
}
/* ── Shared primitives ──────────────────────────────────────── */
/* ── 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 +255,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}
@@ -242,6 +272,47 @@ function DiffBlock({ text }: { text: string }) {
);
}
/* ── JSON syntax highlighting ───────────────────────────────── */
const jsonTokenPattern =
/("(?:[^"\\]|\\.)*")(\s*:)?|\b(true|false|null)\b|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|([{}\[\],])/g;
function JsonHighlighted({ json }: { json: string }) {
const elements: React.ReactNode[] = [];
let lastIndex = 0;
let key = 0;
for (const match of json.matchAll(jsonTokenPattern)) {
const idx = match.index ?? 0;
if (idx > lastIndex) elements.push(json.slice(lastIndex, idx));
if (match[1] && match[2]) {
// Object key + colon
elements.push(
<span key={key++} className="text-[var(--color-text-accent)]">{match[1]}</span>,
<span key={key++} className="text-[var(--color-text-muted)]">{match[2]}</span>,
);
} else if (match[1]) {
// String value
elements.push(<span key={key++} className="text-[var(--color-status-success)]">{match[1]}</span>);
} else if (match[3]) {
// true / false / null
elements.push(<span key={key++} className="text-[var(--color-accent-sky)]">{match[3]}</span>);
} else if (match[4]) {
// Number
elements.push(<span key={key++} className="text-[var(--color-accent-sky)]">{match[4]}</span>);
} else if (match[5]) {
// Structural punctuation
elements.push(<span key={key++} className="text-[var(--color-text-muted)]">{match[5]}</span>);
}
lastIndex = idx + match[0].length;
}
if (lastIndex < json.length) elements.push(json.slice(lastIndex));
return <>{elements}</>;
}
function CollapsibleCode({
label,
text,
@@ -254,12 +325,13 @@ function CollapsibleCode({
defaultExpanded?: boolean;
}) {
const [expanded, setExpanded] = useState(defaultExpanded);
const isJson = text.trimStart().startsWith('{') || text.trimStart().startsWith('[');
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,10 +341,10 @@ 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">
{text}
<pre className="max-h-48 overflow-auto font-mono text-[10px] leading-relaxed text-[var(--color-text-primary)]">
{isJson ? <JsonHighlighted json={text} /> : text}
</pre>
)}
</div>
@@ -283,9 +355,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,420 @@
import { useCallback, useMemo, useState } from 'react';
import {
AlertTriangle,
ArrowDownToLine,
Check,
ChevronRight,
FileCode2,
FileMinus2,
FilePlus2,
GitBranch,
Loader2,
RotateCcw,
Trash2,
} from 'lucide-react';
import type {
ProjectGitFileReference,
ProjectGitRunChangedFile,
ProjectGitRunChangeSummary,
} from '@shared/domain/project';
/* ── Helpers ───────────────────────────────────────────────── */
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) : '';
}
function kindLabel(kind: ProjectGitRunChangedFile['kind']): string {
switch (kind) {
case 'added': return 'added';
case 'modified': return 'modified';
case 'deleted': return 'deleted';
case 'renamed': return 'renamed';
case 'copied': return 'copied';
case 'type-changed': return 'type changed';
case 'unmerged': return 'conflict';
case 'untracked': return 'new';
case 'cleaned': return 'cleaned';
}
}
function kindIcon(kind: ProjectGitRunChangedFile['kind']) {
switch (kind) {
case 'added':
case 'untracked':
case 'copied':
return <FilePlus2 className="size-3 shrink-0 text-[var(--color-status-success)]" />;
case 'deleted':
case 'cleaned':
return <FileMinus2 className="size-3 shrink-0 text-[var(--color-status-error)]" />;
default:
return <FileCode2 className="size-3 shrink-0 text-[var(--color-accent-sky)]" />;
}
}
function originBadge(origin: ProjectGitRunChangedFile['origin']) {
if (origin === 'pre-existing') {
return (
<span className="rounded px-1 py-px text-[7px] font-semibold uppercase tracking-wider bg-[var(--color-status-warning)]/10 text-[var(--color-status-warning)]">
pre-existing
</span>
);
}
return null;
}
/* ── Mini diff-stats bar ───────────────────────────────────── */
function DiffStatsBar({ additions, deletions }: { additions: number; deletions: number }) {
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>;
}
/* ── Single file row ───────────────────────────────────────── */
function ChangedFileRow({
file,
isSelected,
onToggleSelect,
canSelect,
}: {
file: ProjectGitRunChangedFile;
isSelected: boolean;
onToggleSelect: () => void;
canSelect: boolean;
}) {
const [diffExpanded, setDiffExpanded] = useState(false);
const hasPreview = !!file.preview?.diff || !!file.preview?.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">
<div className="flex items-center gap-1 px-2 py-[5px] text-[10px]">
{/* Select checkbox */}
{canSelect && (
<button
className={`flex size-3.5 shrink-0 items-center justify-center rounded border transition-colors duration-100 ${
isSelected
? 'border-[var(--color-accent)] bg-[var(--color-accent)] text-white'
: 'border-[var(--color-border)] bg-transparent hover:border-[var(--color-text-muted)]'
}`}
onClick={onToggleSelect}
type="button"
aria-label={`${isSelected ? 'Deselect' : 'Select'} ${file.path}`}
aria-pressed={isSelected}
>
{isSelected && <Check className="size-2" />}
</button>
)}
{/* Expand diff button */}
<button
className="flex min-w-0 flex-1 items-center gap-1.5 text-left transition-colors duration-150 hover:bg-[var(--color-surface-3)]/40 disabled:cursor-default"
disabled={!hasPreview}
onClick={hasPreview ? () => setDiffExpanded(!diffExpanded) : undefined}
type="button"
aria-expanded={hasPreview ? diffExpanded : undefined}
>
{hasPreview ? (
<ChevronRight
className={`size-2.5 shrink-0 text-[var(--color-text-muted)] transition-transform duration-150 ${diffExpanded ? 'rotate-90' : ''}`}
/>
) : (
<span className="w-2.5 shrink-0" />
)}
{kindIcon(file.kind)}
<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>
<span className="shrink-0 rounded px-1 py-px text-[8px] font-semibold uppercase tracking-wider bg-[var(--color-surface-3)] text-[var(--color-text-muted)]">
{kindLabel(file.kind)}
</span>
{originBadge(file.origin)}
{(file.additions > 0 || file.deletions > 0) && (
<span className="flex items-center gap-1.5 shrink-0 font-mono">
{file.additions > 0 && <span className="text-[var(--color-status-success)]">+{file.additions}</span>}
{file.deletions > 0 && <span className="text-[var(--color-status-error)]">{file.deletions}</span>}
<DiffStatsBar additions={file.additions} deletions={file.deletions} />
</span>
)}
</button>
</div>
{/* Diff preview */}
{diffExpanded && file.preview && (
<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.preview.diff
? file.preview.diff.split('\n').map((line, i) => <DiffLine key={i} line={line} />)
: file.preview.newFileContents
? file.preview.newFileContents.split('\n').map((line, i) => (
<div key={i} className="text-[var(--color-text-secondary)]">{line || '\u00A0'}</div>
))
: file.preview.isBinary
? <div className="text-[var(--color-text-muted)] italic">Binary file</div>
: null}
</pre>
</div>
)}
</div>
);
}
/* ── Main export ───────────────────────────────────────────── */
interface RunChangeSummaryCardProps {
summary: ProjectGitRunChangeSummary;
sessionId: string;
runId: string;
onDiscard: (sessionId: string, runId: string, files?: ProjectGitFileReference[]) => Promise<unknown>;
onOpenCommitComposer?: () => void;
}
export function RunChangeSummaryCard({
summary,
sessionId,
runId,
onDiscard,
onOpenCommitComposer,
}: RunChangeSummaryCardProps) {
const [expanded, setExpanded] = useState(false);
const [selectedPaths, setSelectedPaths] = useState<Set<string>>(new Set());
const [discarding, setDiscarding] = useState(false);
const [confirmDiscard, setConfirmDiscard] = useState<'bulk' | 'selected' | undefined>();
const revertableFiles = useMemo(
() => summary.files.filter((file) => file.canRevert),
[summary.files],
);
const hasRevertable = revertableFiles.length > 0;
const toggleSelect = useCallback((path: string) => {
setSelectedPaths((prev) => {
const next = new Set(prev);
if (next.has(path)) {
next.delete(path);
} else {
next.add(path);
}
return next;
});
}, []);
const handleDiscard = useCallback(async (mode: 'bulk' | 'selected') => {
setDiscarding(true);
try {
if (mode === 'selected') {
const files: ProjectGitFileReference[] = summary.files
.filter((f) => selectedPaths.has(f.path))
.map((f) => ({ path: f.path, previousPath: f.previousPath }));
await onDiscard(sessionId, runId, files);
setSelectedPaths(new Set());
} else {
await onDiscard(sessionId, runId);
}
} finally {
setDiscarding(false);
setConfirmDiscard(undefined);
}
}, [onDiscard, sessionId, runId, selectedPaths, summary.files]);
const selectedRevertableCount = useMemo(
() => revertableFiles.filter((f) => selectedPaths.has(f.path)).length,
[revertableFiles, selectedPaths],
);
return (
<div className="overflow-hidden rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)]/80">
{/* Header */}
<button
className="flex w-full items-center gap-2 px-3 py-2 text-left transition-colors duration-150 hover:bg-[var(--color-surface-2)]/40"
onClick={() => setExpanded(!expanded)}
type="button"
aria-expanded={expanded}
aria-label={`${summary.fileCount} files changed by this run`}
>
<ChevronRight
className={`size-3 shrink-0 text-[var(--color-text-muted)] transition-transform duration-150 ${expanded ? 'rotate-90' : ''}`}
/>
<GitBranch className="size-3 shrink-0 text-[var(--color-accent-sky)]" />
<span className="text-[11px] font-medium text-[var(--color-text-secondary)]">
{summary.fileCount} {summary.fileCount === 1 ? 'file' : 'files'} changed
</span>
{(summary.additions > 0 || summary.deletions > 0) && (
<span className="flex items-center gap-1.5 font-mono text-[10px]">
{summary.additions > 0 && (
<span className="text-[var(--color-status-success)]">+{summary.additions}</span>
)}
{summary.deletions > 0 && (
<span className="text-[var(--color-status-error)]">{summary.deletions}</span>
)}
<DiffStatsBar additions={summary.additions} deletions={summary.deletions} />
</span>
)}
{summary.branchChanged && (
<span className="ml-auto flex items-center gap-1 text-[9px] text-[var(--color-status-warning)]">
<AlertTriangle className="size-2.5" />
branch changed
</span>
)}
</button>
{/* Expanded content */}
{expanded && (
<div className="border-t border-[var(--color-border-subtle)]">
{/* Branch info */}
{summary.branchChanged && summary.branchAtStart && summary.branchAtEnd && (
<div className="flex items-center gap-1.5 border-b border-[var(--color-border-subtle)] px-3 py-1.5 text-[9px] text-[var(--color-text-muted)]">
<GitBranch className="size-2.5" />
<span className="font-mono text-[var(--color-text-secondary)]">{summary.branchAtStart}</span>
<span></span>
<span className="font-mono text-[var(--color-text-secondary)]">{summary.branchAtEnd}</span>
</div>
)}
{/* File list */}
<div>
{summary.files.map((file) => (
<ChangedFileRow
canSelect={hasRevertable && file.canRevert}
file={file}
isSelected={selectedPaths.has(file.path)}
key={file.path}
onToggleSelect={() => toggleSelect(file.path)}
/>
))}
</div>
{/* Actions */}
{(hasRevertable || onOpenCommitComposer) && (
<div className="flex items-center gap-2 border-t border-[var(--color-border-subtle)] px-3 py-2">
{/* Commit button */}
{onOpenCommitComposer && (
<button
className="flex items-center gap-1.5 rounded-md bg-[var(--color-accent)] px-2.5 py-1 text-[10px] font-medium text-white transition-colors duration-150 hover:bg-[var(--color-accent-hover)]"
onClick={onOpenCommitComposer}
type="button"
>
<ArrowDownToLine className="size-3" />
Commit changes
</button>
)}
<div className="flex-1" />
{/* Discard actions */}
{hasRevertable && !confirmDiscard && (
<>
{selectedRevertableCount > 0 && (
<button
className="flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-medium text-[var(--color-status-error)] transition-colors duration-150 hover:bg-[var(--color-status-error)]/10"
disabled={discarding}
onClick={() => setConfirmDiscard('selected')}
type="button"
>
<Trash2 className="size-3" />
Discard {selectedRevertableCount} selected
</button>
)}
<button
className="flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-medium text-[var(--color-text-muted)] transition-colors duration-150 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-status-error)]"
disabled={discarding}
onClick={() => setConfirmDiscard('bulk')}
type="button"
>
<RotateCcw className="size-3" />
Discard all
</button>
</>
)}
{/* Confirmation */}
{confirmDiscard && (
<div className="flex items-center gap-1.5 rounded-md border border-[var(--color-status-error)]/30 bg-[var(--color-status-error)]/5 px-2.5 py-1" role="alert">
<AlertTriangle className="size-3 text-[var(--color-status-error)]" />
<span className="text-[10px] text-[var(--color-status-error)]">
{confirmDiscard === 'bulk'
? `Revert all ${revertableFiles.length} files to pre-run state?`
: `Revert ${selectedRevertableCount} selected files?`}
</span>
<button
className="flex items-center gap-1 rounded px-1.5 py-0.5 text-[9px] font-semibold text-[var(--color-status-error)] transition-colors duration-100 hover:bg-[var(--color-status-error)]/15"
disabled={discarding}
onClick={() => void handleDiscard(confirmDiscard)}
type="button"
>
{discarding ? <Loader2 className="size-2.5 animate-spin" /> : <Check className="size-2.5" />}
Yes
</button>
<button
className="rounded px-1.5 py-0.5 text-[9px] font-semibold text-[var(--color-text-muted)] transition-colors duration-100 hover:bg-[var(--color-surface-3)]"
onClick={() => setConfirmDiscard(undefined)}
type="button"
>
Cancel
</button>
</div>
)}
</div>
)}
</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>
);
}
@@ -0,0 +1,120 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Brain, ChevronDown, ChevronRight } from 'lucide-react';
import type { ChatMessageRecord } from '@shared/domain/session';
interface ThinkingProcessProps {
messages: ChatMessageRecord[];
isActive: boolean;
turnStartedAt?: string;
}
export function ThinkingProcess({ messages, isActive, turnStartedAt }: ThinkingProcessProps) {
const [expanded, setExpanded] = useState(false);
const wasActiveRef = useRef(isActive);
// Auto-expand when the turn is active and thinking messages appear.
// Auto-collapse once the turn finishes.
useEffect(() => {
if (isActive && messages.length > 0) {
setExpanded(true);
} else if (wasActiveRef.current && !isActive) {
setExpanded(false);
}
wasActiveRef.current = isActive;
}, [isActive, messages.length]);
const toggle = useCallback(() => setExpanded((prev) => !prev), []);
const elapsed = useMemo(() => {
if (!turnStartedAt || messages.length === 0) return undefined;
const start = new Date(turnStartedAt).getTime();
const lastMessage = messages[messages.length - 1];
const end = isActive ? Date.now() : new Date(lastMessage.createdAt).getTime();
const seconds = Math.max(0, Math.round((end - start) / 1000));
if (seconds < 2) return undefined;
return seconds >= 60 ? `${Math.floor(seconds / 60)}m ${seconds % 60}s` : `${seconds}s`;
}, [turnStartedAt, messages, isActive]);
if (messages.length === 0) {
return null;
}
const stepCount = messages.length;
const summaryParts: string[] = [];
if (elapsed) summaryParts.push(`${elapsed}`);
summaryParts.push(`${stepCount} ${stepCount === 1 ? 'step' : 'steps'}`);
return (
<div className="thinking-process-enter mb-2 overflow-hidden rounded-lg border border-[var(--color-border)]/50 bg-[var(--color-surface-1)]/60">
<button
type="button"
onClick={toggle}
onKeyDown={(e) => { if (e.key === ' ') { e.preventDefault(); toggle(); } }}
aria-expanded={expanded}
className="flex w-full items-center gap-2 px-3 py-2 text-left text-[12px] text-[var(--color-text-muted)] transition-colors hover:bg-[var(--color-surface-2)]/50"
>
<Brain className="size-3.5 shrink-0 text-[var(--color-accent-purple)]" />
{isActive ? (
<span className="flex items-center gap-1.5">
<span className="text-[var(--color-text-secondary)]">Thinking</span>
<ThinkingPulse />
</span>
) : (
<span className="text-[var(--color-text-secondary)]">
Thought for {summaryParts.join(' · ')}
</span>
)}
<span className="ml-auto shrink-0">
{expanded
? <ChevronDown className="size-3 text-[var(--color-text-muted)]" />
: <ChevronRight className="size-3 text-[var(--color-text-muted)]" />}
</span>
</button>
{expanded && (
<div className="border-t border-[var(--color-border)]/30 px-3 py-2">
<div className="space-y-1.5">
{messages.map((message) => (
<ThinkingStep key={message.id} message={message} />
))}
</div>
</div>
)}
</div>
);
}
function ThinkingStep({ message }: { message: ChatMessageRecord }) {
const preview = useMemo(() => truncatePreview(message.content, 180), [message.content]);
return (
<div className="flex gap-2 text-[12px] leading-relaxed">
<span className="mt-0.5 shrink-0 text-[var(--color-text-muted)]"></span>
<div className="min-w-0">
{message.authorName && (
<span className="mr-1.5 font-medium text-[var(--color-text-secondary)]">
{message.authorName}
</span>
)}
<span className="text-[var(--color-text-muted)]">{preview}</span>
</div>
</div>
);
}
function ThinkingPulse() {
return (
<span className="inline-flex items-center gap-0.5">
<span className="thinking-dot size-1 rounded-full bg-[var(--color-accent-purple)]" />
<span className="thinking-dot size-1 rounded-full bg-[var(--color-accent-purple)]" />
<span className="thinking-dot size-1 rounded-full bg-[var(--color-accent-purple)]" />
</span>
);
}
function truncatePreview(text: string, maxLength: number): string {
const firstLine = text.split('\n')[0] ?? '';
const cleaned = firstLine.trim();
if (cleaned.length <= maxLength) return cleaned;
return `${cleaned.slice(0, maxLength)}`;
}

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