mirror of
https://github.com/davidkaya/aryx.git
synced 2026-07-23 21:18:40 +02:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a1932788ae | ||
|
|
c3e611dc74 | ||
|
|
dcabc65dbf | ||
|
|
1068ed39e4 | ||
|
|
e956f8ea6c | ||
|
|
af69d494a5 | ||
|
|
e72bb7c7ca | ||
|
|
5f4318e761 | ||
|
|
d88ce0f00c | ||
|
|
15071fdc47 | ||
|
|
66b2a94977 | ||
|
|
4726e2acea | ||
|
|
c0a37b0cd4 | ||
|
|
7aae1b2cd5 | ||
|
|
a670817870 | ||
|
|
8813f9e90a | ||
|
|
20b400be56 | ||
|
|
05dded9b37 | ||
|
|
ea58f7d66a | ||
|
|
bb713f61be | ||
|
|
395965c639 | ||
|
|
be3f8d4cb3 | ||
|
|
f8b4c3cf4f | ||
|
|
2f1c5bc6d7 | ||
|
|
898e27e64d | ||
|
|
92832c6116 | ||
|
|
48efbf36f9 | ||
|
|
21f0ccb184 | ||
|
|
7921b6648f | ||
|
|
6d12cce836 | ||
|
|
e4142a6def | ||
|
|
edd4c7381a | ||
|
|
251316596c | ||
|
|
651a7d27fc | ||
|
|
cc13ed29f5 | ||
|
|
9ddd831b34 | ||
|
|
08876f694d | ||
|
|
216b17b2ac | ||
|
|
b985a06df3 | ||
|
|
169a9617c8 | ||
|
|
e38a663834 | ||
|
|
f0114058ba | ||
|
|
6505493735 | ||
|
|
b4b0bf54d2 | ||
|
|
8312a47bf1 | ||
|
|
3937904548 | ||
|
|
53a08e0ed4 | ||
|
|
5ad85db0f5 | ||
|
|
dd203ddde5 | ||
|
|
75b9ff667a | ||
|
|
f53907755a | ||
|
|
3c57cb6ded | ||
|
|
b946359c69 | ||
|
|
e4eb221308 | ||
|
|
036fb4d4fa | ||
|
|
6321f9192d | ||
|
|
147b437e36 | ||
|
|
fa5774cbc0 | ||
|
|
ae56d55c85 | ||
|
|
1fbfdbbac4 | ||
|
|
db9ffe8399 | ||
|
|
dff97efd58 | ||
|
|
f459cc7291 | ||
|
|
e13e3b818a | ||
|
|
f1fa52f9c3 | ||
|
|
0c2973c599 | ||
|
|
c1dab96bfd | ||
|
|
bb7e5d4108 | ||
|
|
b5ab92e444 | ||
|
|
689b335220 | ||
|
|
f04e3b9dcc | ||
|
|
3ec69d990b | ||
|
|
154787c336 | ||
|
|
9d65e3d209 | ||
|
|
7247a68f24 | ||
|
|
85a9327f65 | ||
|
|
2a952dfebe | ||
|
|
cf41279ff5 | ||
|
|
c02589f4c0 | ||
|
|
73595039fc | ||
|
|
81bddcbd63 | ||
|
|
53f1167681 | ||
|
|
4f7b479996 | ||
|
|
0fd7a04a51 | ||
|
|
6c6b49fde4 | ||
|
|
d73eaae30b | ||
|
|
1868a79d9a | ||
|
|
4f1ae86021 | ||
|
|
f0c2b4982b | ||
|
|
ac48aa58e0 | ||
|
|
f9757d5ce2 | ||
|
|
192c28f721 | ||
|
|
b670680a7d | ||
|
|
231be36e6c | ||
|
|
380e402512 | ||
|
|
c069b86add | ||
|
|
912677fba0 | ||
|
|
a1a044e7ca | ||
|
|
f15b1aedb1 | ||
|
|
2ae4bd01b4 | ||
|
|
4c01d8b1a7 | ||
|
|
13c543e2fd | ||
|
|
69562c19f3 | ||
|
|
7c1852f79f | ||
|
|
d7d1b33a53 |
+135
-21
@@ -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
|
||||
@@ -134,20 +126,142 @@ jobs:
|
||||
- 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
|
||||
|
||||
@@ -9,3 +9,4 @@ sidecar/**/obj/
|
||||
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
plan/
|
||||
@@ -42,6 +42,7 @@ These instructions apply to any automated or semi-automated agent working in thi
|
||||
- Treat tests as part of the implementation, not as follow-up work. Every fix, behavior change, and new feature must be covered by tests, and the relevant test suite must pass before the work is considered complete.
|
||||
- Always check whether `README.md` needs an update before handing work off. If the change affects user-facing behavior, workflows, prerequisites, installation, packaging, or product positioning, update the README in the same change.
|
||||
- Always check whether `ARCHITECTURE.md` needs an update before handing work off. If the change affects runtime boundaries, data flow, persistence, IPC, orchestration, tooling integration, packaging, or other material technical design, update `ARCHITECTURE.md` in the same change.
|
||||
- Always check whether the product website (`website/`) needs an update before handing work off. If the change introduces a major new feature, or a minor feature that is particularly interesting or noteworthy to end users, update the relevant website content in the same change. The website is a standalone Astro app under `website/` and validates with `bun run build` from that directory.
|
||||
- Do not ship quick fixes, hacks, or "temporary" patches as final solutions. Take the time to understand the problem, plan the change, and implement a maintainable solution that fits the codebase cleanly.
|
||||
- Remove code that is no longer necessary before handing work off. If an experiment, workaround, hotfix, helper, or test path does not end up being part of the final correct solution, delete it rather than leaving dead or misleading code behind.
|
||||
- Apply the same quality bar to feature work. Think through scope, edge cases, integration points, and long-term maintainability before implementing.
|
||||
@@ -153,13 +154,17 @@ Every interactive component must include basic accessibility:
|
||||
- Keep changes focused and reviewable. Avoid mixing unrelated concerns into a single change.
|
||||
- Always commit completed repository changes before handing work off. If unrelated pre-existing changes are present in the worktree, stop and ask the user how to proceed before creating the commit.
|
||||
- Do not mark work as done until both the implementation and its verification are complete.
|
||||
- **Never use unscoped glob patterns** (e.g. `**/*`) at or near the repository root. The repository contains large `node_modules/` directories that will cause glob operations to hang or exhaust resources. Always scope globs to a specific subdirectory (e.g. `src/**/*.ts`, `sidecar/src/**/*.cs`) or use `view` on known directories instead.
|
||||
|
||||
## 8. Planning requirements
|
||||
|
||||
- If a task spans both backend and frontend work, the implementation plan must be split into **Part 1 — Backend** and **Part 2 — Frontend**. The Frontend part will be launched manually by the user.
|
||||
- Backend work must be planned and executed first.
|
||||
- Before frontend work begins, backend work must produce a handover artifact in the session workspace `files\` directory. Do not put this handover document in the repository.
|
||||
> **Hard rule — no exceptions.** Every task that touches both backend (C# / sidecar) and frontend (TypeScript / renderer) code **must** produce a plan with exactly two phases: **Part 1 — Backend** and **Part 2 — Frontend**. A single combined plan that mixes backend and frontend work is never acceptable, even if the changes seem small or tightly coupled. When in doubt about whether a task spans both surfaces, treat it as spanning both and split the plan.
|
||||
|
||||
- **Part 1 — Backend** is always planned, implemented, tested, and committed first. No frontend work may begin until Part 1 is complete.
|
||||
- **Part 2 — Frontend** is launched manually by the user in a separate session. Do not start frontend implementation in the same session as backend work.
|
||||
- Before frontend work begins, backend work must produce a handover artifact in the session workspace `files\` directory. Do not put this handover document in the repository. The handover must describe every new or changed contract (DTOs, IPC messages, events, API shapes) that the frontend needs to consume.
|
||||
- The frontend phase must consume that backend handover artifact and build on it rather than rediscovering backend contracts from scratch.
|
||||
- If a task is frontend-only or backend-only, a two-part split is not required — but you must still confirm the scope before planning.
|
||||
|
||||
## 9. Validation checklist
|
||||
|
||||
|
||||
+47
-6
@@ -33,7 +33,7 @@ flowchart LR
|
||||
Renderer[Renderer UI<br/>React + Tailwind]
|
||||
Preload[Preload bridge]
|
||||
Main[Electron main process]
|
||||
Workspace[Workspace storage<br/>JSON + scratchpad files]
|
||||
Workspace[Workspace storage<br/>workspace.json + per-session scratchpad directories]
|
||||
Git[Local git repositories]
|
||||
Sidecar[.NET sidecar]
|
||||
Copilot[GitHub Copilot CLI<br/>+ agent runtime]
|
||||
@@ -55,7 +55,7 @@ flowchart LR
|
||||
| --- | --- | --- | --- |
|
||||
| Renderer | Screens, interaction, local view composition, theme application | Filesystem, process spawning, raw Electron access, Copilot runtime | Typed preload API and pushed events |
|
||||
| Preload | Narrow bridge between browser context and Electron IPC | Business logic, persistence, orchestration | `ipcRenderer` / `ipcMain` |
|
||||
| Main process | Workspace mutation, persistence, git inspection, session lifecycle, native window state, sidecar lifecycle | UI rendering, LLM orchestration internals | IPC, filesystem, git CLI, stdio with sidecar |
|
||||
| Main process | Workspace mutation, persistence, git inspection, session lifecycle, native window state, sidecar lifecycle, PTY-backed terminal lifecycle | UI rendering, LLM orchestration internals | IPC, filesystem, git CLI, stdio with sidecar, native child processes |
|
||||
| Sidecar | Capability discovery, pattern validation, run execution, streaming deltas and activity | UI, workspace persistence, Electron APIs | Line-delimited JSON over stdio |
|
||||
| External systems | Git data, Copilot account/model access, OS window chrome | Application state and UI behavior | Controlled adapters owned by main or sidecar |
|
||||
|
||||
@@ -122,7 +122,9 @@ Projects are the container for context. There are two kinds:
|
||||
- a special **scratchpad** project for lightweight work
|
||||
- normal **project-backed** entries pointing at local folders
|
||||
|
||||
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.
|
||||
The scratchpad is modeled inside the same workspace system instead of as a separate subsystem. That keeps the UI and session model consistent while still allowing special rules for scratchpad behavior. Each scratchpad session receives its own working directory under the shared scratchpad root, so session-created files stay isolated from other scratchpad conversations.
|
||||
|
||||
Project-backed entries also persist scanned Copilot customization metadata discovered from repository files such as `.github/copilot-instructions.md`, `AGENTS.md`, `.github/agents/*.agent.md`, and `.github/prompts/*.prompt.md`. The main process owns that scan step and stores the normalized results on the project record so repo instructions and enabled custom agent profiles can participate in later run execution without turning the renderer into a filesystem crawler.
|
||||
|
||||
### Patterns
|
||||
|
||||
@@ -136,6 +138,8 @@ Patterns describe how agents collaborate. The architecture supports:
|
||||
|
||||
Their runtime semantics follow the Agent Framework orchestration model: sequential and group chat preserve a visible shared conversation, concurrent aggregates multiple independent responses into one turn, and handoff turns can end once the active agent has responded and is waiting for the next user input.
|
||||
|
||||
For Copilot-backed agents, Aryx uses a repo-local adapter around the Copilot SDK session layer so handoff routes still behave like Agent Framework handoffs. This is necessary because the upstream `GitHubCopilotAgent` does not currently project run-time handoff tool declarations into Copilot sessions or surface Copilot tool requests back as `FunctionCallContent` for the workflow runtime.
|
||||
|
||||
Patterns are shared application data, not renderer-only configuration. That means the same pattern definition can drive validation, persistence, UI rendering, and sidecar execution.
|
||||
|
||||
Patterns now persist an explicit graph-backed topology alongside the flat agent list. Agent nodes carry stable agent ids, ordering, and layout metadata, while system nodes such as user input/output, distributor, collector, and orchestrator make mode-specific flow visible in the saved contract.
|
||||
@@ -183,16 +187,20 @@ Typical examples:
|
||||
- create session
|
||||
- send message
|
||||
- update theme
|
||||
- create or restart the integrated terminal
|
||||
- toggle session tooling
|
||||
- update session approval overrides
|
||||
|
||||
The renderer does not reach into Electron or the filesystem directly. It talks through a constrained API surface.
|
||||
|
||||
The integrated terminal uses the same boundary. The renderer never opens a shell directly; it asks the main process to create or restart a PTY, sends fire-and-forget input and resize messages over IPC, and listens for streamed terminal data and exit events pushed back through preload. The `TerminalPanel` component manages an xterm.js terminal instance with a FitAddon, a drag-to-resize handle, and a header bar showing shell status.
|
||||
|
||||
### 2. Main process <-> sidecar
|
||||
|
||||
This is a structured stdio protocol used for:
|
||||
|
||||
- capability discovery
|
||||
- on-demand account quota lookup
|
||||
- pattern validation
|
||||
- run execution
|
||||
- streaming partial output
|
||||
@@ -200,6 +208,26 @@ This is a structured stdio protocol used for:
|
||||
|
||||
This protocol boundary keeps the AI execution runtime replaceable and prevents the Electron main process from becoming overloaded with workflow-specific behavior.
|
||||
|
||||
The protocol also carries **turn-scoped lifecycle events** alongside output deltas. These events let the UI visualize execution internals without the main process having to interpret AI workflow semantics:
|
||||
|
||||
- **Sub-agent events**: started, completed, failed, selected, deselected — surfaced when custom agents are defined
|
||||
- **Skill invocation events**: emitted when an agent-side skill is triggered
|
||||
- **Hook lifecycle events**: start and end of configured project hook commands discovered from `.github/hooks/*.json`; Aryx suppresses the SDK's built-in no-op hook chatter so the UI only sees meaningful hook activity
|
||||
- **Assistant usage events**: per-LLM-call tokens, cost, AIU, and quota snapshots from the Copilot SDK's `assistant.usage` stream
|
||||
- **Session compaction events**: start and complete, with token-reduction metrics when infinite sessions trigger context trimming
|
||||
- **Session usage events**: current token count and context-window limit 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**.
|
||||
@@ -256,6 +284,8 @@ Tooling is deliberately split into two levels:
|
||||
|
||||
- **dynamic runtime tools** reported by the Copilot CLI, with a fallback catalog for startup/offline cases
|
||||
- **global definitions** for MCP servers and LSP profiles
|
||||
- **MCP tool discovery** — when MCP server configs declare wildcard tools (empty `tools` array), the main process probes each server directly via the MCP protocol `tools/list` method to discover available tools, using the same auth credentials Aryx manages for OAuth-protected servers
|
||||
- **incremental probe progress** — MCP probing runs concurrently and publishes per-server progress through the pushed workspace snapshot, using the runtime-only `mcpProbingServerIds` field so the renderer can reflect in-flight discovery without persisting transient UI state
|
||||
- **pattern defaults** where tool-call approval is enabled by default, plus which known runtime tools can bypass manual approval
|
||||
- **per-session overrides** for both tool enablement and tool auto-approval
|
||||
|
||||
@@ -263,7 +293,7 @@ This lets the application treat tooling as reusable workspace capability while s
|
||||
|
||||
### Project awareness
|
||||
|
||||
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. 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.
|
||||
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.
|
||||
|
||||
### Execution observability
|
||||
|
||||
@@ -271,11 +301,20 @@ The architecture treats execution as observable by design:
|
||||
|
||||
- partial output is streamed
|
||||
- agent activity is surfaced
|
||||
- turn-scoped lifecycle events (sub-agent, hook, skill, compaction, usage) are streamed
|
||||
- runs are persisted as timeline history
|
||||
- failures are represented explicitly
|
||||
|
||||
This improves trust and debuggability, especially for multi-agent workflows.
|
||||
|
||||
### Mid-turn steering
|
||||
|
||||
Aryx supports sending user messages while a turn is actively running. These messages are delivered with a `messageMode` flag (`immediate` or `enqueue`) that tells the sidecar to inject the content into the current Copilot session rather than starting a new turn. This enables real-time steering without waiting for turn completion. The main process allows the IPC call even when the session is in `running` status, and the renderer keeps the composer enabled throughout.
|
||||
|
||||
### Image attachments
|
||||
|
||||
User messages can carry image attachments as base64-encoded blobs. These flow from the renderer through IPC, the main process, and the sidecar protocol as `ChatMessageAttachmentDto` objects alongside the text content. The sidecar maps them into the Copilot SDK's `DataPart` model. Attachment metadata is persisted on the `ChatMessageRecord` so thumbnail previews render correctly when revisiting a session.
|
||||
|
||||
## Persistence and repair
|
||||
|
||||
Workspace persistence is intentionally simple: the app stores a durable workspace document and repairs or normalizes it when loading.
|
||||
@@ -307,9 +346,11 @@ The build pipeline is organized around three layers:
|
||||
|
||||
- building the Electron renderer and main process assets
|
||||
- publishing the sidecar for the target runtime
|
||||
- assembling a platform-specific release bundle
|
||||
- packaging platform artifacts with electron-builder
|
||||
|
||||
Release automation validates the app across Windows, macOS, and Linux, and tag-based releases publish platform bundles directly to GitHub Releases, including both macOS x64 and arm64 artifacts.
|
||||
electron-builder bundles the packaged Electron app, copies the published sidecar into `resources/sidecar`, produces Windows NSIS installers, macOS DMG + ZIP artifacts, and Linux AppImages, and uploads the release assets plus update metadata to GitHub Releases. Tagged macOS release jobs now materialize the certificate and App Store Connect key from repository secrets into temporary files on the runner, normalize the decoded PKCS#12 into a `security import`-compatible container, preflight that normalized certificate against a temporary keychain, export the standard `electron-builder` signing and notarization environment variables from those files, and package with checked-in hardened-runtime entitlements so native modules still run correctly under code signing. The main process consumes the published metadata through `electron-updater`, which checks GitHub Releases for packaged builds and can stage a restart-based update install.
|
||||
|
||||
Current Windows builds are unsigned, so the packaging config disables executable resource editing/signing and skips Windows update signature verification until a code-signing certificate is available. The packaging scripts also clear `release/` before each build so local packaging runs cannot accidentally mix stale artifacts with current ones.
|
||||
|
||||
This packaging model matches the runtime architecture: one desktop shell plus one dedicated AI execution process.
|
||||
|
||||
|
||||
@@ -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>.
|
||||
@@ -17,8 +17,10 @@ It works especially well when you want AI help that stays grounded in an actual
|
||||
- **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.
|
||||
- **Stay organized** with persistent sessions you can rename, pin, archive, and return to later.
|
||||
- **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.
|
||||
|
||||
## What you can do in the app
|
||||
@@ -26,6 +28,7 @@ It works especially well when you want AI help that stays grounded in an actual
|
||||
### Ask quick questions in a scratchpad
|
||||
|
||||
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.
|
||||
|
||||
### Connect a real project
|
||||
|
||||
@@ -49,13 +52,23 @@ This keeps machine-wide tooling reusable while still letting each session decide
|
||||
|
||||
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.
|
||||
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, and duplicate sessions as your workspace grows.
|
||||
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
|
||||
|
||||
@@ -111,7 +124,19 @@ To package the current platform into `release/`, run:
|
||||
|
||||
- `bun run package`
|
||||
|
||||
GitHub Actions now runs validation on pushes and pull requests, and pushing a git tag creates a GitHub release with Windows, macOS (x64 and arm64), and Linux assets uploaded directly to the release.
|
||||
To create the installable artifacts for the current platform, run:
|
||||
|
||||
- `bun run installer`
|
||||
|
||||
To publish packaged artifacts and update metadata to GitHub Releases, run:
|
||||
|
||||
- `bun run publish-release`
|
||||
|
||||
GitHub Actions runs validation on pushes and pull requests, and tagged releases now use `electron-builder` to publish Windows (NSIS), macOS (DMG + ZIP for updater metadata), and Linux (AppImage) artifacts directly to GitHub Releases. Packaged builds use `electron-updater` against those releases for in-app updates.
|
||||
|
||||
Tagged macOS release jobs now prepare signing assets from the GitHub secrets `APPLE_CERT_P12_BASE64`, `APPLE_CERT_PASSWORD`, `APPLE_API_KEY_P8`, `APPLE_API_KEY_ID`, `APPLE_API_ISSUER`, and `APPLE_TEAM_ID`, normalize the decoded PKCS#12 into a macOS-compatible container, preflight `security import` against a temporary keychain, and then export the standard `electron-builder` environment variables (`CSC_LINK`, `CSC_KEY_PASSWORD`, `APPLE_API_KEY`, `APPLE_API_KEY_ID`, `APPLE_API_ISSUER`, `APPLE_TEAM_ID`) before packaging. That same release path signs and notarizes the macOS artifacts as part of publication.
|
||||
|
||||
Windows builds are currently packaged without Authenticode signing, so Aryx disables `electron-updater`'s Windows signature verification until a signing certificate is configured. macOS auto-update metadata still requires a ZIP artifact alongside the DMG build.
|
||||
|
||||
## Current focus
|
||||
|
||||
|
||||
@@ -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>
|
||||
@@ -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,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
|
||||
@@ -1,112 +0,0 @@
|
||||
!include "MUI2.nsh"
|
||||
|
||||
;--- Product metadata (passed via /D defines from the build script) ---
|
||||
!ifndef PRODUCT_NAME
|
||||
!define PRODUCT_NAME "Aryx"
|
||||
!endif
|
||||
!ifndef PRODUCT_VERSION
|
||||
!define PRODUCT_VERSION "0.0.0"
|
||||
!endif
|
||||
!ifndef PRODUCT_PUBLISHER
|
||||
!define PRODUCT_PUBLISHER "David Kaya"
|
||||
!endif
|
||||
!ifndef SOURCE_DIR
|
||||
!error "SOURCE_DIR must be defined (path to the packaged app directory)."
|
||||
!endif
|
||||
!ifndef OUTPUT_PATH
|
||||
!error "OUTPUT_PATH must be defined (path to the output installer .exe)."
|
||||
!endif
|
||||
|
||||
;--- Installer attributes ---
|
||||
Name "${PRODUCT_NAME}"
|
||||
OutFile "${OUTPUT_PATH}"
|
||||
InstallDir "$LOCALAPPDATA\Programs\${PRODUCT_NAME}"
|
||||
InstallDirRegKey HKCU "Software\${PRODUCT_NAME}" "InstallDir"
|
||||
RequestExecutionLevel user
|
||||
SetCompressor /SOLID lzma
|
||||
|
||||
;--- Version info embedded in the installer EXE ---
|
||||
VIProductVersion "${PRODUCT_VERSION}.0"
|
||||
VIAddVersionKey "ProductName" "${PRODUCT_NAME}"
|
||||
VIAddVersionKey "ProductVersion" "${PRODUCT_VERSION}"
|
||||
VIAddVersionKey "FileDescription" "${PRODUCT_NAME} Setup"
|
||||
VIAddVersionKey "FileVersion" "${PRODUCT_VERSION}"
|
||||
VIAddVersionKey "CompanyName" "${PRODUCT_PUBLISHER}"
|
||||
VIAddVersionKey "LegalCopyright" "Copyright ${PRODUCT_PUBLISHER}"
|
||||
|
||||
;--- MUI configuration ---
|
||||
!define MUI_ABORTWARNING
|
||||
|
||||
;--- Installer pages ---
|
||||
!insertmacro MUI_PAGE_WELCOME
|
||||
!insertmacro MUI_PAGE_DIRECTORY
|
||||
!insertmacro MUI_PAGE_INSTFILES
|
||||
!define MUI_FINISHPAGE_RUN "$INSTDIR\${PRODUCT_NAME}.exe"
|
||||
!insertmacro MUI_PAGE_FINISH
|
||||
|
||||
;--- Uninstaller pages ---
|
||||
!insertmacro MUI_UNPAGE_CONFIRM
|
||||
!insertmacro MUI_UNPAGE_INSTFILES
|
||||
|
||||
;--- Language ---
|
||||
!insertmacro MUI_LANGUAGE "English"
|
||||
|
||||
;--- Installer section ---
|
||||
Section "Install"
|
||||
; Close any running instance
|
||||
ExecWait 'taskkill /F /IM ${PRODUCT_NAME}.exe' $0
|
||||
|
||||
SetOutPath "$INSTDIR"
|
||||
File /r "${SOURCE_DIR}\*.*"
|
||||
|
||||
; Write uninstaller
|
||||
WriteUninstaller "$INSTDIR\Uninstall.exe"
|
||||
|
||||
; Start Menu shortcut
|
||||
CreateDirectory "$SMPROGRAMS\${PRODUCT_NAME}"
|
||||
CreateShortcut "$SMPROGRAMS\${PRODUCT_NAME}\${PRODUCT_NAME}.lnk" "$INSTDIR\${PRODUCT_NAME}.exe"
|
||||
CreateShortcut "$SMPROGRAMS\${PRODUCT_NAME}\Uninstall ${PRODUCT_NAME}.lnk" "$INSTDIR\Uninstall.exe"
|
||||
|
||||
; Desktop shortcut
|
||||
CreateShortcut "$DESKTOP\${PRODUCT_NAME}.lnk" "$INSTDIR\${PRODUCT_NAME}.exe"
|
||||
|
||||
; Add/Remove Programs registry entry
|
||||
WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" \
|
||||
"DisplayName" "${PRODUCT_NAME}"
|
||||
WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" \
|
||||
"UninstallString" '"$INSTDIR\Uninstall.exe"'
|
||||
WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" \
|
||||
"QuietUninstallString" '"$INSTDIR\Uninstall.exe" /S'
|
||||
WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" \
|
||||
"InstallLocation" "$INSTDIR"
|
||||
WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" \
|
||||
"DisplayIcon" "$INSTDIR\${PRODUCT_NAME}.exe"
|
||||
WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" \
|
||||
"Publisher" "${PRODUCT_PUBLISHER}"
|
||||
WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" \
|
||||
"DisplayVersion" "${PRODUCT_VERSION}"
|
||||
WriteRegDWORD HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" \
|
||||
"NoModify" 1
|
||||
WriteRegDWORD HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" \
|
||||
"NoRepair" 1
|
||||
|
||||
; Store install directory for future upgrades
|
||||
WriteRegStr HKCU "Software\${PRODUCT_NAME}" "InstallDir" "$INSTDIR"
|
||||
SectionEnd
|
||||
|
||||
;--- Uninstaller section ---
|
||||
Section "Uninstall"
|
||||
; Close any running instance
|
||||
ExecWait 'taskkill /F /IM ${PRODUCT_NAME}.exe' $0
|
||||
|
||||
; Remove application files
|
||||
RMDir /r "$INSTDIR"
|
||||
|
||||
; Remove shortcuts
|
||||
RMDir /r "$SMPROGRAMS\${PRODUCT_NAME}"
|
||||
Delete "$DESKTOP\${PRODUCT_NAME}.lnk"
|
||||
|
||||
; Remove registry entries
|
||||
DeleteRegKey HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}"
|
||||
DeleteRegKey HKCU "Software\${PRODUCT_NAME}"
|
||||
SectionEnd
|
||||
@@ -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'),
|
||||
|
||||
+99
-8
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "aryx",
|
||||
"version": "1.0.0",
|
||||
"version": "0.0.8",
|
||||
"description": "Electron orchestrator for Copilot-powered agent workflows across multiple projects.",
|
||||
"private": true,
|
||||
"main": "dist-electron/main/index.js",
|
||||
@@ -8,8 +8,9 @@
|
||||
"dev": "electron-vite dev",
|
||||
"build:electron": "electron-vite build",
|
||||
"build": "bun run build:electron && bun run sidecar:build",
|
||||
"package": "bun run build:electron && bun run sidecar:publish && bun run scripts/package-electron.ts",
|
||||
"installer": "bun run package && bun run scripts/create-installer.ts",
|
||||
"package": "bun run scripts/clean-release.ts && bun run build:electron && bun run sidecar:publish && electron-builder --dir --publish never",
|
||||
"installer": "bun run scripts/clean-release.ts && bun run build:electron && bun run sidecar:publish && electron-builder --publish never",
|
||||
"publish-release": "bun run scripts/clean-release.ts && bun run build:electron && bun run sidecar:publish && electron-builder --publish always",
|
||||
"preview": "electron-vite preview",
|
||||
"lsp:typescript": "typescript-language-server --stdio",
|
||||
"typecheck": "tsc --noEmit -p tsconfig.json",
|
||||
@@ -33,7 +34,6 @@
|
||||
"packageManager": "bun@1.3.6",
|
||||
"devDependencies": {
|
||||
"@dagrejs/dagre": "^3.0.0",
|
||||
"@electron/asar": "^4.1.1",
|
||||
"@lexical/code": "0.42.0",
|
||||
"@lexical/headless": "0.42.0",
|
||||
"@lexical/link": "0.42.0",
|
||||
@@ -41,20 +41,22 @@
|
||||
"@lexical/markdown": "0.42.0",
|
||||
"@lexical/react": "0.42.0",
|
||||
"@lexical/rich-text": "0.42.0",
|
||||
"@modelcontextprotocol/sdk": "^1.28.0",
|
||||
"@tailwindcss/vite": "^4.2.2",
|
||||
"@types/node": "^25.5.0",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "5.1.0",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"@xyflow/react": "^12.10.1",
|
||||
"bun-types": "^1.3.11",
|
||||
"create-dmg": "^8.1.0",
|
||||
"electron": "^41.0.3",
|
||||
"electron-builder": "^26.8.1",
|
||||
"electron-vite": "^5.0.0",
|
||||
"highlight.js": "^11.11.1",
|
||||
"lexical": "0.42.0",
|
||||
"lucide-react": "^0.577.0",
|
||||
"rcedit": "^5.0.2",
|
||||
"react": "^19.2.4",
|
||||
"react-dom": "^19.2.4",
|
||||
"react-markdown": "^10.1.0",
|
||||
@@ -62,9 +64,98 @@
|
||||
"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"
|
||||
},
|
||||
"win": {
|
||||
"target": [
|
||||
"nsis"
|
||||
],
|
||||
"icon": "assets/icons/windows/icon.ico",
|
||||
"artifactName": "Aryx-windows-${arch}.${ext}",
|
||||
"signAndEditExecutable": false,
|
||||
"verifyUpdateCodeSignature": false
|
||||
},
|
||||
"nsis": {
|
||||
"oneClick": false,
|
||||
"perMachine": false,
|
||||
"allowToChangeInstallationDirectory": true,
|
||||
"installerIcon": "assets/icons/windows/icon.ico",
|
||||
"uninstallerIcon": "assets/icons/windows/icon.ico"
|
||||
},
|
||||
"mac": {
|
||||
"target": [
|
||||
"dmg",
|
||||
"zip"
|
||||
],
|
||||
"icon": "assets/icons/macos/icon.icns",
|
||||
"category": "public.app-category.developer-tools",
|
||||
"hardenedRuntime": true,
|
||||
"entitlements": "assets/entitlements.mac.plist",
|
||||
"entitlementsInherit": "assets/entitlements.mac.inherit.plist",
|
||||
"gatekeeperAssess": false,
|
||||
"notarize": true,
|
||||
"artifactName": "Aryx-macos-${arch}.${ext}"
|
||||
},
|
||||
"linux": {
|
||||
"target": [
|
||||
"AppImage"
|
||||
],
|
||||
"icon": "assets/icons/linux/icons",
|
||||
"category": "Development",
|
||||
"artifactName": "Aryx-linux-${arch}.${ext}",
|
||||
"desktop": {
|
||||
"entry": {
|
||||
"Name": "Aryx",
|
||||
"Comment": "Copilot-powered agent workflow orchestrator",
|
||||
"StartupWMClass": "Aryx"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 });
|
||||
@@ -1,238 +0,0 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import { constants } from 'node:fs';
|
||||
import {
|
||||
access,
|
||||
cp,
|
||||
mkdir,
|
||||
readFile,
|
||||
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: NSIS installer ---
|
||||
|
||||
async function resolveNsisPath(): Promise<string> {
|
||||
const candidates = [
|
||||
'C:\\Program Files (x86)\\NSIS\\makensis.exe',
|
||||
'C:\\Program Files\\NSIS\\makensis.exe',
|
||||
'makensis',
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (candidate.includes('\\') && (await pathExists(candidate))) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return 'makensis';
|
||||
}
|
||||
|
||||
async function createWindowsInstaller(version: string): Promise<void> {
|
||||
const nsisScript = join(installerAssetsDirectory, 'windows.nsi');
|
||||
const makensisPath = await resolveNsisPath();
|
||||
|
||||
await runCommand(
|
||||
makensisPath,
|
||||
[
|
||||
`/DPRODUCT_NAME=${productName}`,
|
||||
`/DPRODUCT_VERSION=${version}`,
|
||||
`/DSOURCE_DIR=${packagedAppDirectory}`,
|
||||
`/DOUTPUT_PATH=${installerOutputPath}`,
|
||||
nsisScript,
|
||||
],
|
||||
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');
|
||||
|
||||
try {
|
||||
await runCommand(
|
||||
createDmg,
|
||||
[
|
||||
'--overwrite',
|
||||
'--window-size', '600', '400',
|
||||
'--icon-size', '100',
|
||||
'--icon', appBundleName, '150', '200',
|
||||
'--app-drop-link', '450', '200',
|
||||
installerOutputPath,
|
||||
appBundlePath,
|
||||
],
|
||||
repositoryRoot,
|
||||
);
|
||||
} catch {
|
||||
// create-dmg exits with code 2 when code signing fails (expected without
|
||||
// a Developer ID certificate) but still produces a valid DMG. Check
|
||||
// whether the output file was created before treating this as an error.
|
||||
if (!(await pathExists(installerOutputPath))) {
|
||||
throw new Error('Failed to create DMG — output file was not produced.');
|
||||
}
|
||||
|
||||
console.log('DMG created (code signing skipped — ad-hoc only).');
|
||||
}
|
||||
}
|
||||
|
||||
// --- 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}`);
|
||||
@@ -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.`);
|
||||
@@ -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}`);
|
||||
|
||||
@@ -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}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Aryx.AgentHost.Contracts;
|
||||
|
||||
internal static class HookTypeNames
|
||||
{
|
||||
public const string SessionStart = "sessionStart";
|
||||
public const string SessionEnd = "sessionEnd";
|
||||
public const string UserPromptSubmitted = "userPromptSubmitted";
|
||||
public const string PreToolUse = "preToolUse";
|
||||
public const string PostToolUse = "postToolUse";
|
||||
public const string ErrorOccurred = "errorOccurred";
|
||||
}
|
||||
|
||||
internal sealed class HookConfigFile
|
||||
{
|
||||
public int Version { get; init; }
|
||||
public HookConfigHooks Hooks { get; init; } = new();
|
||||
}
|
||||
|
||||
internal sealed class HookConfigHooks
|
||||
{
|
||||
public IReadOnlyList<HookCommandDefinition>? SessionStart { get; init; }
|
||||
public IReadOnlyList<HookCommandDefinition>? SessionEnd { get; init; }
|
||||
public IReadOnlyList<HookCommandDefinition>? UserPromptSubmitted { get; init; }
|
||||
public IReadOnlyList<HookCommandDefinition>? PreToolUse { get; init; }
|
||||
public IReadOnlyList<HookCommandDefinition>? PostToolUse { get; init; }
|
||||
public IReadOnlyList<HookCommandDefinition>? ErrorOccurred { get; init; }
|
||||
}
|
||||
|
||||
internal sealed class HookCommandDefinition
|
||||
{
|
||||
public string Type { get; init; } = string.Empty;
|
||||
public string? Bash { get; init; }
|
||||
|
||||
[JsonPropertyName("powershell")]
|
||||
public string? PowerShell { get; init; }
|
||||
|
||||
public string? Cwd { get; init; }
|
||||
public IReadOnlyDictionary<string, string>? Env { get; init; }
|
||||
public int? TimeoutSec { get; init; }
|
||||
}
|
||||
|
||||
internal sealed class ResolvedHookSet
|
||||
{
|
||||
public static ResolvedHookSet Empty { get; } = new();
|
||||
|
||||
public IReadOnlyList<HookCommandDefinition> SessionStart { get; init; } = [];
|
||||
public IReadOnlyList<HookCommandDefinition> SessionEnd { get; init; } = [];
|
||||
public IReadOnlyList<HookCommandDefinition> UserPromptSubmitted { get; init; } = [];
|
||||
public IReadOnlyList<HookCommandDefinition> PreToolUse { get; init; } = [];
|
||||
public IReadOnlyList<HookCommandDefinition> PostToolUse { get; init; } = [];
|
||||
public IReadOnlyList<HookCommandDefinition> ErrorOccurred { get; init; } = [];
|
||||
|
||||
public bool IsEmpty =>
|
||||
SessionStart.Count == 0
|
||||
&& SessionEnd.Count == 0
|
||||
&& UserPromptSubmitted.Count == 0
|
||||
&& PreToolUse.Count == 0
|
||||
&& PostToolUse.Count == 0
|
||||
&& ErrorOccurred.Count == 0;
|
||||
}
|
||||
@@ -10,6 +10,16 @@ public sealed class PatternAgentDefinitionDto
|
||||
public string Instructions { get; init; } = string.Empty;
|
||||
public string Model { get; init; } = string.Empty;
|
||||
public string? ReasoningEffort { get; init; }
|
||||
public PatternAgentCopilotConfigDto? Copilot { get; init; }
|
||||
}
|
||||
|
||||
public sealed class PatternAgentCopilotConfigDto
|
||||
{
|
||||
public IReadOnlyList<RunTurnCustomAgentConfigDto> CustomAgents { get; init; } = [];
|
||||
public string? Agent { get; init; }
|
||||
public IReadOnlyList<string> SkillDirectories { get; init; } = [];
|
||||
public IReadOnlyList<string> DisabledSkills { get; init; } = [];
|
||||
public RunTurnInfiniteSessionsConfigDto? InfiniteSessions { get; init; }
|
||||
}
|
||||
|
||||
public sealed class PatternGraphPositionDto
|
||||
@@ -75,6 +85,16 @@ 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 IReadOnlyList<ChatMessageAttachmentDto> Attachments { get; init; } = [];
|
||||
}
|
||||
|
||||
public sealed class ChatMessageAttachmentDto
|
||||
{
|
||||
public string Type { get; init; } = string.Empty;
|
||||
public string? Path { get; init; }
|
||||
public string? Data { get; init; }
|
||||
public string? MimeType { get; init; }
|
||||
public string? DisplayName { get; init; }
|
||||
}
|
||||
|
||||
public sealed class PatternValidationIssueDto
|
||||
@@ -161,6 +181,9 @@ public sealed class RunTurnCommandDto : SidecarCommandEnvelope
|
||||
public string SessionId { get; init; } = string.Empty;
|
||||
public string ProjectPath { get; init; } = string.Empty;
|
||||
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; }
|
||||
@@ -175,8 +198,34 @@ public sealed class ResolveApprovalCommandDto : SidecarCommandEnvelope
|
||||
{
|
||||
public string ApprovalId { get; init; } = string.Empty;
|
||||
public string Decision { get; init; } = string.Empty;
|
||||
public bool AlwaysApprove { get; init; }
|
||||
}
|
||||
|
||||
public sealed class ResolveUserInputCommandDto : SidecarCommandEnvelope
|
||||
{
|
||||
public string UserInputId { get; init; } = string.Empty;
|
||||
public string Answer { get; init; } = string.Empty;
|
||||
public bool WasFreeform { get; init; }
|
||||
}
|
||||
|
||||
public sealed class ListSessionsCommandDto : SidecarCommandEnvelope
|
||||
{
|
||||
public CopilotSessionListFilterDto? Filter { get; init; }
|
||||
}
|
||||
|
||||
public sealed class DeleteSessionCommandDto : SidecarCommandEnvelope
|
||||
{
|
||||
public string? SessionId { get; init; }
|
||||
public string? CopilotSessionId { get; init; }
|
||||
}
|
||||
|
||||
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; } = [];
|
||||
@@ -208,6 +257,48 @@ public sealed class RunTurnLspProfileConfigDto
|
||||
public IReadOnlyList<string> FileExtensions { get; init; } = [];
|
||||
}
|
||||
|
||||
public sealed class RunTurnCustomAgentConfigDto
|
||||
{
|
||||
public string Name { get; init; } = string.Empty;
|
||||
public string? DisplayName { get; init; }
|
||||
public string? Description { get; init; }
|
||||
public IReadOnlyList<string>? Tools { get; init; }
|
||||
public string Prompt { get; init; } = string.Empty;
|
||||
public IReadOnlyList<RunTurnMcpServerConfigDto> McpServers { get; init; } = [];
|
||||
public bool? Infer { get; init; }
|
||||
}
|
||||
|
||||
public sealed class RunTurnInfiniteSessionsConfigDto
|
||||
{
|
||||
public bool? Enabled { get; init; }
|
||||
public double? BackgroundCompactionThreshold { get; init; }
|
||||
public double? BufferExhaustionThreshold { get; init; }
|
||||
}
|
||||
|
||||
public sealed class CopilotSessionListFilterDto
|
||||
{
|
||||
public string? Cwd { get; init; }
|
||||
public string? GitRoot { get; init; }
|
||||
public string? Repository { get; init; }
|
||||
public string? Branch { get; init; }
|
||||
}
|
||||
|
||||
public sealed class CopilotSessionInfoDto
|
||||
{
|
||||
public string CopilotSessionId { get; init; } = string.Empty;
|
||||
public bool ManagedByAryx { get; init; }
|
||||
public string? SessionId { get; init; }
|
||||
public string? AgentId { get; init; }
|
||||
public string StartTime { get; init; } = string.Empty;
|
||||
public string ModifiedTime { get; init; } = string.Empty;
|
||||
public string? Summary { get; init; }
|
||||
public bool IsRemote { get; init; }
|
||||
public string? Cwd { get; init; }
|
||||
public string? GitRoot { get; init; }
|
||||
public string? Repository { get; init; }
|
||||
public string? Branch { get; init; }
|
||||
}
|
||||
|
||||
public abstract class SidecarEventDto
|
||||
{
|
||||
public string Type { get; init; } = string.Empty;
|
||||
@@ -249,6 +340,176 @@ 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
|
||||
{
|
||||
public string SessionId { get; init; } = string.Empty;
|
||||
public string EventKind { get; init; } = string.Empty;
|
||||
public string? AgentId { get; init; }
|
||||
public string? AgentName { get; init; }
|
||||
public string? ToolCallId { get; init; }
|
||||
public string? CustomAgentName { get; init; }
|
||||
public string? CustomAgentDisplayName { get; init; }
|
||||
public string? CustomAgentDescription { get; init; }
|
||||
public string? Error { get; init; }
|
||||
public string? Model { get; init; }
|
||||
public double? TotalToolCalls { get; init; }
|
||||
public double? TotalTokens { get; init; }
|
||||
public double? DurationMs { get; init; }
|
||||
public IReadOnlyList<string>? Tools { get; init; }
|
||||
}
|
||||
|
||||
public sealed class SkillInvokedEventDto : SidecarEventDto
|
||||
{
|
||||
public string SessionId { get; init; } = string.Empty;
|
||||
public string? AgentId { get; init; }
|
||||
public string? AgentName { get; init; }
|
||||
public string SkillName { get; init; } = string.Empty;
|
||||
public string Path { get; init; } = string.Empty;
|
||||
public string Content { get; init; } = string.Empty;
|
||||
public IReadOnlyList<string>? AllowedTools { get; init; }
|
||||
public string? PluginName { get; init; }
|
||||
public string? PluginVersion { get; init; }
|
||||
public string? Description { get; init; }
|
||||
}
|
||||
|
||||
public sealed class HookLifecycleEventDto : SidecarEventDto
|
||||
{
|
||||
public string SessionId { get; init; } = string.Empty;
|
||||
public string? AgentId { get; init; }
|
||||
public string? AgentName { get; init; }
|
||||
public string HookInvocationId { get; init; } = string.Empty;
|
||||
public string HookType { get; init; } = string.Empty;
|
||||
public string Phase { get; init; } = string.Empty;
|
||||
public bool? Success { get; init; }
|
||||
public object? Input { get; init; }
|
||||
public object? Output { get; init; }
|
||||
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;
|
||||
public string? AgentId { get; init; }
|
||||
public string? AgentName { get; init; }
|
||||
public double TokenLimit { get; init; }
|
||||
public double CurrentTokens { get; init; }
|
||||
public double MessagesLength { get; init; }
|
||||
public double? SystemTokens { get; init; }
|
||||
public double? ConversationTokens { get; init; }
|
||||
public double? ToolDefinitionsTokens { get; init; }
|
||||
public bool? IsInitial { get; init; }
|
||||
}
|
||||
|
||||
public sealed class SessionCompactionEventDto : SidecarEventDto
|
||||
{
|
||||
public string SessionId { get; init; } = string.Empty;
|
||||
public string? AgentId { get; init; }
|
||||
public string? AgentName { get; init; }
|
||||
public string Phase { get; init; } = string.Empty;
|
||||
public bool? Success { get; init; }
|
||||
public string? Error { get; init; }
|
||||
public double? SystemTokens { get; init; }
|
||||
public double? ConversationTokens { get; init; }
|
||||
public double? ToolDefinitionsTokens { get; init; }
|
||||
public double? PreCompactionTokens { get; init; }
|
||||
public double? PostCompactionTokens { get; init; }
|
||||
public double? PreCompactionMessagesLength { get; init; }
|
||||
public double? MessagesRemoved { get; init; }
|
||||
public double? TokensRemoved { get; init; }
|
||||
public string? SummaryContent { get; init; }
|
||||
public double? CheckpointNumber { get; init; }
|
||||
public string? CheckpointPath { get; init; }
|
||||
}
|
||||
|
||||
public sealed class PendingMessagesModifiedEventDto : SidecarEventDto
|
||||
{
|
||||
public string SessionId { get; init; } = string.Empty;
|
||||
public string? AgentId { get; init; }
|
||||
public string? AgentName { get; init; }
|
||||
}
|
||||
|
||||
public sealed class SessionsListedEventDto : SidecarEventDto
|
||||
{
|
||||
public IReadOnlyList<CopilotSessionInfoDto> Sessions { get; init; } = [];
|
||||
}
|
||||
|
||||
public sealed class SessionsDeletedEventDto : SidecarEventDto
|
||||
{
|
||||
public string? SessionId { get; init; }
|
||||
public IReadOnlyList<CopilotSessionInfoDto> Sessions { get; init; } = [];
|
||||
}
|
||||
|
||||
public sealed class SessionDisconnectedEventDto : SidecarEventDto
|
||||
{
|
||||
public string SessionId { get; init; } = string.Empty;
|
||||
public IReadOnlyList<string> CancelledRequestIds { get; init; } = [];
|
||||
}
|
||||
|
||||
public sealed class PermissionDetailDto
|
||||
{
|
||||
public string Kind { get; init; } = string.Empty;
|
||||
public string? Intention { get; init; }
|
||||
public string? Command { get; init; }
|
||||
public string? Warning { get; init; }
|
||||
public IReadOnlyList<string>? PossiblePaths { get; init; }
|
||||
public IReadOnlyList<string>? PossibleUrls { get; init; }
|
||||
public bool? HasWriteFileRedirection { get; init; }
|
||||
public string? FileName { get; init; }
|
||||
public string? Diff { get; init; }
|
||||
public string? NewFileContents { get; init; }
|
||||
public string? Path { get; init; }
|
||||
public string? ServerName { get; init; }
|
||||
public string? ToolTitle { get; init; }
|
||||
public object? Args { get; init; }
|
||||
public bool? ReadOnly { get; init; }
|
||||
public string? Url { get; init; }
|
||||
public string? Subject { get; init; }
|
||||
public string? Fact { get; init; }
|
||||
public string? Citations { get; init; }
|
||||
public string? ToolDescription { get; init; }
|
||||
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
|
||||
@@ -262,6 +523,47 @@ public sealed class ApprovalRequestedEventDto : SidecarEventDto
|
||||
public string? PermissionKind { get; init; }
|
||||
public string Title { get; init; } = string.Empty;
|
||||
public string? Detail { get; init; }
|
||||
public PermissionDetailDto? PermissionDetail { get; init; }
|
||||
}
|
||||
|
||||
public sealed class UserInputRequestedEventDto : SidecarEventDto
|
||||
{
|
||||
public string SessionId { get; init; } = string.Empty;
|
||||
public string UserInputId { get; init; } = string.Empty;
|
||||
public string? AgentId { get; init; }
|
||||
public string? AgentName { get; init; }
|
||||
public string Question { get; init; } = string.Empty;
|
||||
public IReadOnlyList<string>? Choices { get; init; }
|
||||
public bool? AllowFreeform { get; init; }
|
||||
}
|
||||
|
||||
public sealed class McpOauthStaticClientConfigDto
|
||||
{
|
||||
public string ClientId { get; init; } = string.Empty;
|
||||
public bool? PublicClient { get; init; }
|
||||
}
|
||||
|
||||
public sealed class McpOauthRequiredEventDto : SidecarEventDto
|
||||
{
|
||||
public string SessionId { get; init; } = string.Empty;
|
||||
public string OauthRequestId { get; init; } = string.Empty;
|
||||
public string? AgentId { get; init; }
|
||||
public string? AgentName { get; init; }
|
||||
public string ServerName { get; init; } = string.Empty;
|
||||
public string ServerUrl { get; init; } = string.Empty;
|
||||
public McpOauthStaticClientConfigDto? StaticClientConfig { get; init; }
|
||||
}
|
||||
|
||||
public sealed class ExitPlanModeRequestedEventDto : SidecarEventDto
|
||||
{
|
||||
public string SessionId { get; init; } = string.Empty;
|
||||
public string ExitPlanId { get; init; } = string.Empty;
|
||||
public string? AgentId { get; init; }
|
||||
public string? AgentName { get; init; }
|
||||
public string Summary { get; init; } = string.Empty;
|
||||
public string PlanContent { get; init; } = string.Empty;
|
||||
public IReadOnlyList<string>? Actions { get; init; }
|
||||
public string? RecommendedAction { get; init; }
|
||||
}
|
||||
|
||||
public sealed class CommandErrorEventDto : SidecarEventDto
|
||||
|
||||
@@ -8,9 +8,12 @@ internal static class AgentInstructionComposer
|
||||
PatternDefinitionDto pattern,
|
||||
PatternAgentDefinitionDto agent,
|
||||
int agentIndex,
|
||||
string workspaceKind = "project")
|
||||
string workspaceKind = "project",
|
||||
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.
|
||||
@@ -20,6 +23,14 @@ internal static class AgentInstructionComposer
|
||||
Answer conversationally and focus on the user's question directly.
|
||||
"""
|
||||
: string.Empty;
|
||||
string planModeGuidance = string.Equals(interactionMode, "plan", StringComparison.OrdinalIgnoreCase)
|
||||
? """
|
||||
You are operating in plan mode.
|
||||
Your job in this phase is to analyze the request, identify constraints, and produce a concrete implementation plan instead of carrying out the implementation.
|
||||
Once the plan is ready, call the built-in `exit_plan_mode` tool so the host can present the plan for review.
|
||||
Do not continue into implementation, file edits, builds, or tests after producing the plan unless the user explicitly asks to leave plan mode and proceed.
|
||||
"""
|
||||
: string.Empty;
|
||||
|
||||
if (string.Equals(pattern.Mode, "group-chat", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
@@ -37,12 +48,12 @@ internal static class AgentInstructionComposer
|
||||
Focus on refining the answer already in progress.
|
||||
""";
|
||||
|
||||
return JoinInstructionBlocks(baseInstructions, workspaceGuidance, groupChatGuidance);
|
||||
return JoinInstructionBlocks(baseInstructions, repositoryInstructions, workspaceGuidance, planModeGuidance, groupChatGuidance);
|
||||
}
|
||||
|
||||
if (!string.Equals(pattern.Mode, "handoff", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return JoinInstructionBlocks(baseInstructions, workspaceGuidance);
|
||||
return JoinInstructionBlocks(baseInstructions, repositoryInstructions, workspaceGuidance, planModeGuidance);
|
||||
}
|
||||
|
||||
string runtimeGuidance = agentIndex == 0
|
||||
@@ -60,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, runtimeGuidance);
|
||||
return JoinInstructionBlocks(baseInstructions, repositoryInstructions, workspaceGuidance, planModeGuidance, runtimeGuidance);
|
||||
}
|
||||
|
||||
private static string JoinInstructionBlocks(params string[] blocks)
|
||||
|
||||
@@ -0,0 +1,640 @@
|
||||
using System.IO;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Channels;
|
||||
using Aryx.AgentHost.Contracts;
|
||||
using GitHub.Copilot.SDK;
|
||||
using Microsoft.Agents.AI;
|
||||
using Microsoft.Extensions.AI;
|
||||
|
||||
namespace Aryx.AgentHost.Services;
|
||||
|
||||
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;
|
||||
private readonly string _description;
|
||||
private readonly SessionConfig? _sessionConfig;
|
||||
private readonly bool _ownsClient;
|
||||
|
||||
public AryxCopilotAgent(
|
||||
CopilotClient copilotClient,
|
||||
SessionConfig? sessionConfig = null,
|
||||
bool ownsClient = false,
|
||||
string? id = null,
|
||||
string? name = null,
|
||||
string? description = null)
|
||||
{
|
||||
_copilotClient = copilotClient ?? throw new ArgumentNullException(nameof(copilotClient));
|
||||
_sessionConfig = sessionConfig;
|
||||
_ownsClient = ownsClient;
|
||||
_id = id;
|
||||
_name = name ?? DefaultName;
|
||||
_description = description ?? DefaultDescription;
|
||||
}
|
||||
|
||||
protected override ValueTask<AgentSession> CreateSessionCoreAsync(CancellationToken cancellationToken = default)
|
||||
=> new(new AryxCopilotAgentSession());
|
||||
|
||||
protected override ValueTask<JsonElement> SerializeSessionCoreAsync(
|
||||
AgentSession session,
|
||||
JsonSerializerOptions? jsonSerializerOptions = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (session is not AryxCopilotAgentSession typedSession)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"The provided session type '{session.GetType().Name}' is not compatible with this agent. Only sessions of type '{nameof(AryxCopilotAgentSession)}' can be serialized by this agent.");
|
||||
}
|
||||
|
||||
return new(typedSession.Serialize(jsonSerializerOptions));
|
||||
}
|
||||
|
||||
protected override ValueTask<AgentSession> DeserializeSessionCoreAsync(
|
||||
JsonElement serializedState,
|
||||
JsonSerializerOptions? jsonSerializerOptions = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
=> new(AryxCopilotAgentSession.Deserialize(serializedState, jsonSerializerOptions));
|
||||
|
||||
protected override Task<AgentResponse> RunCoreAsync(
|
||||
IEnumerable<ChatMessage> messages,
|
||||
AgentSession? session = null,
|
||||
AgentRunOptions? options = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
=> RunCoreStreamingAsync(messages, session, options, cancellationToken).ToAgentResponseAsync(cancellationToken);
|
||||
|
||||
protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(
|
||||
IEnumerable<ChatMessage> messages,
|
||||
AgentSession? session = null,
|
||||
AgentRunOptions? options = null,
|
||||
[EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(messages);
|
||||
|
||||
session ??= await CreateSessionAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (session is not AryxCopilotAgentSession typedSession)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"The provided session type '{session.GetType().Name}' is not compatible with this agent. Only sessions of type '{nameof(AryxCopilotAgentSession)}' can be used by this agent.");
|
||||
}
|
||||
|
||||
await EnsureClientStartedAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
SessionConfig sessionConfig = CreateConfiguredSessionConfig(_sessionConfig, options);
|
||||
CopilotSession copilotSession;
|
||||
if (typedSession.SessionId is not null)
|
||||
{
|
||||
copilotSession = await _copilotClient.ResumeSessionAsync(
|
||||
typedSession.SessionId,
|
||||
CreateResumeConfig(sessionConfig),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
copilotSession = await _copilotClient.CreateSessionAsync(sessionConfig, cancellationToken).ConfigureAwait(false);
|
||||
typedSession.SessionId = copilotSession.SessionId;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Channel<AgentResponseUpdate> channel = Channel.CreateUnbounded<AgentResponseUpdate>();
|
||||
|
||||
using IDisposable subscription = copilotSession.On(evt =>
|
||||
{
|
||||
switch (evt)
|
||||
{
|
||||
case AssistantMessageDeltaEvent deltaEvent:
|
||||
channel.Writer.TryWrite(ConvertToAgentResponseUpdate(deltaEvent));
|
||||
break;
|
||||
|
||||
case AssistantMessageEvent assistantMessage:
|
||||
channel.Writer.TryWrite(ConvertToAgentResponseUpdate(assistantMessage));
|
||||
break;
|
||||
|
||||
case AssistantUsageEvent usageEvent:
|
||||
channel.Writer.TryWrite(ConvertToAgentResponseUpdate(usageEvent));
|
||||
break;
|
||||
|
||||
case SessionIdleEvent idleEvent:
|
||||
channel.Writer.TryWrite(ConvertToAgentResponseUpdate(idleEvent));
|
||||
channel.Writer.TryComplete();
|
||||
break;
|
||||
|
||||
case SessionErrorEvent errorEvent:
|
||||
channel.Writer.TryWrite(ConvertToAgentResponseUpdate(errorEvent));
|
||||
channel.Writer.TryComplete(new InvalidOperationException(
|
||||
$"Session error: {errorEvent.Data?.Message ?? "Unknown error"}"));
|
||||
break;
|
||||
|
||||
default:
|
||||
channel.Writer.TryWrite(ConvertToAgentResponseUpdate(evt));
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
string? tempDir = null;
|
||||
try
|
||||
{
|
||||
string prompt = string.Join("\n", messages.Select(message => message.Text));
|
||||
(List<UserMessageDataAttachmentsItem>? attachments, string? messageMode, tempDir) = await ProcessMessageAttachmentsAsync(
|
||||
messages,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
MessageOptions messageOptions = new()
|
||||
{
|
||||
Prompt = prompt,
|
||||
Mode = string.IsNullOrWhiteSpace(messageMode) ? null : messageMode,
|
||||
};
|
||||
|
||||
if (attachments is not null)
|
||||
{
|
||||
messageOptions.Attachments = [.. attachments];
|
||||
}
|
||||
|
||||
await copilotSession.SendAsync(messageOptions, cancellationToken).ConfigureAwait(false);
|
||||
await foreach (AgentResponseUpdate update in channel.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
yield return update;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
CleanupTempDir(tempDir);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
await copilotSession.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
protected override string? IdCore => _id;
|
||||
|
||||
public override string Name => _name;
|
||||
|
||||
public override string Description => _description;
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_ownsClient)
|
||||
{
|
||||
await _copilotClient.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
internal static SessionConfig CreateConfiguredSessionConfig(SessionConfig? source, AgentRunOptions? options)
|
||||
{
|
||||
SessionConfig sessionConfig = source?.Clone() ?? new SessionConfig();
|
||||
sessionConfig.Streaming = true;
|
||||
if (sessionConfig.SystemMessage is not null)
|
||||
{
|
||||
sessionConfig.SystemMessage = CloneSystemMessage(sessionConfig.SystemMessage);
|
||||
}
|
||||
|
||||
if (options is not ChatClientAgentRunOptions { ChatOptions: { } chatOptions })
|
||||
{
|
||||
return sessionConfig;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(chatOptions.ModelId))
|
||||
{
|
||||
sessionConfig.Model = chatOptions.ModelId;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(chatOptions.Instructions))
|
||||
{
|
||||
AppendInstructions(sessionConfig, chatOptions.Instructions);
|
||||
}
|
||||
|
||||
sessionConfig.Tools = MergeTools(sessionConfig.Tools, chatOptions.Tools);
|
||||
return sessionConfig;
|
||||
}
|
||||
|
||||
internal static IReadOnlyList<FunctionCallContent> ConvertToolRequestsToFunctionCalls(
|
||||
AssistantMessageDataToolRequestsItem[]? toolRequests)
|
||||
{
|
||||
if (toolRequests is not { Length: > 0 })
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
List<FunctionCallContent> contents = [];
|
||||
foreach (AssistantMessageDataToolRequestsItem toolRequest in toolRequests)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(toolRequest.ToolCallId) || string.IsNullOrWhiteSpace(toolRequest.Name))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Only project handoff tool calls as FunctionCallContent for the Agent Framework.
|
||||
// Other tool calls (ask_user, MCP tools, etc.) are resolved by the Copilot SDK
|
||||
// internally and must not be surfaced, because AIAgentHostExecutor tracks every
|
||||
// FunctionCallContent as an outstanding request. An unmatched request prevents
|
||||
// the executor from emitting a TurnToken, which stalls group-chat advancement.
|
||||
if (!IsHandoffToolName(toolRequest.Name))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
contents.Add(new FunctionCallContent(
|
||||
toolRequest.ToolCallId,
|
||||
toolRequest.Name,
|
||||
ParseToolArguments(toolRequest.Arguments)));
|
||||
}
|
||||
|
||||
return contents;
|
||||
}
|
||||
|
||||
private static bool IsHandoffToolName(string? name)
|
||||
{
|
||||
return !string.IsNullOrWhiteSpace(name)
|
||||
&& name.StartsWith(HandoffToolPrefix, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private async Task EnsureClientStartedAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_copilotClient.State != ConnectionState.Connected)
|
||||
{
|
||||
await _copilotClient.StartAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static ResumeSessionConfig CreateResumeConfig(SessionConfig source)
|
||||
{
|
||||
return new ResumeSessionConfig
|
||||
{
|
||||
ClientName = source.ClientName,
|
||||
Model = source.Model,
|
||||
Tools = source.Tools is not null ? [.. source.Tools] : null,
|
||||
SystemMessage = CloneSystemMessage(source.SystemMessage),
|
||||
AvailableTools = source.AvailableTools is not null ? [.. source.AvailableTools] : null,
|
||||
ExcludedTools = source.ExcludedTools is not null ? [.. source.ExcludedTools] : null,
|
||||
Provider = source.Provider,
|
||||
OnPermissionRequest = source.OnPermissionRequest,
|
||||
OnUserInputRequest = source.OnUserInputRequest,
|
||||
Hooks = source.Hooks,
|
||||
WorkingDirectory = source.WorkingDirectory,
|
||||
ConfigDir = source.ConfigDir,
|
||||
Streaming = true,
|
||||
McpServers = source.McpServers is not null
|
||||
? new Dictionary<string, object>(source.McpServers, source.McpServers.Comparer)
|
||||
: null,
|
||||
CustomAgents = source.CustomAgents is not null ? [.. source.CustomAgents] : null,
|
||||
Agent = source.Agent,
|
||||
SkillDirectories = source.SkillDirectories is not null ? [.. source.SkillDirectories] : null,
|
||||
DisabledSkills = source.DisabledSkills is not null ? [.. source.DisabledSkills] : null,
|
||||
InfiniteSessions = source.InfiniteSessions,
|
||||
OnEvent = source.OnEvent,
|
||||
ReasoningEffort = source.ReasoningEffort,
|
||||
};
|
||||
}
|
||||
|
||||
private static SystemMessageConfig? CloneSystemMessage(SystemMessageConfig? source)
|
||||
{
|
||||
if (source is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new SystemMessageConfig
|
||||
{
|
||||
Mode = source.Mode,
|
||||
Content = source.Content,
|
||||
Sections = source.Sections is not null ? new Dictionary<string, SectionOverride>(source.Sections) : null,
|
||||
};
|
||||
}
|
||||
|
||||
private static void AppendInstructions(SessionConfig sessionConfig, string instructions)
|
||||
{
|
||||
string trimmedInstructions = instructions.Trim();
|
||||
if (trimmedInstructions.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (sessionConfig.SystemMessage is null)
|
||||
{
|
||||
sessionConfig.SystemMessage = new SystemMessageConfig
|
||||
{
|
||||
Mode = SystemMessageMode.Append,
|
||||
Content = trimmedInstructions,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
string? existingContent = sessionConfig.SystemMessage.Content;
|
||||
sessionConfig.SystemMessage.Content = string.IsNullOrWhiteSpace(existingContent)
|
||||
? trimmedInstructions
|
||||
: $"{existingContent.Trim()}\n\n{trimmedInstructions}";
|
||||
}
|
||||
|
||||
private static ICollection<AIFunction>? MergeTools(
|
||||
ICollection<AIFunction>? sessionTools,
|
||||
IList<AITool>? runtimeTools)
|
||||
{
|
||||
if (runtimeTools is not { Count: > 0 })
|
||||
{
|
||||
return sessionTools;
|
||||
}
|
||||
|
||||
List<AIFunction> mergedTools = sessionTools is not null ? [.. sessionTools] : [];
|
||||
foreach (AITool runtimeTool in runtimeTools)
|
||||
{
|
||||
mergedTools.Add(MapRuntimeTool(runtimeTool));
|
||||
}
|
||||
|
||||
return mergedTools;
|
||||
}
|
||||
|
||||
private static AIFunction MapRuntimeTool(AITool tool)
|
||||
{
|
||||
return tool switch
|
||||
{
|
||||
AIFunction function => function,
|
||||
AIFunctionDeclaration declaration when IsHandoffDeclaration(declaration) => CreateInvokableHandoffFunction(declaration),
|
||||
AIFunctionDeclaration declaration => throw new NotSupportedException(
|
||||
$"GitHub Copilot session tools must be invokable AIFunctions. Runtime tool '{declaration.Name}' is declaration-only."),
|
||||
_ => throw new NotSupportedException(
|
||||
$"GitHub Copilot session tools must be invokable AIFunctions. Runtime tool '{tool.Name}' is not supported."),
|
||||
};
|
||||
}
|
||||
|
||||
private static bool IsHandoffDeclaration(AIFunctionDeclaration declaration)
|
||||
{
|
||||
return IsHandoffToolName(declaration.Name);
|
||||
}
|
||||
|
||||
private static AIFunction CreateInvokableHandoffFunction(AIFunctionDeclaration declaration)
|
||||
{
|
||||
AIFunction function = AIFunctionFactory.Create(
|
||||
(string? reasonForHandoff) => "Transferred.",
|
||||
new AIFunctionFactoryOptions
|
||||
{
|
||||
Name = declaration.Name,
|
||||
Description = declaration.Description,
|
||||
AdditionalProperties = new Dictionary<string, object?>
|
||||
{
|
||||
["skip_permission"] = true,
|
||||
},
|
||||
});
|
||||
return function;
|
||||
}
|
||||
|
||||
private AgentResponseUpdate ConvertToAgentResponseUpdate(AssistantMessageDeltaEvent deltaEvent)
|
||||
{
|
||||
TextContent textContent = new(deltaEvent.Data?.DeltaContent ?? string.Empty)
|
||||
{
|
||||
RawRepresentation = deltaEvent,
|
||||
};
|
||||
|
||||
return new AgentResponseUpdate(ChatRole.Assistant, [textContent])
|
||||
{
|
||||
AgentId = Id,
|
||||
MessageId = deltaEvent.Data?.MessageId,
|
||||
CreatedAt = deltaEvent.Timestamp,
|
||||
};
|
||||
}
|
||||
|
||||
private AgentResponseUpdate ConvertToAgentResponseUpdate(AssistantMessageEvent assistantMessage)
|
||||
{
|
||||
List<AIContent> contents = [];
|
||||
contents.AddRange(ConvertToolRequestsToFunctionCalls(assistantMessage.Data?.ToolRequests));
|
||||
contents.Add(new AIContent
|
||||
{
|
||||
RawRepresentation = assistantMessage,
|
||||
});
|
||||
|
||||
return new AgentResponseUpdate(ChatRole.Assistant, contents)
|
||||
{
|
||||
AgentId = Id,
|
||||
ResponseId = assistantMessage.Data?.MessageId,
|
||||
MessageId = assistantMessage.Data?.MessageId,
|
||||
CreatedAt = assistantMessage.Timestamp,
|
||||
};
|
||||
}
|
||||
|
||||
private AgentResponseUpdate ConvertToAgentResponseUpdate(AssistantUsageEvent usageEvent)
|
||||
{
|
||||
UsageDetails usageDetails = new()
|
||||
{
|
||||
InputTokenCount = (int?)usageEvent.Data?.InputTokens,
|
||||
OutputTokenCount = (int?)usageEvent.Data?.OutputTokens,
|
||||
TotalTokenCount = (int?)((usageEvent.Data?.InputTokens ?? 0) + (usageEvent.Data?.OutputTokens ?? 0)),
|
||||
CachedInputTokenCount = (int?)usageEvent.Data?.CacheReadTokens,
|
||||
};
|
||||
|
||||
UsageContent usageContent = new(usageDetails)
|
||||
{
|
||||
RawRepresentation = usageEvent,
|
||||
};
|
||||
|
||||
return new AgentResponseUpdate(ChatRole.Assistant, [usageContent])
|
||||
{
|
||||
AgentId = Id,
|
||||
CreatedAt = usageEvent.Timestamp,
|
||||
};
|
||||
}
|
||||
|
||||
private AgentResponseUpdate ConvertToAgentResponseUpdate(SessionEvent sessionEvent)
|
||||
{
|
||||
AIContent content = new()
|
||||
{
|
||||
RawRepresentation = sessionEvent,
|
||||
};
|
||||
|
||||
return new AgentResponseUpdate(ChatRole.Assistant, [content])
|
||||
{
|
||||
AgentId = Id,
|
||||
CreatedAt = sessionEvent.Timestamp,
|
||||
};
|
||||
}
|
||||
|
||||
private static Dictionary<string, object?>? ParseToolArguments(object? arguments)
|
||||
{
|
||||
if (arguments is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (arguments is Dictionary<string, object?> dictionary)
|
||||
{
|
||||
return new Dictionary<string, object?>(dictionary, StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
if (arguments is JsonElement jsonElement)
|
||||
{
|
||||
if (jsonElement.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return JsonSerializer.Deserialize<Dictionary<string, object?>>(jsonElement.GetRawText(), ToolArgumentJsonOptions);
|
||||
}
|
||||
|
||||
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(
|
||||
IEnumerable<ChatMessage> messages,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
List<UserMessageDataAttachmentsItem>? attachments = null;
|
||||
string? messageMode = null;
|
||||
string? tempDir = null;
|
||||
foreach (ChatMessage message in messages)
|
||||
{
|
||||
foreach (AIContent content in message.Contents)
|
||||
{
|
||||
if (content is DataContent dataContent)
|
||||
{
|
||||
tempDir ??= Directory.CreateDirectory(
|
||||
Path.Combine(Path.GetTempPath(), $"af_copilot_{Guid.NewGuid():N}")).FullName;
|
||||
|
||||
string tempFilePath = await dataContent.SaveToAsync(tempDir, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
attachments ??= [];
|
||||
attachments.Add(new UserMessageDataAttachmentsItemFile
|
||||
{
|
||||
Path = tempFilePath,
|
||||
DisplayName = Path.GetFileName(tempFilePath),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if (content.RawRepresentation is ChatMessageAttachmentDto protocolAttachment)
|
||||
{
|
||||
attachments ??= [];
|
||||
attachments.Add(CreateProtocolAttachment(protocolAttachment));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (content.RawRepresentation is CopilotMessageOptionsMetadata metadata
|
||||
&& !string.IsNullOrWhiteSpace(metadata.MessageMode))
|
||||
{
|
||||
messageMode = metadata.MessageMode.Trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (attachments, messageMode, tempDir);
|
||||
}
|
||||
|
||||
private static UserMessageDataAttachmentsItem CreateProtocolAttachment(ChatMessageAttachmentDto attachment)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(attachment);
|
||||
|
||||
return attachment.Type switch
|
||||
{
|
||||
"file" => CreateFileAttachment(attachment),
|
||||
"blob" => CreateBlobAttachment(attachment),
|
||||
_ => throw new NotSupportedException($"Unsupported attachment type '{attachment.Type}'."),
|
||||
};
|
||||
}
|
||||
|
||||
private static UserMessageDataAttachmentsItemFile CreateFileAttachment(ChatMessageAttachmentDto attachment)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(attachment.Path))
|
||||
{
|
||||
throw new InvalidOperationException("File attachments require an absolute path.");
|
||||
}
|
||||
|
||||
string path = attachment.Path.Trim();
|
||||
if (!Path.IsPathRooted(path))
|
||||
{
|
||||
throw new InvalidOperationException($"File attachment path '{path}' must be absolute.");
|
||||
}
|
||||
|
||||
return new UserMessageDataAttachmentsItemFile
|
||||
{
|
||||
Path = path,
|
||||
DisplayName = string.IsNullOrWhiteSpace(attachment.DisplayName)
|
||||
? Path.GetFileName(path)
|
||||
: attachment.DisplayName.Trim(),
|
||||
};
|
||||
}
|
||||
|
||||
private static UserMessageDataAttachmentsItemBlob CreateBlobAttachment(ChatMessageAttachmentDto attachment)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(attachment.Data))
|
||||
{
|
||||
throw new InvalidOperationException("Blob attachments require base64-encoded data.");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(attachment.MimeType))
|
||||
{
|
||||
throw new InvalidOperationException("Blob attachments require a MIME type.");
|
||||
}
|
||||
|
||||
return new UserMessageDataAttachmentsItemBlob
|
||||
{
|
||||
Data = attachment.Data.Trim(),
|
||||
MimeType = attachment.MimeType.Trim(),
|
||||
DisplayName = string.IsNullOrWhiteSpace(attachment.DisplayName) ? null : attachment.DisplayName.Trim(),
|
||||
};
|
||||
}
|
||||
|
||||
private static void CleanupTempDir(string? tempDir)
|
||||
{
|
||||
if (tempDir is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Directory.Delete(tempDir, recursive: true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class AryxCopilotAgentSession : AgentSession
|
||||
{
|
||||
private static readonly JsonSerializerOptions DefaultJsonOptions = JsonSerialization.CreateWebOptions();
|
||||
|
||||
public AryxCopilotAgentSession()
|
||||
{
|
||||
}
|
||||
|
||||
[JsonConstructor]
|
||||
public AryxCopilotAgentSession(string? sessionId, AgentSessionStateBag? stateBag = null)
|
||||
: base(stateBag ?? new AgentSessionStateBag())
|
||||
{
|
||||
SessionId = sessionId;
|
||||
}
|
||||
|
||||
[JsonPropertyName("sessionId")]
|
||||
public string? SessionId { get; set; }
|
||||
|
||||
internal JsonElement Serialize(JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
{
|
||||
JsonSerializerOptions options = jsonSerializerOptions ?? DefaultJsonOptions;
|
||||
return JsonSerializer.SerializeToElement(this, options);
|
||||
}
|
||||
|
||||
internal static AryxCopilotAgentSession Deserialize(
|
||||
JsonElement serializedState,
|
||||
JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
{
|
||||
if (serializedState.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
throw new ArgumentException("The serialized session state must be a JSON object.", nameof(serializedState));
|
||||
}
|
||||
|
||||
JsonSerializerOptions options = jsonSerializerOptions ?? DefaultJsonOptions;
|
||||
return serializedState.Deserialize<AryxCopilotAgentSession>(options)
|
||||
?? new AryxCopilotAgentSession();
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Threading;
|
||||
using GitHub.Copilot.SDK;
|
||||
using Aryx.AgentHost.Contracts;
|
||||
using Microsoft.Agents.AI;
|
||||
@@ -12,22 +13,29 @@ internal sealed class CopilotAgentBundle : IAsyncDisposable
|
||||
{
|
||||
private readonly List<IAsyncDisposable> _disposables = [];
|
||||
|
||||
private CopilotAgentBundle(IReadOnlyList<AIAgent> agents)
|
||||
internal CopilotAgentBundle(IReadOnlyList<AIAgent> agents, bool hasConfiguredHooks)
|
||||
{
|
||||
Agents = agents;
|
||||
HasConfiguredHooks = hasConfiguredHooks;
|
||||
}
|
||||
|
||||
public IReadOnlyList<AIAgent> Agents { get; }
|
||||
|
||||
public bool HasConfiguredHooks { get; }
|
||||
|
||||
public static async Task<CopilotAgentBundle> CreateAsync(
|
||||
RunTurnCommandDto command,
|
||||
Func<PatternAgentDefinitionDto, PermissionRequest, PermissionInvocation, Task<PermissionRequestResult>> onPermissionRequest,
|
||||
Func<PatternAgentDefinitionDto, UserInputRequest, UserInputInvocation, Task<UserInputResponse>> onUserInputRequest,
|
||||
Action<PatternAgentDefinitionDto, SessionEvent>? onSessionEvent,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
List<IAsyncDisposable> disposables = [];
|
||||
List<AIAgent> agents = [];
|
||||
CopilotClientOptions clientOptions = CopilotCliPathResolver.CreateClientOptions();
|
||||
ResolvedHookSet configuredHooks = await HookConfigLoader.LoadAsync(command.ProjectPath, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
IHookCommandRunner hookCommandRunner = HookCommandRunner.Instance;
|
||||
SessionToolingBundle? toolingBundle = command.Tooling is null
|
||||
? null
|
||||
: await SessionToolingBundle.CreateAsync(command.Tooling, command.ProjectPath, cancellationToken)
|
||||
@@ -43,23 +51,19 @@ internal sealed class CopilotAgentBundle : IAsyncDisposable
|
||||
CopilotClient client = new(clientOptions);
|
||||
await client.StartAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
SessionConfig sessionConfig = new()
|
||||
{
|
||||
Model = definition.Model,
|
||||
ReasoningEffort = definition.ReasoningEffort,
|
||||
SystemMessage = new SystemMessageConfig
|
||||
{
|
||||
Content = AgentInstructionComposer.Compose(command.Pattern, definition, agentIndex, command.WorkspaceKind),
|
||||
},
|
||||
WorkingDirectory = command.ProjectPath,
|
||||
OnPermissionRequest = (request, invocation) => onPermissionRequest(definition, request, invocation),
|
||||
OnEvent = evt => onSessionEvent?.Invoke(definition, evt),
|
||||
Streaming = true,
|
||||
};
|
||||
SessionConfig sessionConfig = CreateSessionConfig(
|
||||
command,
|
||||
definition,
|
||||
agentIndex,
|
||||
(request, invocation) => onPermissionRequest(definition, request, invocation),
|
||||
(request, invocation) => onUserInputRequest(definition, request, invocation),
|
||||
evt => onSessionEvent?.Invoke(definition, evt),
|
||||
configuredHooks,
|
||||
hookCommandRunner);
|
||||
|
||||
ApplySessionTooling(sessionConfig, toolingBundle?.McpServers, toolingBundle?.Tools);
|
||||
|
||||
GitHubCopilotAgent agent = new(
|
||||
AryxCopilotAgent agent = new(
|
||||
client,
|
||||
sessionConfig,
|
||||
ownsClient: true,
|
||||
@@ -71,11 +75,51 @@ internal sealed class CopilotAgentBundle : IAsyncDisposable
|
||||
disposables.Add(agent);
|
||||
}
|
||||
|
||||
CopilotAgentBundle bundle = new(agents);
|
||||
CopilotAgentBundle bundle = new(agents, hasConfiguredHooks: !configuredHooks.IsEmpty);
|
||||
bundle._disposables.AddRange(disposables);
|
||||
return bundle;
|
||||
}
|
||||
|
||||
internal static SessionConfig CreateSessionConfig(
|
||||
RunTurnCommandDto command,
|
||||
PatternAgentDefinitionDto definition,
|
||||
int agentIndex,
|
||||
PermissionRequestHandler? onPermissionRequest = null,
|
||||
UserInputHandler? onUserInputRequest = null,
|
||||
SessionEventHandler? onSessionEvent = null,
|
||||
ResolvedHookSet? configuredHooks = null,
|
||||
IHookCommandRunner? hookCommandRunner = null)
|
||||
{
|
||||
// Let the Copilot SDK allocate session IDs. Explicit custom SessionId values currently
|
||||
// cause turns to complete without assistant output, even for simple single-agent prompts.
|
||||
return new SessionConfig
|
||||
{
|
||||
Model = definition.Model,
|
||||
ReasoningEffort = definition.ReasoningEffort,
|
||||
SystemMessage = new SystemMessageConfig
|
||||
{
|
||||
Content = AgentInstructionComposer.Compose(
|
||||
command.Pattern,
|
||||
definition,
|
||||
agentIndex,
|
||||
command.WorkspaceKind,
|
||||
command.Mode,
|
||||
command.ProjectInstructions),
|
||||
},
|
||||
WorkingDirectory = command.ProjectPath,
|
||||
OnPermissionRequest = onPermissionRequest,
|
||||
OnUserInputRequest = onUserInputRequest,
|
||||
Hooks = CopilotSessionHooks.Create(command, definition, configuredHooks, hookCommandRunner),
|
||||
OnEvent = onSessionEvent,
|
||||
Streaming = true,
|
||||
CustomAgents = CreateCustomAgents(definition.Copilot?.CustomAgents),
|
||||
Agent = NormalizeOptionalString(definition.Copilot?.Agent),
|
||||
SkillDirectories = CreateStringList(definition.Copilot?.SkillDirectories),
|
||||
DisabledSkills = CreateStringList(definition.Copilot?.DisabledSkills),
|
||||
InfiniteSessions = CreateInfiniteSessions(definition.Copilot?.InfiniteSessions),
|
||||
};
|
||||
}
|
||||
|
||||
internal static void ApplySessionTooling(
|
||||
SessionConfig sessionConfig,
|
||||
Dictionary<string, object>? mcpServers,
|
||||
@@ -92,6 +136,55 @@ internal sealed class CopilotAgentBundle : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
internal static List<CustomAgentConfig>? CreateCustomAgents(
|
||||
IReadOnlyList<RunTurnCustomAgentConfigDto>? customAgents)
|
||||
{
|
||||
if (customAgents is not { Count: > 0 })
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return customAgents.Select(customAgent => new CustomAgentConfig
|
||||
{
|
||||
Name = customAgent.Name,
|
||||
DisplayName = NormalizeOptionalString(customAgent.DisplayName),
|
||||
Description = NormalizeOptionalString(customAgent.Description),
|
||||
Tools = customAgent.Tools is null ? null : [.. customAgent.Tools],
|
||||
Prompt = customAgent.Prompt,
|
||||
McpServers = customAgent.McpServers.Count == 0
|
||||
? null
|
||||
: SessionToolingBundle.BuildMcpServerConfigurations(customAgent.McpServers),
|
||||
Infer = customAgent.Infer,
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
internal static InfiniteSessionConfig? CreateInfiniteSessions(RunTurnInfiniteSessionsConfigDto? config)
|
||||
{
|
||||
if (config is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new InfiniteSessionConfig
|
||||
{
|
||||
Enabled = config.Enabled,
|
||||
BackgroundCompactionThreshold = config.BackgroundCompactionThreshold,
|
||||
BufferExhaustionThreshold = config.BufferExhaustionThreshold,
|
||||
};
|
||||
}
|
||||
|
||||
private static List<string>? CreateStringList(IReadOnlyList<string>? values)
|
||||
{
|
||||
return values is { Count: > 0 }
|
||||
? [.. values]
|
||||
: null;
|
||||
}
|
||||
|
||||
private static string? NormalizeOptionalString(string? value)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
}
|
||||
|
||||
public Workflow BuildWorkflow(PatternDefinitionDto pattern)
|
||||
{
|
||||
return pattern.Mode switch
|
||||
@@ -124,7 +217,10 @@ internal sealed class CopilotAgentBundle : IAsyncDisposable
|
||||
definition => definition,
|
||||
StringComparer.Ordinal);
|
||||
PatternHandoffTopology topology = PatternGraphResolver.ResolveHandoff(pattern);
|
||||
AIAgent entryAgent = agentMap.GetValueOrDefault(topology.EntryAgentId) ?? Agents[0];
|
||||
string entryAgentId = agentMap.ContainsKey(topology.EntryAgentId)
|
||||
? topology.EntryAgentId
|
||||
: pattern.Agents.FirstOrDefault()?.Id ?? topology.EntryAgentId;
|
||||
AIAgent entryAgent = agentMap.GetValueOrDefault(entryAgentId) ?? Agents[0];
|
||||
|
||||
HandoffsWorkflowBuilder builder = AgentWorkflowBuilder.CreateHandoffBuilderWith(entryAgent)
|
||||
.WithHandoffInstructions(HandoffWorkflowGuidance.CreateWorkflowInstructions());
|
||||
|
||||
@@ -9,9 +9,20 @@ internal sealed class CopilotApprovalCoordinator
|
||||
private const string ApprovedDecision = "approved";
|
||||
private const string RejectedDecision = "rejected";
|
||||
private const string ToolCallApprovalKind = "tool-call";
|
||||
private const string StoreMemoryToolName = "store_memory";
|
||||
private const string WebFetchToolName = "web_fetch";
|
||||
private const string ShellPermissionKind = "shell";
|
||||
private const string WritePermissionKind = "write";
|
||||
private const string ReadPermissionKind = "read";
|
||||
private const string McpPermissionKind = "mcp";
|
||||
private const string UrlPermissionKind = "url";
|
||||
private const string MemoryPermissionKind = "memory";
|
||||
private const string CustomToolPermissionKind = "custom-tool";
|
||||
private const string HookPermissionKind = "hook";
|
||||
private const string ToolCallingActivityType = "tool-calling";
|
||||
|
||||
private readonly ConcurrentDictionary<string, PendingApprovalRequest> _pendingApprovals = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<string, ConcurrentDictionary<string, byte>> _requestApprovedTools = new(StringComparer.Ordinal);
|
||||
|
||||
public Task ResolveApprovalAsync(
|
||||
ResolveApprovalCommandDto command,
|
||||
@@ -28,6 +39,11 @@ internal sealed class CopilotApprovalCoordinator
|
||||
throw new InvalidOperationException($"Approval \"{approvalId}\" is no longer pending.");
|
||||
}
|
||||
|
||||
if (decision == PermissionRequestResultKind.Approved && command.AlwaysApprove)
|
||||
{
|
||||
CacheApprovedToolForRequest(pending.RequestId, pending.ApprovalCacheKey);
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
@@ -39,14 +55,47 @@ 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);
|
||||
if (!RequiresToolCallApproval(command.Pattern.ApprovalPolicy, agent.Id, toolName))
|
||||
string? autoApprovedToolName = ResolveAutoApprovedToolName(request);
|
||||
string? mcpServerApprovalKey = ResolveMcpServerApprovalKey(request);
|
||||
string? approvalCacheKey = ResolveApprovalCacheKey(toolName, autoApprovedToolName);
|
||||
|
||||
AgentActivityEventDto? fileChangeActivity = BuildToolCallFileChangeActivity(command, agent, request, toolName);
|
||||
if (fileChangeActivity is not null && onActivity is not null)
|
||||
{
|
||||
await onActivity(fileChangeActivity).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (IsToolApprovedForRequest(command.RequestId, approvalCacheKey)
|
||||
|| !RequiresToolCallApproval(command.Pattern.ApprovalPolicy, agent.Id, toolName, autoApprovedToolName, mcpServerApprovalKey))
|
||||
{
|
||||
return CreateApprovalResult(PermissionRequestResultKind.Approved);
|
||||
}
|
||||
|
||||
PendingApprovalRequest pending = CreatePendingApproval(command);
|
||||
PendingApprovalRequest pending = CreatePendingApproval(command, approvalCacheKey);
|
||||
if (!_pendingApprovals.TryAdd(pending.ApprovalId, pending))
|
||||
{
|
||||
throw new InvalidOperationException($"Approval \"{pending.ApprovalId}\" is already pending.");
|
||||
@@ -131,13 +180,126 @@ internal sealed class CopilotApprovalCoordinator
|
||||
PermissionKind = permissionKind,
|
||||
Title = title,
|
||||
Detail = detail,
|
||||
PermissionDetail = BuildPermissionDetail(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)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
|
||||
return request switch
|
||||
{
|
||||
PermissionRequestShell shell => new PermissionDetailDto
|
||||
{
|
||||
Kind = ShellPermissionKind,
|
||||
Intention = NormalizeOptionalString(shell.Intention),
|
||||
Command = NormalizeOptionalString(shell.FullCommandText),
|
||||
Warning = NormalizeOptionalString(shell.Warning),
|
||||
PossiblePaths = NormalizeOptionalStringList(shell.PossiblePaths),
|
||||
PossibleUrls = NormalizeOptionalStringList(shell.PossibleUrls.Select(static candidate => candidate.Url)),
|
||||
HasWriteFileRedirection = shell.HasWriteFileRedirection,
|
||||
},
|
||||
PermissionRequestWrite write => new PermissionDetailDto
|
||||
{
|
||||
Kind = WritePermissionKind,
|
||||
Intention = NormalizeOptionalString(write.Intention),
|
||||
FileName = NormalizeOptionalString(write.FileName),
|
||||
Diff = NormalizeOptionalString(write.Diff),
|
||||
NewFileContents = NormalizeOptionalString(write.NewFileContents),
|
||||
},
|
||||
PermissionRequestRead read => new PermissionDetailDto
|
||||
{
|
||||
Kind = ReadPermissionKind,
|
||||
Intention = NormalizeOptionalString(read.Intention),
|
||||
Path = NormalizeOptionalString(read.Path),
|
||||
},
|
||||
PermissionRequestMcp mcp => new PermissionDetailDto
|
||||
{
|
||||
Kind = McpPermissionKind,
|
||||
ServerName = NormalizeOptionalString(mcp.ServerName),
|
||||
ToolTitle = NormalizeOptionalString(mcp.ToolTitle),
|
||||
Args = mcp.Args,
|
||||
ReadOnly = mcp.ReadOnly,
|
||||
},
|
||||
PermissionRequestUrl url => new PermissionDetailDto
|
||||
{
|
||||
Kind = UrlPermissionKind,
|
||||
Intention = NormalizeOptionalString(url.Intention),
|
||||
Url = NormalizeOptionalString(url.Url),
|
||||
},
|
||||
PermissionRequestMemory memory => new PermissionDetailDto
|
||||
{
|
||||
Kind = MemoryPermissionKind,
|
||||
Subject = NormalizeOptionalString(memory.Subject),
|
||||
Fact = NormalizeOptionalString(memory.Fact),
|
||||
Citations = NormalizeOptionalString(memory.Citations),
|
||||
},
|
||||
PermissionRequestCustomTool customTool => new PermissionDetailDto
|
||||
{
|
||||
Kind = CustomToolPermissionKind,
|
||||
ToolDescription = NormalizeOptionalString(customTool.ToolDescription),
|
||||
Args = customTool.Args,
|
||||
},
|
||||
PermissionRequestHook hook => new PermissionDetailDto
|
||||
{
|
||||
Kind = HookPermissionKind,
|
||||
Args = hook.ToolArgs,
|
||||
HookMessage = NormalizeOptionalString(hook.HookMessage),
|
||||
},
|
||||
_ => new PermissionDetailDto
|
||||
{
|
||||
Kind = NormalizeOptionalString(request.Kind) ?? "unknown",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
internal static bool RequiresToolCallApproval(
|
||||
ApprovalPolicyDto? approvalPolicy,
|
||||
string agentId,
|
||||
string? toolName)
|
||||
string? toolName,
|
||||
string? autoApprovedToolName = null,
|
||||
string? mcpServerApprovalKey = null)
|
||||
{
|
||||
if (approvalPolicy?.Rules is null || approvalPolicy.Rules.Count == 0)
|
||||
{
|
||||
@@ -149,9 +311,14 @@ internal sealed class CopilotApprovalCoordinator
|
||||
return false;
|
||||
}
|
||||
|
||||
return string.IsNullOrWhiteSpace(toolName)
|
||||
|| !approvalPolicy.AutoApprovedToolNames.Any(candidate =>
|
||||
string.Equals(candidate, toolName, StringComparison.OrdinalIgnoreCase));
|
||||
IReadOnlyList<string> autoApprovedToolNames = approvalPolicy.AutoApprovedToolNames;
|
||||
if (autoApprovedToolNames.Count == 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return !MatchesAutoApprovedTool(autoApprovedToolNames, toolName, autoApprovedToolName)
|
||||
&& !MatchesAutoApprovedToolName(autoApprovedToolNames, mcpServerApprovalKey);
|
||||
}
|
||||
|
||||
internal static bool TryGetApprovalToolName(
|
||||
@@ -166,6 +333,17 @@ internal sealed class CopilotApprovalCoordinator
|
||||
internal static bool TryGetApprovalToolName(PermissionRequest request, out string? toolName)
|
||||
=> TryGetApprovalToolName(request, toolNamesByCallId: null, out toolName);
|
||||
|
||||
internal void ClearRequestApprovals(string requestId)
|
||||
{
|
||||
string? normalizedRequestId = NormalizeOptionalString(requestId);
|
||||
if (normalizedRequestId is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_requestApprovedTools.TryRemove(normalizedRequestId, out _);
|
||||
}
|
||||
|
||||
private static bool HasMatchingToolCallCheckpoint(
|
||||
IReadOnlyList<ApprovalCheckpointRuleDto> rules,
|
||||
string agentId)
|
||||
@@ -188,12 +366,15 @@ internal sealed class CopilotApprovalCoordinator
|
||||
return false;
|
||||
}
|
||||
|
||||
private static PendingApprovalRequest CreatePendingApproval(RunTurnCommandDto command)
|
||||
private static PendingApprovalRequest CreatePendingApproval(
|
||||
RunTurnCommandDto command,
|
||||
string? approvalCacheKey)
|
||||
{
|
||||
return new PendingApprovalRequest(
|
||||
command.RequestId,
|
||||
command.SessionId,
|
||||
CreateApprovalRequestId(),
|
||||
NormalizeOptionalString(approvalCacheKey),
|
||||
new TaskCompletionSource<PermissionRequestResultKind>(TaskCreationOptions.RunContinuationsAsynchronously));
|
||||
}
|
||||
|
||||
@@ -214,6 +395,32 @@ internal sealed class CopilotApprovalCoordinator
|
||||
?? GetFallbackToolName(request);
|
||||
}
|
||||
|
||||
private static string? ResolveAutoApprovedToolName(PermissionRequest request)
|
||||
{
|
||||
return GetFallbackToolName(request);
|
||||
}
|
||||
|
||||
private const string McpServerApprovalPrefix = "mcp_server:";
|
||||
|
||||
private static string? ResolveMcpServerApprovalKey(PermissionRequest request)
|
||||
{
|
||||
if (request is not PermissionRequestMcp mcp)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
string? serverName = NormalizeOptionalString(mcp.ServerName);
|
||||
return serverName is not null ? $"{McpServerApprovalPrefix}{serverName}" : null;
|
||||
}
|
||||
|
||||
private static string? ResolveApprovalCacheKey(
|
||||
string? toolName,
|
||||
string? autoApprovedToolName)
|
||||
{
|
||||
return NormalizeOptionalString(autoApprovedToolName)
|
||||
?? NormalizeOptionalString(toolName);
|
||||
}
|
||||
|
||||
private static string? GetDirectToolName(PermissionRequest request)
|
||||
{
|
||||
return request switch
|
||||
@@ -265,10 +472,61 @@ internal sealed class CopilotApprovalCoordinator
|
||||
return request switch
|
||||
{
|
||||
PermissionRequestUrl => WebFetchToolName,
|
||||
PermissionRequestShell => ShellPermissionKind,
|
||||
PermissionRequestWrite => WritePermissionKind,
|
||||
PermissionRequestRead => ReadPermissionKind,
|
||||
PermissionRequestMemory => StoreMemoryToolName,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
private static bool MatchesAutoApprovedTool(
|
||||
IReadOnlyList<string> autoApprovedToolNames,
|
||||
string? toolName,
|
||||
string? autoApprovedToolName)
|
||||
{
|
||||
return MatchesAutoApprovedToolName(autoApprovedToolNames, toolName)
|
||||
|| MatchesAutoApprovedToolName(autoApprovedToolNames, autoApprovedToolName);
|
||||
}
|
||||
|
||||
private static bool MatchesAutoApprovedToolName(
|
||||
IReadOnlyList<string> autoApprovedToolNames,
|
||||
string? toolName)
|
||||
{
|
||||
string? normalizedToolName = NormalizeOptionalString(toolName);
|
||||
return normalizedToolName is not null
|
||||
&& autoApprovedToolNames.Any(candidate =>
|
||||
string.Equals(candidate, normalizedToolName, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
private bool IsToolApprovedForRequest(string requestId, string? approvalCacheKey)
|
||||
{
|
||||
string? normalizedRequestId = NormalizeOptionalString(requestId);
|
||||
string? normalizedApprovalCacheKey = NormalizeOptionalString(approvalCacheKey);
|
||||
if (normalizedRequestId is null || normalizedApprovalCacheKey is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return _requestApprovedTools.TryGetValue(normalizedRequestId, out ConcurrentDictionary<string, byte>? approvedTools)
|
||||
&& approvedTools.ContainsKey(normalizedApprovalCacheKey);
|
||||
}
|
||||
|
||||
private void CacheApprovedToolForRequest(string requestId, string? approvalCacheKey)
|
||||
{
|
||||
string? normalizedRequestId = NormalizeOptionalString(requestId);
|
||||
string? normalizedApprovalCacheKey = NormalizeOptionalString(approvalCacheKey);
|
||||
if (normalizedRequestId is null || normalizedApprovalCacheKey is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
ConcurrentDictionary<string, byte> approvedTools = _requestApprovedTools.GetOrAdd(
|
||||
normalizedRequestId,
|
||||
static _ => new ConcurrentDictionary<string, byte>(StringComparer.OrdinalIgnoreCase));
|
||||
approvedTools.TryAdd(normalizedApprovalCacheKey, 0);
|
||||
}
|
||||
|
||||
private PendingApprovalRequest GetPendingApproval(string approvalId)
|
||||
{
|
||||
if (_pendingApprovals.TryGetValue(approvalId, out PendingApprovalRequest? pending))
|
||||
@@ -307,9 +565,26 @@ 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
|
||||
.Select(NormalizeOptionalString)
|
||||
.Where(static value => value is not null)
|
||||
.Cast<string>()
|
||||
.ToList();
|
||||
|
||||
return normalized.Count > 0 ? normalized : null;
|
||||
}
|
||||
|
||||
private sealed record PendingApprovalRequest(
|
||||
string RequestId,
|
||||
string SessionId,
|
||||
string ApprovalId,
|
||||
string? ApprovalCacheKey,
|
||||
TaskCompletionSource<PermissionRequestResultKind> Decision);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Aryx.AgentHost.Contracts;
|
||||
using GitHub.Copilot.SDK;
|
||||
|
||||
namespace Aryx.AgentHost.Services;
|
||||
|
||||
internal sealed class CopilotExitPlanModeCoordinator
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, ExitPlanModeRequestedEventDto> _pendingExitPlanRequests =
|
||||
new(StringComparer.Ordinal);
|
||||
|
||||
public ExitPlanModeRequestedEventDto RecordExitPlanModeRequest(
|
||||
RunTurnCommandDto command,
|
||||
PatternAgentDefinitionDto agent,
|
||||
ExitPlanModeRequestedEvent request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(command);
|
||||
ArgumentNullException.ThrowIfNull(agent);
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
|
||||
ExitPlanModeRequestedEventDto exitPlanEvent = BuildExitPlanModeRequestedEvent(command, agent, request);
|
||||
_pendingExitPlanRequests[command.RequestId] = exitPlanEvent;
|
||||
return exitPlanEvent;
|
||||
}
|
||||
|
||||
public ExitPlanModeRequestedEventDto? ConsumePendingRequest(string turnRequestId)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(turnRequestId);
|
||||
return _pendingExitPlanRequests.TryRemove(turnRequestId, out ExitPlanModeRequestedEventDto? pending)
|
||||
? pending
|
||||
: null;
|
||||
}
|
||||
|
||||
internal static ExitPlanModeRequestedEventDto BuildExitPlanModeRequestedEvent(
|
||||
RunTurnCommandDto command,
|
||||
PatternAgentDefinitionDto agent,
|
||||
ExitPlanModeRequestedEvent request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(command);
|
||||
ArgumentNullException.ThrowIfNull(agent);
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
|
||||
ExitPlanModeRequestedData requestData = request.Data
|
||||
?? throw new InvalidOperationException("Exit plan mode request data is required.");
|
||||
|
||||
string exitPlanId = NormalizeOptionalString(requestData.RequestId)
|
||||
?? throw new InvalidOperationException("Exit plan mode request ID is required.");
|
||||
string? normalizedAgentId = NormalizeOptionalString(agent.Id);
|
||||
string? normalizedAgentName = NormalizeOptionalString(agent.Name) ?? normalizedAgentId;
|
||||
|
||||
return new ExitPlanModeRequestedEventDto
|
||||
{
|
||||
Type = "exit-plan-mode-requested",
|
||||
RequestId = command.RequestId,
|
||||
SessionId = command.SessionId,
|
||||
ExitPlanId = exitPlanId,
|
||||
AgentId = normalizedAgentId,
|
||||
AgentName = normalizedAgentName,
|
||||
Summary = NormalizeOptionalString(requestData.Summary) ?? string.Empty,
|
||||
PlanContent = NormalizeOptionalString(requestData.PlanContent) ?? string.Empty,
|
||||
Actions = NormalizeOptionalStringList(requestData.Actions ?? []),
|
||||
RecommendedAction = NormalizeOptionalString(requestData.RecommendedAction),
|
||||
};
|
||||
}
|
||||
|
||||
private static string? NormalizeOptionalString(string? value)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
}
|
||||
|
||||
private static IReadOnlyList<string>? NormalizeOptionalStringList(IEnumerable<string?> values)
|
||||
{
|
||||
List<string> normalized = values
|
||||
.Select(NormalizeOptionalString)
|
||||
.Where(static value => value is not null)
|
||||
.Cast<string>()
|
||||
.ToList();
|
||||
|
||||
return normalized.Count > 0 ? normalized : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
namespace Aryx.AgentHost.Services;
|
||||
|
||||
internal static class CopilotManagedSessionIds
|
||||
{
|
||||
private const string Prefix = "aryx::";
|
||||
private const string Separator = "::";
|
||||
|
||||
public static string Build(string aryxSessionId, string agentId)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(aryxSessionId);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(agentId);
|
||||
|
||||
return $"{Prefix}{Uri.EscapeDataString(aryxSessionId)}{Separator}{Uri.EscapeDataString(agentId)}";
|
||||
}
|
||||
|
||||
public static bool IsManagedByAryx(string copilotSessionId)
|
||||
=> TryParse(copilotSessionId, out _, out _);
|
||||
|
||||
public static bool IsManagedByAryx(string copilotSessionId, string aryxSessionId)
|
||||
{
|
||||
return TryParse(copilotSessionId, out string? parsedSessionId, out _)
|
||||
&& string.Equals(parsedSessionId, aryxSessionId, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
public static bool TryParse(string? copilotSessionId, out string aryxSessionId, out string agentId)
|
||||
{
|
||||
aryxSessionId = string.Empty;
|
||||
agentId = string.Empty;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(copilotSessionId)
|
||||
|| !copilotSessionId.StartsWith(Prefix, StringComparison.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
string payload = copilotSessionId[Prefix.Length..];
|
||||
string[] parts = payload.Split(Separator, StringSplitOptions.None);
|
||||
if (parts.Length != 2
|
||||
|| string.IsNullOrWhiteSpace(parts[0])
|
||||
|| string.IsNullOrWhiteSpace(parts[1]))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
aryxSessionId = Uri.UnescapeDataString(parts[0]);
|
||||
agentId = Uri.UnescapeDataString(parts[1]);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
using Aryx.AgentHost.Contracts;
|
||||
using GitHub.Copilot.SDK;
|
||||
|
||||
namespace Aryx.AgentHost.Services;
|
||||
|
||||
internal sealed class CopilotMcpOAuthCoordinator
|
||||
{
|
||||
public McpOauthRequiredEventDto BuildMcpOauthRequiredEvent(
|
||||
RunTurnCommandDto command,
|
||||
PatternAgentDefinitionDto agent,
|
||||
McpOauthRequiredEvent request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(command);
|
||||
ArgumentNullException.ThrowIfNull(agent);
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
|
||||
McpOauthRequiredData requestData = request.Data
|
||||
?? throw new InvalidOperationException("MCP OAuth request data is required.");
|
||||
|
||||
string oauthRequestId = NormalizeOptionalString(requestData.RequestId)
|
||||
?? throw new InvalidOperationException("MCP OAuth request ID is required.");
|
||||
string? normalizedAgentId = NormalizeOptionalString(agent.Id);
|
||||
string? normalizedAgentName = NormalizeOptionalString(agent.Name) ?? normalizedAgentId;
|
||||
|
||||
return new McpOauthRequiredEventDto
|
||||
{
|
||||
Type = "mcp-oauth-required",
|
||||
RequestId = command.RequestId,
|
||||
SessionId = command.SessionId,
|
||||
OauthRequestId = oauthRequestId,
|
||||
AgentId = normalizedAgentId,
|
||||
AgentName = normalizedAgentName,
|
||||
ServerName = NormalizeOptionalString(requestData.ServerName) ?? string.Empty,
|
||||
ServerUrl = NormalizeOptionalString(requestData.ServerUrl) ?? string.Empty,
|
||||
StaticClientConfig = BuildStaticClientConfig(requestData.StaticClientConfig),
|
||||
};
|
||||
}
|
||||
|
||||
private static McpOauthStaticClientConfigDto? BuildStaticClientConfig(
|
||||
McpOauthRequiredDataStaticClientConfig? staticClientConfig)
|
||||
{
|
||||
if (staticClientConfig is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new McpOauthStaticClientConfigDto
|
||||
{
|
||||
ClientId = NormalizeOptionalString(staticClientConfig.ClientId) ?? string.Empty,
|
||||
PublicClient = staticClientConfig.PublicClient,
|
||||
};
|
||||
}
|
||||
|
||||
private static string? NormalizeOptionalString(string? value)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace Aryx.AgentHost.Services;
|
||||
|
||||
internal sealed record CopilotMessageOptionsMetadata(string MessageMode);
|
||||
@@ -0,0 +1,359 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Aryx.AgentHost.Contracts;
|
||||
using GitHub.Copilot.SDK;
|
||||
|
||||
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 const string HandoffToolPrefix = "handoff_to_";
|
||||
private const string ReportIntentToolName = "report_intent";
|
||||
private const string TaskCompleteToolName = "task_complete";
|
||||
private static readonly HashSet<string> AlwaysAllowedToolNames = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
AskUserToolName,
|
||||
ReportIntentToolName,
|
||||
TaskCompleteToolName,
|
||||
};
|
||||
private static readonly JsonSerializerOptions HookJsonOptions = CreateHookJsonOptions();
|
||||
|
||||
public static SessionHooks Create(
|
||||
RunTurnCommandDto command,
|
||||
PatternAgentDefinitionDto agentDefinition,
|
||||
ResolvedHookSet? configuredHooks = null,
|
||||
IHookCommandRunner? hookCommandRunner = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(command);
|
||||
ArgumentNullException.ThrowIfNull(agentDefinition);
|
||||
ResolvedHookSet hooks = configuredHooks ?? ResolvedHookSet.Empty;
|
||||
IHookCommandRunner runner = hookCommandRunner ?? HookCommandRunner.Instance;
|
||||
|
||||
return new SessionHooks
|
||||
{
|
||||
OnPreToolUse = (input, _) => CreatePreToolUseOutputAsync(command, agentDefinition, hooks, runner, input),
|
||||
OnPostToolUse = (input, _) => RunPostToolUseHooksAsync(command, hooks, runner, input),
|
||||
OnUserPromptSubmitted = (input, _) => RunUserPromptSubmittedHooksAsync(command, hooks, runner, input),
|
||||
OnSessionStart = (input, _) => RunSessionStartHooksAsync(command, hooks, runner, input),
|
||||
OnSessionEnd = (input, _) => RunSessionEndHooksAsync(command, hooks, runner, input),
|
||||
OnErrorOccurred = (input, _) => RunErrorOccurredHooksAsync(command, hooks, runner, input),
|
||||
};
|
||||
}
|
||||
|
||||
private static async Task<PreToolUseHookOutput?> CreatePreToolUseOutputAsync(
|
||||
RunTurnCommandDto command,
|
||||
PatternAgentDefinitionDto agentDefinition,
|
||||
ResolvedHookSet configuredHooks,
|
||||
IHookCommandRunner hookCommandRunner,
|
||||
PreToolUseHookInput input)
|
||||
{
|
||||
if (configuredHooks.PreToolUse.Count > 0)
|
||||
{
|
||||
string payload = SerializeHookInput(new FilePreToolUseHookInput
|
||||
{
|
||||
Timestamp = input.Timestamp,
|
||||
Cwd = input.Cwd,
|
||||
ToolName = input.ToolName,
|
||||
ToolArgs = SerializeHookValue(input.ToolArgs),
|
||||
});
|
||||
|
||||
foreach (HookCommandDefinition hook in configuredHooks.PreToolUse)
|
||||
{
|
||||
string? hookOutput = await hookCommandRunner.RunAsync(
|
||||
hook,
|
||||
payload,
|
||||
command.ProjectPath,
|
||||
CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
PreToolUseHookOutput? decision = ParsePreToolUseDecision(hookOutput);
|
||||
if (string.Equals(decision?.PermissionDecision, DenyDecision, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return decision;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return CreateApprovalPolicyOutput(command, agentDefinition, input);
|
||||
}
|
||||
|
||||
private static async Task<PostToolUseHookOutput?> RunPostToolUseHooksAsync(
|
||||
RunTurnCommandDto command,
|
||||
ResolvedHookSet configuredHooks,
|
||||
IHookCommandRunner hookCommandRunner,
|
||||
PostToolUseHookInput input)
|
||||
{
|
||||
await RunConfiguredHooksAsync(
|
||||
configuredHooks.PostToolUse,
|
||||
hookCommandRunner,
|
||||
command.ProjectPath,
|
||||
SerializeHookInput(new FilePostToolUseHookInput
|
||||
{
|
||||
Timestamp = input.Timestamp,
|
||||
Cwd = input.Cwd,
|
||||
ToolName = input.ToolName,
|
||||
ToolArgs = SerializeHookValue(input.ToolArgs),
|
||||
ToolResult = input.ToolResult,
|
||||
}))
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static async Task<UserPromptSubmittedHookOutput?> RunUserPromptSubmittedHooksAsync(
|
||||
RunTurnCommandDto command,
|
||||
ResolvedHookSet configuredHooks,
|
||||
IHookCommandRunner hookCommandRunner,
|
||||
UserPromptSubmittedHookInput input)
|
||||
{
|
||||
await RunConfiguredHooksAsync(
|
||||
configuredHooks.UserPromptSubmitted,
|
||||
hookCommandRunner,
|
||||
command.ProjectPath,
|
||||
SerializeHookInput(new FileUserPromptSubmittedHookInput
|
||||
{
|
||||
Timestamp = input.Timestamp,
|
||||
Cwd = input.Cwd,
|
||||
Prompt = input.Prompt,
|
||||
}))
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static async Task<SessionStartHookOutput?> RunSessionStartHooksAsync(
|
||||
RunTurnCommandDto command,
|
||||
ResolvedHookSet configuredHooks,
|
||||
IHookCommandRunner hookCommandRunner,
|
||||
SessionStartHookInput input)
|
||||
{
|
||||
await RunConfiguredHooksAsync(
|
||||
configuredHooks.SessionStart,
|
||||
hookCommandRunner,
|
||||
command.ProjectPath,
|
||||
SerializeHookInput(new FileSessionStartHookInput
|
||||
{
|
||||
Timestamp = input.Timestamp,
|
||||
Cwd = input.Cwd,
|
||||
Source = input.Source,
|
||||
InitialPrompt = input.InitialPrompt,
|
||||
}))
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static async Task<SessionEndHookOutput?> RunSessionEndHooksAsync(
|
||||
RunTurnCommandDto command,
|
||||
ResolvedHookSet configuredHooks,
|
||||
IHookCommandRunner hookCommandRunner,
|
||||
SessionEndHookInput input)
|
||||
{
|
||||
await RunConfiguredHooksAsync(
|
||||
configuredHooks.SessionEnd,
|
||||
hookCommandRunner,
|
||||
command.ProjectPath,
|
||||
SerializeHookInput(new FileSessionEndHookInput
|
||||
{
|
||||
Timestamp = input.Timestamp,
|
||||
Cwd = input.Cwd,
|
||||
Reason = input.Reason,
|
||||
FinalMessage = input.FinalMessage,
|
||||
Error = input.Error,
|
||||
}))
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static async Task<ErrorOccurredHookOutput?> RunErrorOccurredHooksAsync(
|
||||
RunTurnCommandDto command,
|
||||
ResolvedHookSet configuredHooks,
|
||||
IHookCommandRunner hookCommandRunner,
|
||||
ErrorOccurredHookInput input)
|
||||
{
|
||||
await RunConfiguredHooksAsync(
|
||||
configuredHooks.ErrorOccurred,
|
||||
hookCommandRunner,
|
||||
command.ProjectPath,
|
||||
SerializeHookInput(new FileErrorOccurredHookInput
|
||||
{
|
||||
Timestamp = input.Timestamp,
|
||||
Cwd = input.Cwd,
|
||||
Error = new FileHookError
|
||||
{
|
||||
Message = input.Error,
|
||||
Context = input.ErrorContext,
|
||||
Recoverable = input.Recoverable,
|
||||
},
|
||||
}))
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static async Task RunConfiguredHooksAsync(
|
||||
IReadOnlyList<HookCommandDefinition> hooks,
|
||||
IHookCommandRunner hookCommandRunner,
|
||||
string projectPath,
|
||||
string payload)
|
||||
{
|
||||
if (hooks.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (HookCommandDefinition hook in hooks)
|
||||
{
|
||||
await hookCommandRunner.RunAsync(
|
||||
hook,
|
||||
payload,
|
||||
projectPath,
|
||||
CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static PreToolUseHookOutput CreateApprovalPolicyOutput(
|
||||
RunTurnCommandDto command,
|
||||
PatternAgentDefinitionDto agentDefinition,
|
||||
PreToolUseHookInput input)
|
||||
{
|
||||
string? toolName = Normalize(input.ToolName);
|
||||
if (IsAlwaysAllowedTool(toolName))
|
||||
{
|
||||
return new PreToolUseHookOutput
|
||||
{
|
||||
PermissionDecision = AllowDecision,
|
||||
};
|
||||
}
|
||||
|
||||
bool requiresApproval = CopilotApprovalCoordinator.RequiresToolCallApproval(
|
||||
command.Pattern.ApprovalPolicy,
|
||||
agentDefinition.Id,
|
||||
toolName,
|
||||
toolName);
|
||||
|
||||
return new PreToolUseHookOutput
|
||||
{
|
||||
PermissionDecision = requiresApproval ? AskDecision : AllowDecision,
|
||||
};
|
||||
}
|
||||
|
||||
private static PreToolUseHookOutput? ParsePreToolUseDecision(string? hookOutput)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(hookOutput))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
FilePreToolUseHookOutput? parsed = JsonSerializer.Deserialize<FilePreToolUseHookOutput>(hookOutput, HookJsonOptions);
|
||||
if (!string.Equals(parsed?.PermissionDecision, DenyDecision, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new PreToolUseHookOutput
|
||||
{
|
||||
PermissionDecision = DenyDecision,
|
||||
PermissionDecisionReason = Normalize(parsed?.PermissionDecisionReason),
|
||||
};
|
||||
}
|
||||
catch (JsonException exception)
|
||||
{
|
||||
Console.Error.WriteLine($"[aryx hooks] Ignoring invalid preToolUse hook output: {exception.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string SerializeHookInput<T>(T input)
|
||||
=> JsonSerializer.Serialize(input, HookJsonOptions);
|
||||
|
||||
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();
|
||||
|
||||
private sealed class FileSessionStartHookInput
|
||||
{
|
||||
public long Timestamp { get; init; }
|
||||
public string Cwd { get; init; } = string.Empty;
|
||||
public string Source { get; init; } = string.Empty;
|
||||
public string? InitialPrompt { get; init; }
|
||||
}
|
||||
|
||||
private sealed class FileSessionEndHookInput
|
||||
{
|
||||
public long Timestamp { get; init; }
|
||||
public string Cwd { get; init; } = string.Empty;
|
||||
public string Reason { get; init; } = string.Empty;
|
||||
public string? FinalMessage { get; init; }
|
||||
public string? Error { get; init; }
|
||||
}
|
||||
|
||||
private sealed class FileUserPromptSubmittedHookInput
|
||||
{
|
||||
public long Timestamp { get; init; }
|
||||
public string Cwd { get; init; } = string.Empty;
|
||||
public string Prompt { get; init; } = string.Empty;
|
||||
}
|
||||
|
||||
private sealed class FilePreToolUseHookInput
|
||||
{
|
||||
public long Timestamp { get; init; }
|
||||
public string Cwd { get; init; } = string.Empty;
|
||||
public string ToolName { get; init; } = string.Empty;
|
||||
public string ToolArgs { get; init; } = "null";
|
||||
}
|
||||
|
||||
private sealed class FilePostToolUseHookInput
|
||||
{
|
||||
public long Timestamp { get; init; }
|
||||
public string Cwd { get; init; } = string.Empty;
|
||||
public string ToolName { get; init; } = string.Empty;
|
||||
public string ToolArgs { get; init; } = "null";
|
||||
public object? ToolResult { get; init; }
|
||||
}
|
||||
|
||||
private sealed class FileErrorOccurredHookInput
|
||||
{
|
||||
public long Timestamp { get; init; }
|
||||
public string Cwd { get; init; } = string.Empty;
|
||||
public FileHookError Error { get; init; } = new();
|
||||
}
|
||||
|
||||
private sealed class FileHookError
|
||||
{
|
||||
public string Message { get; init; } = string.Empty;
|
||||
public string Context { get; init; } = string.Empty;
|
||||
public bool Recoverable { get; init; }
|
||||
}
|
||||
|
||||
private sealed class FilePreToolUseHookOutput
|
||||
{
|
||||
public string? PermissionDecision { get; init; }
|
||||
public string? PermissionDecisionReason { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
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)
|
||||
{
|
||||
await using CopilotClient client = await CreateStartedClientAsync(cancellationToken).ConfigureAwait(false);
|
||||
List<SessionMetadata> sessions = await client.ListSessionsAsync(CreateFilter(filter), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return sessions
|
||||
.Select(MapSession)
|
||||
.OrderByDescending(session => session.ModifiedTime, StringComparer.Ordinal)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<CopilotSessionInfoDto>> DeleteSessionsAsync(
|
||||
string? aryxSessionId,
|
||||
string? copilotSessionId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
string? normalizedAryxSessionId = Normalize(aryxSessionId);
|
||||
string? normalizedCopilotSessionId = Normalize(copilotSessionId);
|
||||
if (normalizedAryxSessionId is null && normalizedCopilotSessionId is null)
|
||||
{
|
||||
throw new InvalidOperationException("delete-session requires a sessionId or copilotSessionId.");
|
||||
}
|
||||
|
||||
await using CopilotClient client = await CreateStartedClientAsync(cancellationToken).ConfigureAwait(false);
|
||||
List<SessionMetadata> sessions = await client.ListSessionsAsync(null, cancellationToken).ConfigureAwait(false);
|
||||
List<CopilotSessionInfoDto> targets = sessions
|
||||
.Select(MapSession)
|
||||
.Where(session =>
|
||||
(normalizedCopilotSessionId is not null
|
||||
&& string.Equals(session.CopilotSessionId, normalizedCopilotSessionId, StringComparison.Ordinal))
|
||||
|| (normalizedAryxSessionId is not null
|
||||
&& string.Equals(session.SessionId, normalizedAryxSessionId, StringComparison.Ordinal)
|
||||
&& session.ManagedByAryx))
|
||||
.ToList();
|
||||
|
||||
if (targets.Count == 0 && normalizedCopilotSessionId is not null)
|
||||
{
|
||||
targets.Add(CreateUnknownSessionInfo(normalizedCopilotSessionId));
|
||||
}
|
||||
|
||||
foreach (CopilotSessionInfoDto target in targets)
|
||||
{
|
||||
await client.DeleteSessionAsync(target.CopilotSessionId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return targets;
|
||||
}
|
||||
|
||||
private static async Task<CopilotClient> CreateStartedClientAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
CopilotClient client = new(CopilotCliPathResolver.CreateClientOptions());
|
||||
await client.StartAsync(cancellationToken).ConfigureAwait(false);
|
||||
return client;
|
||||
}
|
||||
|
||||
private static SessionListFilter? CreateFilter(CopilotSessionListFilterDto? filter)
|
||||
{
|
||||
if (filter is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new SessionListFilter
|
||||
{
|
||||
Cwd = Normalize(filter.Cwd),
|
||||
GitRoot = Normalize(filter.GitRoot),
|
||||
Repository = Normalize(filter.Repository),
|
||||
Branch = Normalize(filter.Branch),
|
||||
};
|
||||
}
|
||||
|
||||
private static CopilotSessionInfoDto MapSession(SessionMetadata session)
|
||||
{
|
||||
bool managedByAryx = CopilotManagedSessionIds.TryParse(
|
||||
session.SessionId,
|
||||
out string aryxSessionId,
|
||||
out string agentId);
|
||||
|
||||
return new CopilotSessionInfoDto
|
||||
{
|
||||
CopilotSessionId = session.SessionId,
|
||||
ManagedByAryx = managedByAryx,
|
||||
SessionId = managedByAryx ? aryxSessionId : null,
|
||||
AgentId = managedByAryx ? agentId : null,
|
||||
StartTime = session.StartTime.ToUniversalTime().ToString("O"),
|
||||
ModifiedTime = session.ModifiedTime.ToUniversalTime().ToString("O"),
|
||||
Summary = Normalize(session.Summary),
|
||||
IsRemote = session.IsRemote,
|
||||
Cwd = Normalize(session.Context?.Cwd),
|
||||
GitRoot = Normalize(session.Context?.GitRoot),
|
||||
Repository = Normalize(session.Context?.Repository),
|
||||
Branch = Normalize(session.Context?.Branch),
|
||||
};
|
||||
}
|
||||
|
||||
private static CopilotSessionInfoDto CreateUnknownSessionInfo(string copilotSessionId)
|
||||
{
|
||||
bool managedByAryx = CopilotManagedSessionIds.TryParse(
|
||||
copilotSessionId,
|
||||
out string aryxSessionId,
|
||||
out string agentId);
|
||||
|
||||
return new CopilotSessionInfoDto
|
||||
{
|
||||
CopilotSessionId = copilotSessionId,
|
||||
ManagedByAryx = managedByAryx,
|
||||
SessionId = managedByAryx ? aryxSessionId : null,
|
||||
AgentId = managedByAryx ? agentId : null,
|
||||
};
|
||||
}
|
||||
|
||||
private static string? Normalize(string? value)
|
||||
=> string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ internal sealed class CopilotTurnExecutionState
|
||||
{
|
||||
private readonly RunTurnCommandDto _command;
|
||||
private readonly HashSet<string> _startedAgents = new(StringComparer.OrdinalIgnoreCase);
|
||||
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;
|
||||
@@ -24,31 +26,36 @@ internal sealed class CopilotTurnExecutionState
|
||||
|
||||
public List<ChatMessageDto> CompletedMessages { get; private set; } = [];
|
||||
|
||||
public bool HasPendingExitPlanModeRequest { get; private set; }
|
||||
|
||||
public bool SuppressHookLifecycleEvents { get; set; }
|
||||
|
||||
public async Task EmitThinkingIfNeeded(
|
||||
AgentIdentity agent,
|
||||
Func<AgentActivityEventDto, Task> onActivity)
|
||||
Func<SidecarEventDto, Task> onEvent)
|
||||
{
|
||||
ActiveAgent = agent;
|
||||
|
||||
if (!_startedAgents.Add(agent.AgentId))
|
||||
AgentActivityEventDto? thinkingActivity = CreateThinkingActivityIfNeeded(agent);
|
||||
if (thinkingActivity is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await onActivity(new AgentActivityEventDto
|
||||
{
|
||||
Type = "agent-activity",
|
||||
RequestId = _command.RequestId,
|
||||
SessionId = _command.SessionId,
|
||||
ActivityType = "thinking",
|
||||
AgentId = agent.AgentId,
|
||||
AgentName = agent.AgentName,
|
||||
}).ConfigureAwait(false);
|
||||
await onEvent(thinkingActivity).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public void ApplyActivity(AgentActivityEventDto activity)
|
||||
public void QueueThinkingIfNeeded(AgentIdentity agent)
|
||||
{
|
||||
if (string.Equals(activity.ActivityType, "handoff", StringComparison.Ordinal)
|
||||
AgentActivityEventDto? thinkingActivity = CreateThinkingActivityIfNeeded(agent);
|
||||
if (thinkingActivity is not null)
|
||||
{
|
||||
_pendingEvents.Enqueue(thinkingActivity);
|
||||
}
|
||||
}
|
||||
|
||||
public void ApplyEvent(SidecarEventDto evt)
|
||||
{
|
||||
if (evt is AgentActivityEventDto activity
|
||||
&& string.Equals(activity.ActivityType, "handoff", StringComparison.Ordinal)
|
||||
&& !string.IsNullOrWhiteSpace(activity.AgentId)
|
||||
&& !string.IsNullOrWhiteSpace(activity.AgentName))
|
||||
{
|
||||
@@ -67,16 +74,117 @@ internal sealed class CopilotTurnExecutionState
|
||||
{
|
||||
case AssistantMessageDeltaEvent messageDelta when !string.IsNullOrWhiteSpace(messageDelta.Data?.MessageId):
|
||||
RecordObservedAgentForMessage(agent, messageDelta.Data!.MessageId);
|
||||
QueueThinkingIfNeeded(agent);
|
||||
break;
|
||||
case AssistantMessageEvent assistantMessage when !string.IsNullOrWhiteSpace(assistantMessage.Data?.MessageId):
|
||||
RecordObservedAgentForMessage(agent, assistantMessage.Data!.MessageId);
|
||||
QueueThinkingIfNeeded(agent);
|
||||
break;
|
||||
case ToolExecutionStartEvent toolExecutionStart
|
||||
when !string.IsNullOrWhiteSpace(toolExecutionStart.Data?.ToolCallId)
|
||||
&& !string.IsNullOrWhiteSpace(toolExecutionStart.Data?.ToolName):
|
||||
ToolNamesByCallId[toolExecutionStart.Data.ToolCallId.Trim()] = toolExecutionStart.Data.ToolName.Trim();
|
||||
break;
|
||||
case AssistantReasoningDeltaEvent:
|
||||
ActiveAgent = agent;
|
||||
QueueThinkingIfNeeded(agent);
|
||||
break;
|
||||
case SubagentStartedEvent started:
|
||||
ActiveAgent = agent;
|
||||
_pendingEvents.Enqueue(CreateSubagentEvent(agent, "started", started.Data));
|
||||
break;
|
||||
case SubagentCompletedEvent completed:
|
||||
ActiveAgent = agent;
|
||||
_pendingEvents.Enqueue(CreateSubagentCompletedEvent(agent, completed.Data));
|
||||
break;
|
||||
case SubagentFailedEvent failed:
|
||||
ActiveAgent = agent;
|
||||
_pendingEvents.Enqueue(CreateSubagentFailedEvent(agent, failed.Data));
|
||||
break;
|
||||
case SubagentSelectedEvent selected:
|
||||
ActiveAgent = agent;
|
||||
_pendingEvents.Enqueue(CreateSubagentSelectedEvent(agent, selected.Data));
|
||||
break;
|
||||
case SubagentDeselectedEvent:
|
||||
ActiveAgent = agent;
|
||||
_pendingEvents.Enqueue(CreateSubagentDeselectedEvent(agent));
|
||||
break;
|
||||
case SkillInvokedEvent skillInvoked:
|
||||
ActiveAgent = agent;
|
||||
_pendingEvents.Enqueue(CreateSkillInvokedEvent(agent, skillInvoked.Data));
|
||||
break;
|
||||
case HookStartEvent hookStart:
|
||||
ActiveAgent = agent;
|
||||
if (!SuppressHookLifecycleEvents)
|
||||
{
|
||||
_pendingEvents.Enqueue(CreateHookLifecycleEvent(agent, "start", hookStart.Data));
|
||||
}
|
||||
break;
|
||||
case HookEndEvent hookEnd:
|
||||
ActiveAgent = agent;
|
||||
if (!SuppressHookLifecycleEvents)
|
||||
{
|
||||
_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));
|
||||
break;
|
||||
case SessionCompactionStartEvent compactionStart:
|
||||
ActiveAgent = agent;
|
||||
_pendingEvents.Enqueue(CreateCompactionStartEvent(agent, compactionStart.Data));
|
||||
break;
|
||||
case SessionCompactionCompleteEvent compactionComplete:
|
||||
ActiveAgent = agent;
|
||||
_pendingEvents.Enqueue(CreateCompactionCompleteEvent(agent, compactionComplete.Data));
|
||||
break;
|
||||
case PendingMessagesModifiedEvent:
|
||||
ActiveAgent = agent;
|
||||
_pendingEvents.Enqueue(CreatePendingMessagesModifiedEvent(agent));
|
||||
break;
|
||||
case McpOauthRequiredEvent:
|
||||
ActiveAgent = agent;
|
||||
break;
|
||||
case ExitPlanModeRequestedEvent:
|
||||
HasPendingExitPlanModeRequest = true;
|
||||
ActiveAgent = agent;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<SidecarEventDto> DrainPendingEvents()
|
||||
{
|
||||
List<SidecarEventDto> pending = [];
|
||||
while (_pendingEvents.TryDequeue(out SidecarEventDto? pendingEvent))
|
||||
{
|
||||
pending.Add(pendingEvent);
|
||||
}
|
||||
|
||||
return pending;
|
||||
}
|
||||
|
||||
public void EnqueuePendingMcpOauthRequest(McpOauthRequiredEventDto request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
_pendingMcpOauthRequests.Enqueue(request);
|
||||
}
|
||||
|
||||
public IReadOnlyList<McpOauthRequiredEventDto> DrainPendingMcpOauthRequests()
|
||||
{
|
||||
List<McpOauthRequiredEventDto> pending = [];
|
||||
while (_pendingMcpOauthRequests.TryDequeue(out McpOauthRequiredEventDto? request))
|
||||
{
|
||||
pending.Add(request);
|
||||
}
|
||||
|
||||
return pending;
|
||||
}
|
||||
|
||||
public bool TryResolveObservedAgentForMessage(string? messageId, out AgentIdentity agent)
|
||||
{
|
||||
agent = default;
|
||||
@@ -112,6 +220,26 @@ internal sealed class CopilotTurnExecutionState
|
||||
_observedAgentsByMessageId[messageId] = agent;
|
||||
}
|
||||
|
||||
private AgentActivityEventDto? CreateThinkingActivityIfNeeded(AgentIdentity agent)
|
||||
{
|
||||
ActiveAgent = agent;
|
||||
|
||||
if (!_startedAgents.Add(agent.AgentId))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new AgentActivityEventDto
|
||||
{
|
||||
Type = "agent-activity",
|
||||
RequestId = _command.RequestId,
|
||||
SessionId = _command.SessionId,
|
||||
ActivityType = "thinking",
|
||||
AgentId = agent.AgentId,
|
||||
AgentName = agent.AgentName,
|
||||
};
|
||||
}
|
||||
|
||||
public void UpdateCompletedMessages(
|
||||
IReadOnlyList<ChatMessage> allMessages,
|
||||
IReadOnlyList<ChatMessage> inputMessages)
|
||||
@@ -137,4 +265,252 @@ internal sealed class CopilotTurnExecutionState
|
||||
|
||||
return CompletedMessages;
|
||||
}
|
||||
|
||||
private SubagentEventDto CreateSubagentEvent(
|
||||
AgentIdentity agent,
|
||||
string eventKind,
|
||||
SubagentStartedData? data)
|
||||
{
|
||||
return new SubagentEventDto
|
||||
{
|
||||
Type = "subagent-event",
|
||||
RequestId = _command.RequestId,
|
||||
SessionId = _command.SessionId,
|
||||
EventKind = eventKind,
|
||||
AgentId = agent.AgentId,
|
||||
AgentName = agent.AgentName,
|
||||
ToolCallId = data?.ToolCallId,
|
||||
CustomAgentName = data?.AgentName,
|
||||
CustomAgentDisplayName = data?.AgentDisplayName,
|
||||
CustomAgentDescription = data?.AgentDescription,
|
||||
};
|
||||
}
|
||||
|
||||
private SubagentEventDto CreateSubagentCompletedEvent(
|
||||
AgentIdentity agent,
|
||||
SubagentCompletedData? data)
|
||||
{
|
||||
return new SubagentEventDto
|
||||
{
|
||||
Type = "subagent-event",
|
||||
RequestId = _command.RequestId,
|
||||
SessionId = _command.SessionId,
|
||||
EventKind = "completed",
|
||||
AgentId = agent.AgentId,
|
||||
AgentName = agent.AgentName,
|
||||
ToolCallId = data?.ToolCallId,
|
||||
CustomAgentName = data?.AgentName,
|
||||
CustomAgentDisplayName = data?.AgentDisplayName,
|
||||
};
|
||||
}
|
||||
|
||||
private SubagentEventDto CreateSubagentFailedEvent(
|
||||
AgentIdentity agent,
|
||||
SubagentFailedData? data)
|
||||
{
|
||||
return new SubagentEventDto
|
||||
{
|
||||
Type = "subagent-event",
|
||||
RequestId = _command.RequestId,
|
||||
SessionId = _command.SessionId,
|
||||
EventKind = "failed",
|
||||
AgentId = agent.AgentId,
|
||||
AgentName = agent.AgentName,
|
||||
ToolCallId = data?.ToolCallId,
|
||||
CustomAgentName = data?.AgentName,
|
||||
CustomAgentDisplayName = data?.AgentDisplayName,
|
||||
Error = data?.Error,
|
||||
};
|
||||
}
|
||||
|
||||
private SubagentEventDto CreateSubagentSelectedEvent(
|
||||
AgentIdentity agent,
|
||||
SubagentSelectedData? data)
|
||||
{
|
||||
return new SubagentEventDto
|
||||
{
|
||||
Type = "subagent-event",
|
||||
RequestId = _command.RequestId,
|
||||
SessionId = _command.SessionId,
|
||||
EventKind = "selected",
|
||||
AgentId = agent.AgentId,
|
||||
AgentName = agent.AgentName,
|
||||
CustomAgentName = data?.AgentName,
|
||||
CustomAgentDisplayName = data?.AgentDisplayName,
|
||||
Tools = data?.Tools,
|
||||
};
|
||||
}
|
||||
|
||||
private SubagentEventDto CreateSubagentDeselectedEvent(AgentIdentity agent)
|
||||
{
|
||||
return new SubagentEventDto
|
||||
{
|
||||
Type = "subagent-event",
|
||||
RequestId = _command.RequestId,
|
||||
SessionId = _command.SessionId,
|
||||
EventKind = "deselected",
|
||||
AgentId = agent.AgentId,
|
||||
AgentName = agent.AgentName,
|
||||
};
|
||||
}
|
||||
|
||||
private SkillInvokedEventDto CreateSkillInvokedEvent(
|
||||
AgentIdentity agent,
|
||||
SkillInvokedData? data)
|
||||
{
|
||||
return new SkillInvokedEventDto
|
||||
{
|
||||
Type = "skill-invoked",
|
||||
RequestId = _command.RequestId,
|
||||
SessionId = _command.SessionId,
|
||||
AgentId = agent.AgentId,
|
||||
AgentName = agent.AgentName,
|
||||
SkillName = data?.Name ?? string.Empty,
|
||||
Path = data?.Path ?? string.Empty,
|
||||
Content = data?.Content ?? string.Empty,
|
||||
AllowedTools = data?.AllowedTools,
|
||||
PluginName = data?.PluginName,
|
||||
PluginVersion = data?.PluginVersion,
|
||||
};
|
||||
}
|
||||
|
||||
private HookLifecycleEventDto CreateHookLifecycleEvent(
|
||||
AgentIdentity agent,
|
||||
string phase,
|
||||
HookStartData? data)
|
||||
{
|
||||
return new HookLifecycleEventDto
|
||||
{
|
||||
Type = "hook-lifecycle",
|
||||
RequestId = _command.RequestId,
|
||||
SessionId = _command.SessionId,
|
||||
AgentId = agent.AgentId,
|
||||
AgentName = agent.AgentName,
|
||||
HookInvocationId = data?.HookInvocationId ?? string.Empty,
|
||||
HookType = data?.HookType ?? string.Empty,
|
||||
Phase = phase,
|
||||
Input = data?.Input,
|
||||
};
|
||||
}
|
||||
|
||||
private HookLifecycleEventDto CreateHookLifecycleEvent(
|
||||
AgentIdentity agent,
|
||||
string phase,
|
||||
HookEndData? data)
|
||||
{
|
||||
return new HookLifecycleEventDto
|
||||
{
|
||||
Type = "hook-lifecycle",
|
||||
RequestId = _command.RequestId,
|
||||
SessionId = _command.SessionId,
|
||||
AgentId = agent.AgentId,
|
||||
AgentName = agent.AgentName,
|
||||
HookInvocationId = data?.HookInvocationId ?? string.Empty,
|
||||
HookType = data?.HookType ?? string.Empty,
|
||||
Phase = phase,
|
||||
Success = data?.Success,
|
||||
Output = data?.Output,
|
||||
Error = data?.Error?.Message,
|
||||
};
|
||||
}
|
||||
|
||||
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
|
||||
{
|
||||
Type = "session-usage",
|
||||
RequestId = _command.RequestId,
|
||||
SessionId = _command.SessionId,
|
||||
AgentId = agent.AgentId,
|
||||
AgentName = agent.AgentName,
|
||||
TokenLimit = data?.TokenLimit ?? 0,
|
||||
CurrentTokens = data?.CurrentTokens ?? 0,
|
||||
MessagesLength = data?.MessagesLength ?? 0,
|
||||
SystemTokens = data?.SystemTokens,
|
||||
ConversationTokens = data?.ConversationTokens,
|
||||
ToolDefinitionsTokens = data?.ToolDefinitionsTokens,
|
||||
IsInitial = data?.IsInitial,
|
||||
};
|
||||
}
|
||||
|
||||
private SessionCompactionEventDto CreateCompactionStartEvent(
|
||||
AgentIdentity agent,
|
||||
SessionCompactionStartData? data)
|
||||
{
|
||||
return new SessionCompactionEventDto
|
||||
{
|
||||
Type = "session-compaction",
|
||||
RequestId = _command.RequestId,
|
||||
SessionId = _command.SessionId,
|
||||
AgentId = agent.AgentId,
|
||||
AgentName = agent.AgentName,
|
||||
Phase = "start",
|
||||
SystemTokens = data?.SystemTokens,
|
||||
ConversationTokens = data?.ConversationTokens,
|
||||
ToolDefinitionsTokens = data?.ToolDefinitionsTokens,
|
||||
};
|
||||
}
|
||||
|
||||
private SessionCompactionEventDto CreateCompactionCompleteEvent(
|
||||
AgentIdentity agent,
|
||||
SessionCompactionCompleteData? data)
|
||||
{
|
||||
return new SessionCompactionEventDto
|
||||
{
|
||||
Type = "session-compaction",
|
||||
RequestId = _command.RequestId,
|
||||
SessionId = _command.SessionId,
|
||||
AgentId = agent.AgentId,
|
||||
AgentName = agent.AgentName,
|
||||
Phase = "complete",
|
||||
Success = data?.Success,
|
||||
Error = data?.Error,
|
||||
SystemTokens = data?.SystemTokens,
|
||||
ConversationTokens = data?.ConversationTokens,
|
||||
ToolDefinitionsTokens = data?.ToolDefinitionsTokens,
|
||||
PreCompactionTokens = data?.PreCompactionTokens,
|
||||
PostCompactionTokens = data?.PostCompactionTokens,
|
||||
PreCompactionMessagesLength = data?.PreCompactionMessagesLength,
|
||||
MessagesRemoved = data?.MessagesRemoved,
|
||||
TokensRemoved = data?.TokensRemoved,
|
||||
SummaryContent = data?.SummaryContent,
|
||||
CheckpointNumber = data?.CheckpointNumber,
|
||||
CheckpointPath = data?.CheckpointPath,
|
||||
};
|
||||
}
|
||||
|
||||
private PendingMessagesModifiedEventDto CreatePendingMessagesModifiedEvent(AgentIdentity agent)
|
||||
{
|
||||
return new PendingMessagesModifiedEventDto
|
||||
{
|
||||
Type = "pending-messages-modified",
|
||||
RequestId = _command.RequestId,
|
||||
SessionId = _command.SessionId,
|
||||
AgentId = agent.AgentId,
|
||||
AgentName = agent.AgentName,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Aryx.AgentHost.Contracts;
|
||||
using GitHub.Copilot.SDK;
|
||||
|
||||
namespace Aryx.AgentHost.Services;
|
||||
|
||||
internal sealed class CopilotUserInputCoordinator
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, PendingUserInputRequest> _pendingUserInputs = new(StringComparer.Ordinal);
|
||||
|
||||
public Task ResolveUserInputAsync(
|
||||
ResolveUserInputCommandDto command,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(command);
|
||||
|
||||
string userInputId = RequireUserInputId(command.UserInputId);
|
||||
PendingUserInputRequest pending = GetPendingUserInput(userInputId);
|
||||
UserInputResponse response = new()
|
||||
{
|
||||
Answer = command.Answer ?? string.Empty,
|
||||
WasFreeform = command.WasFreeform,
|
||||
};
|
||||
|
||||
if (!pending.Response.TrySetResult(response))
|
||||
{
|
||||
throw new InvalidOperationException($"User input request \"{userInputId}\" is no longer pending.");
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public async Task<UserInputResponse> RequestUserInputAsync(
|
||||
RunTurnCommandDto command,
|
||||
PatternAgentDefinitionDto agent,
|
||||
UserInputRequest request,
|
||||
UserInputInvocation invocation,
|
||||
Func<UserInputRequestedEventDto, Task> onUserInput,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(command);
|
||||
ArgumentNullException.ThrowIfNull(agent);
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
ArgumentNullException.ThrowIfNull(invocation);
|
||||
ArgumentNullException.ThrowIfNull(onUserInput);
|
||||
|
||||
PendingUserInputRequest pending = CreatePendingUserInput(command);
|
||||
if (!_pendingUserInputs.TryAdd(pending.UserInputId, pending))
|
||||
{
|
||||
throw new InvalidOperationException($"User input request \"{pending.UserInputId}\" is already pending.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await onUserInput(BuildUserInputRequestedEvent(command, agent, request, pending.UserInputId))
|
||||
.ConfigureAwait(false);
|
||||
|
||||
using CancellationTokenRegistration registration = cancellationToken.Register(
|
||||
static state =>
|
||||
{
|
||||
((TaskCompletionSource<UserInputResponse>)state!)
|
||||
.TrySetCanceled();
|
||||
},
|
||||
pending.Response);
|
||||
|
||||
return await pending.Response.Task.ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_pendingUserInputs.TryRemove(pending.UserInputId, out _);
|
||||
}
|
||||
}
|
||||
|
||||
internal static UserInputRequestedEventDto BuildUserInputRequestedEvent(
|
||||
RunTurnCommandDto command,
|
||||
PatternAgentDefinitionDto agent,
|
||||
UserInputRequest request,
|
||||
string userInputId)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(command);
|
||||
ArgumentNullException.ThrowIfNull(agent);
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
|
||||
string? normalizedAgentId = NormalizeOptionalString(agent.Id);
|
||||
string? normalizedAgentName = NormalizeOptionalString(agent.Name) ?? normalizedAgentId;
|
||||
|
||||
return new UserInputRequestedEventDto
|
||||
{
|
||||
Type = "user-input-requested",
|
||||
RequestId = command.RequestId,
|
||||
SessionId = command.SessionId,
|
||||
UserInputId = userInputId,
|
||||
AgentId = normalizedAgentId,
|
||||
AgentName = normalizedAgentName,
|
||||
Question = NormalizeOptionalString(request.Question) ?? string.Empty,
|
||||
Choices = NormalizeOptionalStringList(request.Choices ?? []),
|
||||
AllowFreeform = request.AllowFreeform,
|
||||
};
|
||||
}
|
||||
|
||||
private static PendingUserInputRequest CreatePendingUserInput(RunTurnCommandDto command)
|
||||
{
|
||||
return new PendingUserInputRequest(
|
||||
command.RequestId,
|
||||
command.SessionId,
|
||||
CreateUserInputRequestId(),
|
||||
new TaskCompletionSource<UserInputResponse>(TaskCreationOptions.RunContinuationsAsynchronously));
|
||||
}
|
||||
|
||||
private PendingUserInputRequest GetPendingUserInput(string userInputId)
|
||||
{
|
||||
if (_pendingUserInputs.TryGetValue(userInputId, out PendingUserInputRequest? pending))
|
||||
{
|
||||
return pending;
|
||||
}
|
||||
|
||||
throw new InvalidOperationException($"User input request \"{userInputId}\" is not pending.");
|
||||
}
|
||||
|
||||
private static string RequireUserInputId(string? userInputId)
|
||||
{
|
||||
string? normalizedUserInputId = NormalizeOptionalString(userInputId);
|
||||
return normalizedUserInputId
|
||||
?? throw new InvalidOperationException("User input ID is required.");
|
||||
}
|
||||
|
||||
private static string CreateUserInputRequestId()
|
||||
{
|
||||
return $"user-input-{Guid.NewGuid():N}";
|
||||
}
|
||||
|
||||
private static string? NormalizeOptionalString(string? value)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
}
|
||||
|
||||
private static IReadOnlyList<string>? NormalizeOptionalStringList(IEnumerable<string?> values)
|
||||
{
|
||||
List<string> normalized = values
|
||||
.Select(NormalizeOptionalString)
|
||||
.Where(static value => value is not null)
|
||||
.Cast<string>()
|
||||
.ToList();
|
||||
|
||||
return normalized.Count > 0 ? normalized : null;
|
||||
}
|
||||
|
||||
private sealed record PendingUserInputRequest(
|
||||
string RequestId,
|
||||
string SessionId,
|
||||
string UserInputId,
|
||||
TaskCompletionSource<UserInputResponse> Response);
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.Linq;
|
||||
using Aryx.AgentHost.Contracts;
|
||||
using GitHub.Copilot.SDK;
|
||||
using Microsoft.Agents.AI.Workflows;
|
||||
using Microsoft.Extensions.AI;
|
||||
|
||||
@@ -6,8 +8,12 @@ namespace Aryx.AgentHost.Services;
|
||||
|
||||
public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner
|
||||
{
|
||||
private const string HandoffFunctionPrefix = "handoff_to_";
|
||||
private readonly PatternValidator _patternValidator;
|
||||
private readonly CopilotApprovalCoordinator _approvalCoordinator = new();
|
||||
private readonly CopilotUserInputCoordinator _userInputCoordinator = new();
|
||||
private readonly CopilotMcpOAuthCoordinator _mcpOAuthCoordinator = new();
|
||||
private readonly CopilotExitPlanModeCoordinator _exitPlanModeCoordinator = new();
|
||||
|
||||
public CopilotWorkflowRunner(PatternValidator patternValidator)
|
||||
{
|
||||
@@ -17,8 +23,11 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner
|
||||
public async Task<IReadOnlyList<ChatMessageDto>> RunTurnAsync(
|
||||
RunTurnCommandDto command,
|
||||
Func<TurnDeltaEventDto, Task> onDelta,
|
||||
Func<AgentActivityEventDto, Task> onActivity,
|
||||
Func<SidecarEventDto, Task> onEvent,
|
||||
Func<ApprovalRequestedEventDto, Task> onApproval,
|
||||
Func<UserInputRequestedEventDto, Task> onUserInput,
|
||||
Func<McpOauthRequiredEventDto, Task> onMcpOAuthRequired,
|
||||
Func<ExitPlanModeRequestedEventDto, Task> onExitPlanMode,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
PatternValidationIssueDto? validationError = _patternValidator.Validate(command.Pattern).FirstOrDefault();
|
||||
@@ -28,35 +37,117 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner
|
||||
}
|
||||
|
||||
CopilotTurnExecutionState state = new(command);
|
||||
await using CopilotAgentBundle bundle = await CopilotAgentBundle.CreateAsync(
|
||||
command,
|
||||
(agent, request, invocation) => _approvalCoordinator.RequestApprovalAsync(
|
||||
command,
|
||||
agent,
|
||||
request,
|
||||
invocation,
|
||||
state.ToolNamesByCallId,
|
||||
onApproval,
|
||||
cancellationToken),
|
||||
(agent, sessionEvent) => state.ObserveSessionEvent(agent, sessionEvent),
|
||||
cancellationToken);
|
||||
Workflow workflow = bundle.BuildWorkflow(command.Pattern);
|
||||
List<ChatMessage> inputMessages = command.Messages.Select(WorkflowTranscriptProjector.ToChatMessage).ToList();
|
||||
using CancellationTokenSource runCancellation =
|
||||
CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
|
||||
await using StreamingRun run = await InProcessExecution.RunStreamingAsync(workflow, inputMessages).ConfigureAwait(false);
|
||||
await run.TrySendMessageAsync(new TurnToken(emitEvents: true)).ConfigureAwait(false);
|
||||
|
||||
await foreach (WorkflowEvent evt in run.WatchStreamAsync(cancellationToken).ConfigureAwait(false))
|
||||
try
|
||||
{
|
||||
bool shouldEndTurn = await HandleWorkflowEventAsync(command, evt, inputMessages, state, onDelta, onActivity)
|
||||
.ConfigureAwait(false);
|
||||
if (shouldEndTurn)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
await using CopilotAgentBundle bundle = await CopilotAgentBundle.CreateAsync(
|
||||
command,
|
||||
(agent, request, invocation) => _approvalCoordinator.RequestApprovalAsync(
|
||||
command,
|
||||
agent,
|
||||
request,
|
||||
invocation,
|
||||
state.ToolNamesByCallId,
|
||||
activity => EmitActivityAsync(command, state, activity, onEvent),
|
||||
onApproval,
|
||||
runCancellation.Token),
|
||||
(agent, request, invocation) => _userInputCoordinator.RequestUserInputAsync(
|
||||
command,
|
||||
agent,
|
||||
request,
|
||||
invocation,
|
||||
onUserInput,
|
||||
runCancellation.Token),
|
||||
(agent, sessionEvent) =>
|
||||
{
|
||||
state.ObserveSessionEvent(agent, sessionEvent);
|
||||
if (sessionEvent is McpOauthRequiredEvent mcpOauthRequired)
|
||||
{
|
||||
state.EnqueuePendingMcpOauthRequest(
|
||||
_mcpOAuthCoordinator.BuildMcpOauthRequiredEvent(command, agent, mcpOauthRequired));
|
||||
}
|
||||
|
||||
return state.FinalizeCompletedMessages();
|
||||
if (sessionEvent is ExitPlanModeRequestedEvent exitPlanModeRequested)
|
||||
{
|
||||
_exitPlanModeCoordinator.RecordExitPlanModeRequest(command, agent, exitPlanModeRequested);
|
||||
runCancellation.Cancel();
|
||||
}
|
||||
},
|
||||
runCancellation.Token);
|
||||
ConfigureHookLifecycleEventSuppression(state, bundle);
|
||||
Workflow workflow = bundle.BuildWorkflow(command.Pattern);
|
||||
List<ChatMessage> inputMessages = command.Messages.Select(WorkflowTranscriptProjector.ToChatMessage).ToList();
|
||||
WorkflowTranscriptProjector.AttachMessageMode(inputMessages, command.MessageMode);
|
||||
|
||||
await using StreamingRun run = await InProcessExecution.RunStreamingAsync(workflow, inputMessages).ConfigureAwait(false);
|
||||
await run.TrySendMessageAsync(new TurnToken(emitEvents: true)).ConfigureAwait(false);
|
||||
|
||||
await foreach (WorkflowEvent evt in run.WatchStreamAsync(runCancellation.Token).ConfigureAwait(false))
|
||||
{
|
||||
bool shouldEndTurn = await HandleWorkflowEventAsync(command, evt, inputMessages, state, onDelta, onEvent)
|
||||
.ConfigureAwait(false);
|
||||
await EmitPendingEventsAsync(state, onEvent).ConfigureAwait(false);
|
||||
await EmitPendingMcpOauthRequestsAsync(state, onMcpOAuthRequired).ConfigureAwait(false);
|
||||
if (shouldEndTurn)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
await EmitPendingEventsAsync(state, onEvent).ConfigureAwait(false);
|
||||
await EmitPendingMcpOauthRequestsAsync(state, onMcpOAuthRequired).ConfigureAwait(false);
|
||||
return state.FinalizeCompletedMessages();
|
||||
}
|
||||
catch (OperationCanceledException) when (runCancellation.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
await EmitPendingEventsAsync(state, onEvent).ConfigureAwait(false);
|
||||
await EmitPendingMcpOauthRequestsAsync(state, onMcpOAuthRequired).ConfigureAwait(false);
|
||||
ExitPlanModeRequestedEventDto? exitPlanModeEvent =
|
||||
_exitPlanModeCoordinator.ConsumePendingRequest(command.RequestId);
|
||||
if (exitPlanModeEvent is null || !state.HasPendingExitPlanModeRequest)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
|
||||
await onExitPlanMode(exitPlanModeEvent).ConfigureAwait(false);
|
||||
return state.FinalizeCompletedMessages();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_approvalCoordinator.ClearRequestApprovals(command.RequestId);
|
||||
}
|
||||
}
|
||||
|
||||
internal static void ConfigureHookLifecycleEventSuppression(
|
||||
CopilotTurnExecutionState state,
|
||||
CopilotAgentBundle bundle)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(state);
|
||||
ArgumentNullException.ThrowIfNull(bundle);
|
||||
|
||||
state.SuppressHookLifecycleEvents = !bundle.HasConfiguredHooks;
|
||||
}
|
||||
|
||||
private static async Task EmitPendingEventsAsync(
|
||||
CopilotTurnExecutionState state,
|
||||
Func<SidecarEventDto, Task> onEvent)
|
||||
{
|
||||
foreach (SidecarEventDto pendingEvent in state.DrainPendingEvents())
|
||||
{
|
||||
await onEvent(pendingEvent).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task EmitPendingMcpOauthRequestsAsync(
|
||||
CopilotTurnExecutionState state,
|
||||
Func<McpOauthRequiredEventDto, Task> onMcpOAuthRequired)
|
||||
{
|
||||
foreach (McpOauthRequiredEventDto request in state.DrainPendingMcpOauthRequests())
|
||||
{
|
||||
await onMcpOAuthRequired(request).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public Task ResolveApprovalAsync(
|
||||
@@ -66,21 +157,36 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner
|
||||
return _approvalCoordinator.ResolveApprovalAsync(command, cancellationToken);
|
||||
}
|
||||
|
||||
public Task ResolveUserInputAsync(
|
||||
ResolveUserInputCommandDto command,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return _userInputCoordinator.ResolveUserInputAsync(command, cancellationToken);
|
||||
}
|
||||
|
||||
private static async Task<bool> HandleWorkflowEventAsync(
|
||||
RunTurnCommandDto command,
|
||||
WorkflowEvent evt,
|
||||
IReadOnlyList<ChatMessage> inputMessages,
|
||||
CopilotTurnExecutionState state,
|
||||
Func<TurnDeltaEventDto, Task> onDelta,
|
||||
Func<AgentActivityEventDto, Task> onActivity)
|
||||
Func<SidecarEventDto, Task> onEvent)
|
||||
{
|
||||
if (evt is ExecutorInvokedEvent invoked
|
||||
&& AgentIdentityResolver.TryResolveKnownAgentIdentity(
|
||||
if (evt is ExecutorInvokedEvent invoked)
|
||||
{
|
||||
if (AgentIdentityResolver.TryResolveKnownAgentIdentity(
|
||||
command.Pattern,
|
||||
invoked.ExecutorId,
|
||||
out AgentIdentity invokedAgent))
|
||||
{
|
||||
await state.EmitThinkingIfNeeded(invokedAgent, onActivity).ConfigureAwait(false);
|
||||
{
|
||||
TraceHandoff(command, $"Executor invoked: {invoked.ExecutorId} -> {invokedAgent.AgentName} ({invokedAgent.AgentId}).");
|
||||
await state.EmitThinkingIfNeeded(invokedAgent, onEvent).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
TraceHandoff(command, $"Executor invoked without a known agent match: {invoked.ExecutorId}.");
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -94,28 +200,39 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner
|
||||
|
||||
if (activity is null)
|
||||
{
|
||||
return WorkflowRequestInfoInterpreter.RequiresUserInputTurnBoundary(command, requestInfo);
|
||||
bool requiresBoundary = WorkflowRequestInfoInterpreter.RequiresUserInputTurnBoundary(command, requestInfo);
|
||||
TraceHandoff(
|
||||
command,
|
||||
$"Request info produced no activity for data type '{requestInfo.Request.Data.TypeId}'. Requires boundary: {requiresBoundary}.");
|
||||
return requiresBoundary;
|
||||
}
|
||||
|
||||
state.ApplyActivity(activity);
|
||||
await onActivity(activity).ConfigureAwait(false);
|
||||
await EmitActivityAsync(command, state, activity, onEvent).ConfigureAwait(false);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (evt is AgentResponseUpdateEvent update)
|
||||
{
|
||||
await HandleAgentResponseUpdateAsync(command, update, state, onDelta, onActivity).ConfigureAwait(false);
|
||||
await HandleAgentResponseUpdateAsync(command, update, state, onDelta, onEvent).ConfigureAwait(false);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (evt is ExecutorCompletedEvent completed
|
||||
&& AgentIdentityResolver.TryResolveObservedAgentIdentity(
|
||||
if (evt is ExecutorCompletedEvent completed)
|
||||
{
|
||||
if (AgentIdentityResolver.TryResolveObservedAgentIdentity(
|
||||
command.Pattern,
|
||||
completed.ExecutorId,
|
||||
state.ActiveAgent,
|
||||
out AgentIdentity completedAgent))
|
||||
{
|
||||
state.ClearActiveAgentIfMatching(completedAgent);
|
||||
{
|
||||
TraceHandoff(command, $"Executor completed: {completed.ExecutorId} -> {completedAgent.AgentName} ({completedAgent.AgentId}).");
|
||||
state.ClearActiveAgentIfMatching(completedAgent);
|
||||
}
|
||||
else
|
||||
{
|
||||
TraceHandoff(command, $"Executor completed without a known agent match: {completed.ExecutorId}.");
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -133,10 +250,16 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner
|
||||
AgentResponseUpdateEvent update,
|
||||
CopilotTurnExecutionState state,
|
||||
Func<TurnDeltaEventDto, Task> onDelta,
|
||||
Func<AgentActivityEventDto, Task> onActivity)
|
||||
Func<SidecarEventDto, Task> onEvent)
|
||||
{
|
||||
AgentIdentity? updateAgent = null;
|
||||
string authorName = update.ExecutorId;
|
||||
string[] handoffFunctionCalls = update.Update.Contents
|
||||
.OfType<FunctionCallContent>()
|
||||
.Select(content => content.Name)
|
||||
.Where(IsHandoffFunctionName)
|
||||
.Distinct(StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
if (state.TryResolveObservedAgentForMessage(update.Update.MessageId, out AgentIdentity observedMessageAgent))
|
||||
{
|
||||
updateAgent = observedMessageAgent;
|
||||
@@ -154,7 +277,20 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner
|
||||
|
||||
if (updateAgent.HasValue)
|
||||
{
|
||||
await state.EmitThinkingIfNeeded(updateAgent.Value, onActivity).ConfigureAwait(false);
|
||||
if (handoffFunctionCalls.Length > 0)
|
||||
{
|
||||
TraceHandoff(
|
||||
command,
|
||||
$"Agent response update from {updateAgent.Value.AgentName} ({updateAgent.Value.AgentId}) requested handoff via {string.Join(", ", handoffFunctionCalls)}.");
|
||||
}
|
||||
|
||||
await state.EmitThinkingIfNeeded(updateAgent.Value, onEvent).ConfigureAwait(false);
|
||||
}
|
||||
else if (!string.IsNullOrEmpty(update.Update.Text) || handoffFunctionCalls.Length > 0)
|
||||
{
|
||||
TraceHandoff(
|
||||
command,
|
||||
$"Agent response update could not resolve agent for executor '{update.ExecutorId}' and message '{update.Update.MessageId ?? "<none>"}'.");
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(update.Update.Text))
|
||||
@@ -179,4 +315,45 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner
|
||||
Content = currentContent,
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task EmitActivityAsync(
|
||||
RunTurnCommandDto command,
|
||||
CopilotTurnExecutionState state,
|
||||
AgentActivityEventDto activity,
|
||||
Func<SidecarEventDto, Task> onEvent)
|
||||
{
|
||||
state.ApplyEvent(activity);
|
||||
TraceHandoff(
|
||||
command,
|
||||
$"Activity emitted: {activity.ActivityType} -> {activity.AgentName ?? activity.AgentId ?? "<unknown>"}.");
|
||||
await onEvent(activity).ConfigureAwait(false);
|
||||
|
||||
if (string.Equals(activity.ActivityType, "handoff", StringComparison.Ordinal)
|
||||
&& !string.IsNullOrWhiteSpace(activity.AgentId)
|
||||
&& !string.IsNullOrWhiteSpace(activity.AgentName))
|
||||
{
|
||||
TraceHandoff(
|
||||
command,
|
||||
$"Promoting handoff target to thinking: {activity.AgentName} ({activity.AgentId}).");
|
||||
await state.EmitThinkingIfNeeded(
|
||||
new AgentIdentity(activity.AgentId, activity.AgentName),
|
||||
onEvent).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsHandoffFunctionName(string? candidate)
|
||||
{
|
||||
return !string.IsNullOrWhiteSpace(candidate)
|
||||
&& candidate.StartsWith(HandoffFunctionPrefix, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static void TraceHandoff(RunTurnCommandDto command, string message)
|
||||
{
|
||||
if (!string.Equals(command.Pattern.Mode, "handoff", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Console.Error.WriteLine($"[aryx handoff] {message}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using Aryx.AgentHost.Contracts;
|
||||
|
||||
namespace Aryx.AgentHost.Services;
|
||||
|
||||
internal interface IHookCommandRunner
|
||||
{
|
||||
Task<string?> RunAsync(
|
||||
HookCommandDefinition hook,
|
||||
string inputJson,
|
||||
string projectPath,
|
||||
CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
internal sealed class HookCommandRunner : IHookCommandRunner
|
||||
{
|
||||
private const int DefaultTimeoutSeconds = 30;
|
||||
|
||||
public static HookCommandRunner Instance { get; } = new();
|
||||
|
||||
public async Task<string?> RunAsync(
|
||||
HookCommandDefinition hook,
|
||||
string inputJson,
|
||||
string projectPath,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(hook);
|
||||
ArgumentNullException.ThrowIfNull(inputJson);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(projectPath);
|
||||
|
||||
string? commandText = SelectCommandText(hook);
|
||||
if (commandText is null)
|
||||
{
|
||||
Console.Error.WriteLine("[aryx hooks] Skipping hook because no compatible shell command is configured for this platform.");
|
||||
return null;
|
||||
}
|
||||
|
||||
string workingDirectory = ResolveWorkingDirectory(projectPath, hook.Cwd);
|
||||
ProcessStartInfo startInfo = CreateStartInfo(commandText, workingDirectory);
|
||||
ApplyEnvironment(startInfo, hook.Env);
|
||||
|
||||
using Process process = new()
|
||||
{
|
||||
StartInfo = startInfo,
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
if (!process.Start())
|
||||
{
|
||||
Console.Error.WriteLine($"[aryx hooks] Failed to start hook command '{commandText}'.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
catch (Win32Exception exception)
|
||||
{
|
||||
Console.Error.WriteLine($"[aryx hooks] Failed to start hook command '{commandText}': {exception.Message}");
|
||||
return null;
|
||||
}
|
||||
catch (InvalidOperationException exception)
|
||||
{
|
||||
Console.Error.WriteLine($"[aryx hooks] Failed to start hook command '{commandText}': {exception.Message}");
|
||||
return null;
|
||||
}
|
||||
|
||||
Task<string> stdoutTask = process.StandardOutput.ReadToEndAsync();
|
||||
Task<string> stderrTask = process.StandardError.ReadToEndAsync();
|
||||
|
||||
try
|
||||
{
|
||||
await process.StandardInput.WriteAsync(inputJson).ConfigureAwait(false);
|
||||
await process.StandardInput.FlushAsync().ConfigureAwait(false);
|
||||
process.StandardInput.Close();
|
||||
}
|
||||
catch (IOException exception)
|
||||
{
|
||||
TryKillProcess(process);
|
||||
Console.Error.WriteLine($"[aryx hooks] Failed to write hook input for '{commandText}': {exception.Message}");
|
||||
return null;
|
||||
}
|
||||
catch (ObjectDisposedException exception)
|
||||
{
|
||||
TryKillProcess(process);
|
||||
Console.Error.WriteLine($"[aryx hooks] Failed to write hook input for '{commandText}': {exception.Message}");
|
||||
return null;
|
||||
}
|
||||
|
||||
TimeSpan timeout = TimeSpan.FromSeconds(hook.TimeoutSec ?? DefaultTimeoutSeconds);
|
||||
using CancellationTokenSource timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeoutCts.CancelAfter(timeout);
|
||||
|
||||
try
|
||||
{
|
||||
await process.WaitForExitAsync(timeoutCts.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
TryKillProcess(process);
|
||||
await DrainOutputAsync(process, stdoutTask, stderrTask).ConfigureAwait(false);
|
||||
Console.Error.WriteLine($"[aryx hooks] Hook command timed out after {(int)timeout.TotalSeconds} seconds: '{commandText}'.");
|
||||
return null;
|
||||
}
|
||||
|
||||
string stdout = await stdoutTask.ConfigureAwait(false);
|
||||
string stderr = await stderrTask.ConfigureAwait(false);
|
||||
if (process.ExitCode != 0)
|
||||
{
|
||||
string detail = string.IsNullOrWhiteSpace(stderr) ? $"exit code {process.ExitCode}" : stderr.Trim();
|
||||
Console.Error.WriteLine($"[aryx hooks] Hook command failed for '{commandText}': {detail}");
|
||||
return null;
|
||||
}
|
||||
|
||||
return stdout;
|
||||
}
|
||||
|
||||
private static async Task DrainOutputAsync(Process process, Task<string> stdoutTask, Task<string> stderrTask)
|
||||
{
|
||||
try
|
||||
{
|
||||
await process.WaitForExitAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
// Process already exited or could not be waited on.
|
||||
}
|
||||
|
||||
await Task.WhenAll(stdoutTask, stderrTask).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static ProcessStartInfo CreateStartInfo(string commandText, string workingDirectory)
|
||||
{
|
||||
ProcessStartInfo startInfo = new()
|
||||
{
|
||||
WorkingDirectory = workingDirectory,
|
||||
RedirectStandardInput = true,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
};
|
||||
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
startInfo.FileName = "powershell.exe";
|
||||
startInfo.ArgumentList.Add("-NoLogo");
|
||||
startInfo.ArgumentList.Add("-NoProfile");
|
||||
startInfo.ArgumentList.Add("-NonInteractive");
|
||||
startInfo.ArgumentList.Add("-ExecutionPolicy");
|
||||
startInfo.ArgumentList.Add("Bypass");
|
||||
startInfo.ArgumentList.Add("-Command");
|
||||
startInfo.ArgumentList.Add(commandText);
|
||||
return startInfo;
|
||||
}
|
||||
|
||||
startInfo.FileName = "bash";
|
||||
startInfo.ArgumentList.Add("-lc");
|
||||
startInfo.ArgumentList.Add(commandText);
|
||||
return startInfo;
|
||||
}
|
||||
|
||||
private static void ApplyEnvironment(ProcessStartInfo startInfo, IReadOnlyDictionary<string, string>? environment)
|
||||
{
|
||||
if (environment is not { Count: > 0 })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ((string key, string value) in environment)
|
||||
{
|
||||
startInfo.Environment[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
private static string ResolveWorkingDirectory(string projectPath, string? configuredCwd)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(configuredCwd))
|
||||
{
|
||||
return Path.GetFullPath(projectPath);
|
||||
}
|
||||
|
||||
string resolved = Path.IsPathRooted(configuredCwd)
|
||||
? configuredCwd
|
||||
: Path.Combine(projectPath, configuredCwd);
|
||||
|
||||
return Path.GetFullPath(resolved);
|
||||
}
|
||||
|
||||
private static string? SelectCommandText(HookCommandDefinition hook)
|
||||
{
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
return NormalizeOptionalString(hook.PowerShell);
|
||||
}
|
||||
|
||||
return NormalizeOptionalString(hook.Bash);
|
||||
}
|
||||
|
||||
private static void TryKillProcess(Process process)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!process.HasExited)
|
||||
{
|
||||
process.Kill(entireProcessTree: true);
|
||||
}
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
// Process already exited.
|
||||
}
|
||||
catch (NotSupportedException)
|
||||
{
|
||||
// The platform does not support process tree termination.
|
||||
}
|
||||
}
|
||||
|
||||
private static string? NormalizeOptionalString(string? value)
|
||||
=> string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
using System.Text.Json;
|
||||
using Aryx.AgentHost.Contracts;
|
||||
|
||||
namespace Aryx.AgentHost.Services;
|
||||
|
||||
internal static class HookConfigLoader
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = CreateJsonOptions();
|
||||
|
||||
public static async Task<ResolvedHookSet> LoadAsync(string projectPath, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(projectPath);
|
||||
|
||||
string hooksDirectory = Path.Combine(projectPath, ".github", "hooks");
|
||||
if (!Directory.Exists(hooksDirectory))
|
||||
{
|
||||
return ResolvedHookSet.Empty;
|
||||
}
|
||||
|
||||
string[] hookFiles;
|
||||
try
|
||||
{
|
||||
hookFiles = Directory.GetFiles(hooksDirectory, "*.json", SearchOption.TopDirectoryOnly);
|
||||
}
|
||||
catch (IOException exception)
|
||||
{
|
||||
Console.Error.WriteLine($"[aryx hooks] Failed to enumerate hook files in '{hooksDirectory}': {exception.Message}");
|
||||
return ResolvedHookSet.Empty;
|
||||
}
|
||||
catch (UnauthorizedAccessException exception)
|
||||
{
|
||||
Console.Error.WriteLine($"[aryx hooks] Failed to enumerate hook files in '{hooksDirectory}': {exception.Message}");
|
||||
return ResolvedHookSet.Empty;
|
||||
}
|
||||
|
||||
if (hookFiles.Length == 0)
|
||||
{
|
||||
return ResolvedHookSet.Empty;
|
||||
}
|
||||
|
||||
Array.Sort(hookFiles, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
List<HookCommandDefinition> sessionStart = [];
|
||||
List<HookCommandDefinition> sessionEnd = [];
|
||||
List<HookCommandDefinition> userPromptSubmitted = [];
|
||||
List<HookCommandDefinition> preToolUse = [];
|
||||
List<HookCommandDefinition> postToolUse = [];
|
||||
List<HookCommandDefinition> errorOccurred = [];
|
||||
|
||||
foreach (string hookFile in hookFiles)
|
||||
{
|
||||
HookConfigFile? config = await ReadHookConfigAsync(hookFile, cancellationToken).ConfigureAwait(false);
|
||||
if (config is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (config.Version != 1)
|
||||
{
|
||||
Console.Error.WriteLine($"[aryx hooks] Skipping '{hookFile}' because it declares unsupported version '{config.Version}'.");
|
||||
continue;
|
||||
}
|
||||
|
||||
AddHooks(sessionStart, config.Hooks.SessionStart, HookTypeNames.SessionStart, hookFile);
|
||||
AddHooks(sessionEnd, config.Hooks.SessionEnd, HookTypeNames.SessionEnd, hookFile);
|
||||
AddHooks(userPromptSubmitted, config.Hooks.UserPromptSubmitted, HookTypeNames.UserPromptSubmitted, hookFile);
|
||||
AddHooks(preToolUse, config.Hooks.PreToolUse, HookTypeNames.PreToolUse, hookFile);
|
||||
AddHooks(postToolUse, config.Hooks.PostToolUse, HookTypeNames.PostToolUse, hookFile);
|
||||
AddHooks(errorOccurred, config.Hooks.ErrorOccurred, HookTypeNames.ErrorOccurred, hookFile);
|
||||
}
|
||||
|
||||
if (
|
||||
sessionStart.Count == 0
|
||||
&& sessionEnd.Count == 0
|
||||
&& userPromptSubmitted.Count == 0
|
||||
&& preToolUse.Count == 0
|
||||
&& postToolUse.Count == 0
|
||||
&& errorOccurred.Count == 0)
|
||||
{
|
||||
return ResolvedHookSet.Empty;
|
||||
}
|
||||
|
||||
return new ResolvedHookSet
|
||||
{
|
||||
SessionStart = [.. sessionStart],
|
||||
SessionEnd = [.. sessionEnd],
|
||||
UserPromptSubmitted = [.. userPromptSubmitted],
|
||||
PreToolUse = [.. preToolUse],
|
||||
PostToolUse = [.. postToolUse],
|
||||
ErrorOccurred = [.. errorOccurred],
|
||||
};
|
||||
}
|
||||
|
||||
private static void AddHooks(
|
||||
ICollection<HookCommandDefinition> target,
|
||||
IReadOnlyList<HookCommandDefinition>? definitions,
|
||||
string hookType,
|
||||
string hookFile)
|
||||
{
|
||||
if (definitions is not { Count: > 0 })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (HookCommandDefinition definition in definitions)
|
||||
{
|
||||
HookCommandDefinition? normalized = NormalizeDefinition(definition, hookType, hookFile);
|
||||
if (normalized is not null)
|
||||
{
|
||||
target.Add(normalized);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static HookCommandDefinition? NormalizeDefinition(
|
||||
HookCommandDefinition definition,
|
||||
string hookType,
|
||||
string hookFile)
|
||||
{
|
||||
string type = NormalizeOptionalString(definition.Type) ?? string.Empty;
|
||||
if (!string.Equals(type, "command", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Console.Error.WriteLine($"[aryx hooks] Skipping '{hookType}' entry in '{hookFile}' because type '{definition.Type}' is unsupported.");
|
||||
return null;
|
||||
}
|
||||
|
||||
string? bash = NormalizeOptionalString(definition.Bash);
|
||||
string? powerShell = NormalizeOptionalString(definition.PowerShell);
|
||||
if (bash is null && powerShell is null)
|
||||
{
|
||||
Console.Error.WriteLine($"[aryx hooks] Skipping '{hookType}' entry in '{hookFile}' because no shell command is configured.");
|
||||
return null;
|
||||
}
|
||||
|
||||
int? timeoutSec = definition.TimeoutSec;
|
||||
if (timeoutSec is <= 0)
|
||||
{
|
||||
timeoutSec = null;
|
||||
}
|
||||
|
||||
IReadOnlyDictionary<string, string>? env = NormalizeEnvironment(definition.Env);
|
||||
|
||||
return new HookCommandDefinition
|
||||
{
|
||||
Type = "command",
|
||||
Bash = bash,
|
||||
PowerShell = powerShell,
|
||||
Cwd = NormalizeOptionalString(definition.Cwd),
|
||||
Env = env,
|
||||
TimeoutSec = timeoutSec,
|
||||
};
|
||||
}
|
||||
|
||||
private static async Task<HookConfigFile?> ReadHookConfigAsync(string hookFile, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using FileStream stream = File.OpenRead(hookFile);
|
||||
return await JsonSerializer.DeserializeAsync<HookConfigFile>(stream, JsonOptions, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (JsonException exception)
|
||||
{
|
||||
Console.Error.WriteLine($"[aryx hooks] Failed to parse '{hookFile}': {exception.Message}");
|
||||
return null;
|
||||
}
|
||||
catch (IOException exception)
|
||||
{
|
||||
Console.Error.WriteLine($"[aryx hooks] Failed to read '{hookFile}': {exception.Message}");
|
||||
return null;
|
||||
}
|
||||
catch (UnauthorizedAccessException exception)
|
||||
{
|
||||
Console.Error.WriteLine($"[aryx hooks] Failed to read '{hookFile}': {exception.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static IReadOnlyDictionary<string, string>? NormalizeEnvironment(IReadOnlyDictionary<string, string>? environment)
|
||||
{
|
||||
if (environment is not { Count: > 0 })
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
Dictionary<string, string> normalized = new(StringComparer.Ordinal);
|
||||
foreach ((string key, string value) in environment)
|
||||
{
|
||||
string? normalizedKey = NormalizeOptionalString(key);
|
||||
if (normalizedKey is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
normalized[normalizedKey] = value;
|
||||
}
|
||||
|
||||
return normalized.Count == 0 ? null : normalized;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using Aryx.AgentHost.Contracts;
|
||||
|
||||
namespace Aryx.AgentHost.Services;
|
||||
|
||||
public interface ICopilotSessionManager
|
||||
{
|
||||
Task<IReadOnlyList<CopilotSessionInfoDto>> ListSessionsAsync(
|
||||
CopilotSessionListFilterDto? filter,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
Task<IReadOnlyList<CopilotSessionInfoDto>> DeleteSessionsAsync(
|
||||
string? aryxSessionId,
|
||||
string? copilotSessionId,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
Task<IReadOnlyDictionary<string, QuotaSnapshotDto>> GetQuotaAsync(
|
||||
CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
@@ -7,11 +7,18 @@ public interface ITurnWorkflowRunner
|
||||
Task<IReadOnlyList<ChatMessageDto>> RunTurnAsync(
|
||||
RunTurnCommandDto command,
|
||||
Func<TurnDeltaEventDto, Task> onDelta,
|
||||
Func<AgentActivityEventDto, Task> onActivity,
|
||||
Func<SidecarEventDto, Task> onEvent,
|
||||
Func<ApprovalRequestedEventDto, Task> onApproval,
|
||||
Func<UserInputRequestedEventDto, Task> onUserInput,
|
||||
Func<McpOauthRequiredEventDto, Task> onMcpOAuthRequired,
|
||||
Func<ExitPlanModeRequestedEventDto, Task> onExitPlanMode,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
Task ResolveApprovalAsync(
|
||||
ResolveApprovalCommandDto command,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
Task ResolveUserInputAsync(
|
||||
ResolveUserInputCommandDto command,
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,18 @@ public sealed class SidecarProtocolHost
|
||||
private const string RunTurnCommandType = "run-turn";
|
||||
private const string CancelTurnCommandType = "cancel-turn";
|
||||
private const string ResolveApprovalCommandType = "resolve-approval";
|
||||
private const string ResolveUserInputCommandType = "resolve-user-input";
|
||||
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)
|
||||
{
|
||||
AskUserToolName,
|
||||
"report_intent",
|
||||
"task_complete",
|
||||
};
|
||||
|
||||
private static readonly string[] AuthenticationErrorIndicators =
|
||||
[
|
||||
@@ -31,11 +43,14 @@ public sealed class SidecarProtocolHost
|
||||
private readonly Func<CancellationToken, Task<SidecarCapabilitiesDto>> _capabilitiesProvider;
|
||||
private readonly PatternValidator _patternValidator;
|
||||
private readonly ITurnWorkflowRunner _workflowRunner;
|
||||
private readonly ICopilotSessionManager _sessionManager;
|
||||
private readonly JsonSerializerOptions _jsonOptions;
|
||||
private readonly IReadOnlyDictionary<string, Func<CommandContext, Task>> _commandHandlers;
|
||||
private readonly SemaphoreSlim _writeLock = new(1, 1);
|
||||
private readonly ConcurrentDictionary<string, Task> _inFlight = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<string, CancellationTokenSource> _turnCancellations = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<string, ConcurrentDictionary<string, byte>> _turnRequestIdsBySessionId =
|
||||
new(StringComparer.Ordinal);
|
||||
|
||||
public SidecarProtocolHost()
|
||||
: this(new PatternValidator())
|
||||
@@ -45,16 +60,16 @@ public sealed class SidecarProtocolHost
|
||||
public SidecarProtocolHost(
|
||||
PatternValidator patternValidator,
|
||||
ITurnWorkflowRunner? workflowRunner = null,
|
||||
Func<CancellationToken, Task<SidecarCapabilitiesDto>>? capabilitiesProvider = null)
|
||||
Func<CancellationToken, Task<SidecarCapabilitiesDto>>? capabilitiesProvider = null,
|
||||
ICopilotSessionManager? sessionManager = null)
|
||||
{
|
||||
_patternValidator = patternValidator;
|
||||
_workflowRunner = workflowRunner ?? new CopilotWorkflowRunner(_patternValidator);
|
||||
_capabilitiesProvider = capabilitiesProvider ?? BuildCapabilitiesAsync;
|
||||
_jsonOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web)
|
||||
{
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
PropertyNameCaseInsensitive = true,
|
||||
};
|
||||
_sessionManager = sessionManager ?? new CopilotSessionManager();
|
||||
_jsonOptions = JsonSerialization.CreateWebOptions();
|
||||
_jsonOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
|
||||
_jsonOptions.PropertyNameCaseInsensitive = true;
|
||||
_commandHandlers = new Dictionary<string, Func<CommandContext, Task>>(StringComparer.Ordinal)
|
||||
{
|
||||
[DescribeCapabilitiesCommandType] = HandleDescribeCapabilitiesAsync,
|
||||
@@ -62,6 +77,11 @@ public sealed class SidecarProtocolHost
|
||||
[RunTurnCommandType] = HandleRunTurnAsync,
|
||||
[CancelTurnCommandType] = HandleCancelTurnAsync,
|
||||
[ResolveApprovalCommandType] = HandleResolveApprovalAsync,
|
||||
[ResolveUserInputCommandType] = HandleResolveUserInputAsync,
|
||||
[ListSessionsCommandType] = HandleListSessionsAsync,
|
||||
[DeleteSessionCommandType] = HandleDeleteSessionAsync,
|
||||
[DisconnectSessionCommandType] = HandleDisconnectSessionAsync,
|
||||
[GetQuotaCommandType] = HandleGetQuotaAsync,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -171,13 +191,17 @@ public sealed class SidecarProtocolHost
|
||||
$"A turn with request ID '{context.Envelope.RequestId}' is already in progress.");
|
||||
}
|
||||
|
||||
RegisterTurnRequest(command.SessionId, context.Envelope.RequestId);
|
||||
try
|
||||
{
|
||||
IReadOnlyList<ChatMessageDto> messages = await _workflowRunner.RunTurnAsync(
|
||||
command,
|
||||
delta => WriteAsync(context.Output, delta, turnCancellation.Token),
|
||||
activity => WriteAsync(context.Output, activity, turnCancellation.Token),
|
||||
evt => WriteAsync(context.Output, evt, turnCancellation.Token),
|
||||
approval => WriteAsync(context.Output, approval, turnCancellation.Token),
|
||||
userInput => WriteAsync(context.Output, userInput, turnCancellation.Token),
|
||||
mcpOauth => WriteAsync(context.Output, mcpOauth, turnCancellation.Token),
|
||||
exitPlanMode => WriteAsync(context.Output, exitPlanMode, turnCancellation.Token),
|
||||
turnCancellation.Token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
@@ -204,6 +228,7 @@ public sealed class SidecarProtocolHost
|
||||
finally
|
||||
{
|
||||
_turnCancellations.TryRemove(context.Envelope.RequestId, out _);
|
||||
UnregisterTurnRequest(command.SessionId, context.Envelope.RequestId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,6 +256,80 @@ public sealed class SidecarProtocolHost
|
||||
await _workflowRunner.ResolveApprovalAsync(command, context.CancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task HandleResolveUserInputAsync(CommandContext context)
|
||||
{
|
||||
ResolveUserInputCommandDto command = DeserializeCommand<ResolveUserInputCommandDto>(context);
|
||||
await _workflowRunner.ResolveUserInputAsync(command, context.CancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task HandleListSessionsAsync(CommandContext context)
|
||||
{
|
||||
ListSessionsCommandDto command = DeserializeCommand<ListSessionsCommandDto>(context);
|
||||
IReadOnlyList<CopilotSessionInfoDto> sessions = await _sessionManager.ListSessionsAsync(
|
||||
command.Filter,
|
||||
context.CancellationToken).ConfigureAwait(false);
|
||||
|
||||
await WriteAsync(context.Output, new SessionsListedEventDto
|
||||
{
|
||||
Type = "sessions-listed",
|
||||
RequestId = context.Envelope.RequestId,
|
||||
Sessions = sessions,
|
||||
}, context.CancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task HandleDeleteSessionAsync(CommandContext context)
|
||||
{
|
||||
DeleteSessionCommandDto command = DeserializeCommand<DeleteSessionCommandDto>(context);
|
||||
if (!string.IsNullOrWhiteSpace(command.SessionId))
|
||||
{
|
||||
CancelTurnRequestsForSession(command.SessionId);
|
||||
}
|
||||
|
||||
IReadOnlyList<CopilotSessionInfoDto> deletedSessions = await _sessionManager.DeleteSessionsAsync(
|
||||
command.SessionId,
|
||||
command.CopilotSessionId,
|
||||
context.CancellationToken).ConfigureAwait(false);
|
||||
|
||||
await WriteAsync(context.Output, new SessionsDeletedEventDto
|
||||
{
|
||||
Type = "sessions-deleted",
|
||||
RequestId = context.Envelope.RequestId,
|
||||
SessionId = string.IsNullOrWhiteSpace(command.SessionId) ? null : command.SessionId.Trim(),
|
||||
Sessions = deletedSessions,
|
||||
}, context.CancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task HandleDisconnectSessionAsync(CommandContext context)
|
||||
{
|
||||
DisconnectSessionCommandDto command = DeserializeCommand<DisconnectSessionCommandDto>(context);
|
||||
IReadOnlyList<string> cancelledRequestIds = CancelTurnRequestsForSession(command.SessionId);
|
||||
|
||||
await WriteAsync(context.Output, new SessionDisconnectedEventDto
|
||||
{
|
||||
Type = "session-disconnected",
|
||||
RequestId = context.Envelope.RequestId,
|
||||
SessionId = command.SessionId,
|
||||
CancelledRequestIds = cancelledRequestIds,
|
||||
}, 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
|
||||
{
|
||||
@@ -291,6 +390,67 @@ public sealed class SidecarProtocolHost
|
||||
}
|
||||
}
|
||||
|
||||
private void RegisterTurnRequest(string sessionId, string requestId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(sessionId) || string.IsNullOrWhiteSpace(requestId))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
ConcurrentDictionary<string, byte> requestIds = _turnRequestIdsBySessionId.GetOrAdd(
|
||||
sessionId.Trim(),
|
||||
static _ => new ConcurrentDictionary<string, byte>(StringComparer.Ordinal));
|
||||
requestIds[requestId.Trim()] = 0;
|
||||
}
|
||||
|
||||
private void UnregisterTurnRequest(string sessionId, string requestId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(sessionId) || string.IsNullOrWhiteSpace(requestId))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_turnRequestIdsBySessionId.TryGetValue(sessionId.Trim(), out ConcurrentDictionary<string, byte>? requestIds))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
requestIds.TryRemove(requestId.Trim(), out _);
|
||||
if (requestIds.IsEmpty)
|
||||
{
|
||||
_turnRequestIdsBySessionId.TryRemove(sessionId.Trim(), out _);
|
||||
}
|
||||
}
|
||||
|
||||
private IReadOnlyList<string> CancelTurnRequestsForSession(string sessionId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(sessionId)
|
||||
|| !_turnRequestIdsBySessionId.TryGetValue(sessionId.Trim(), out ConcurrentDictionary<string, byte>? requestIds))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
List<string> cancelledRequestIds = [];
|
||||
foreach (string requestId in requestIds.Keys)
|
||||
{
|
||||
if (!_turnCancellations.TryGetValue(requestId, out CancellationTokenSource? turnCancellation))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
turnCancellation.Cancel();
|
||||
cancelledRequestIds.Add(requestId);
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
return cancelledRequestIds;
|
||||
}
|
||||
|
||||
private static async Task<SidecarCapabilitiesDto> BuildCapabilitiesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
@@ -427,7 +587,13 @@ public sealed class SidecarProtocolHost
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ToolsListResult result = await client.Rpc.Tools.ListAsync(null!, cancellationToken).ConfigureAwait(false);
|
||||
return result.Tools
|
||||
return MapRuntimeTools(result.Tools);
|
||||
}
|
||||
|
||||
internal static IReadOnlyList<SidecarRuntimeToolDto> MapRuntimeTools(IEnumerable<Tool> tools)
|
||||
{
|
||||
return tools
|
||||
.Where(ShouldIncludeRuntimeTool)
|
||||
.Where(tool => !string.IsNullOrWhiteSpace(tool.Name))
|
||||
.Select(tool => new SidecarRuntimeToolDto
|
||||
{
|
||||
@@ -440,6 +606,13 @@ public sealed class SidecarProtocolHost
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private static bool ShouldIncludeRuntimeTool(Tool tool)
|
||||
{
|
||||
string? toolName = string.IsNullOrWhiteSpace(tool.Name) ? null : tool.Name.Trim();
|
||||
return toolName is not null
|
||||
&& !ExcludedRuntimeToolNames.Contains(toolName);
|
||||
}
|
||||
|
||||
private static bool IsReasoningEffort(string? value)
|
||||
{
|
||||
return value is "low" or "medium" or "high" or "xhigh";
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Text;
|
||||
using Aryx.AgentHost.Contracts;
|
||||
using GitHub.Copilot.SDK;
|
||||
using Microsoft.Extensions.AI;
|
||||
|
||||
namespace Aryx.AgentHost.Services;
|
||||
@@ -26,9 +27,30 @@ internal static class WorkflowTranscriptProjector
|
||||
mapped.AuthorName = message.AuthorName;
|
||||
}
|
||||
|
||||
foreach (ChatMessageAttachmentDto attachment in message.Attachments)
|
||||
{
|
||||
mapped.Contents.Add(new AIContent
|
||||
{
|
||||
RawRepresentation = attachment,
|
||||
});
|
||||
}
|
||||
|
||||
return mapped;
|
||||
}
|
||||
|
||||
public static void AttachMessageMode(IList<ChatMessage> messages, string? messageMode)
|
||||
{
|
||||
if (messages.Count == 0 || string.IsNullOrWhiteSpace(messageMode))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
messages[^1].Contents.Add(new AIContent
|
||||
{
|
||||
RawRepresentation = new CopilotMessageOptionsMetadata(messageMode.Trim()),
|
||||
});
|
||||
}
|
||||
|
||||
public static List<ChatMessageDto> ProjectCompletedMessages(
|
||||
RunTurnCommandDto command,
|
||||
IReadOnlyList<ChatMessage> newMessages,
|
||||
@@ -64,7 +86,7 @@ internal static class WorkflowTranscriptProjector
|
||||
assistantMessages.Count - messageIndex,
|
||||
command.Pattern,
|
||||
fallbackAgent);
|
||||
string content = message.Text ?? matchedSegment?.Content ?? string.Empty;
|
||||
string content = ResolveProjectedContent(message, matchedSegment);
|
||||
if (string.IsNullOrWhiteSpace(content))
|
||||
{
|
||||
continue;
|
||||
@@ -106,7 +128,9 @@ internal static class WorkflowTranscriptProjector
|
||||
{
|
||||
return new ChatMessageDto
|
||||
{
|
||||
Id = matchedSegment?.MessageId ?? $"{command.RequestId}-final-{fallbackOutputIndex}",
|
||||
Id = matchedSegment?.MessageId
|
||||
?? message.MessageId
|
||||
?? $"{command.RequestId}-final-{fallbackOutputIndex}",
|
||||
Role = message.Role == ChatRole.System ? "system" : "assistant",
|
||||
AuthorName = ResolveProjectedAuthorName(
|
||||
command.Pattern,
|
||||
@@ -118,6 +142,35 @@ internal static class WorkflowTranscriptProjector
|
||||
};
|
||||
}
|
||||
|
||||
private static string ResolveProjectedContent(
|
||||
ChatMessage message,
|
||||
TranscriptSegment? matchedSegment)
|
||||
{
|
||||
return FirstNonBlank(
|
||||
message.Text,
|
||||
matchedSegment?.Content,
|
||||
TryGetAssistantMessageContent(message))
|
||||
?? string.Empty;
|
||||
}
|
||||
|
||||
private static string? TryGetAssistantMessageContent(ChatMessage message)
|
||||
{
|
||||
if (TryGetAssistantMessageData(message.RawRepresentation, out AssistantMessageData? assistantMessageData))
|
||||
{
|
||||
return assistantMessageData?.Content;
|
||||
}
|
||||
|
||||
foreach (AIContent content in message.Contents)
|
||||
{
|
||||
if (TryGetAssistantMessageData(content.RawRepresentation, out assistantMessageData))
|
||||
{
|
||||
return assistantMessageData?.Content;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static ChatMessageDto CreateProjectedMessageFromSegment(
|
||||
RunTurnCommandDto command,
|
||||
TranscriptSegment segment,
|
||||
@@ -339,11 +392,57 @@ internal static class WorkflowTranscriptProjector
|
||||
return fallbackAgent.Value.AgentName;
|
||||
}
|
||||
|
||||
if (fallbackAgent.HasValue
|
||||
&& string.IsNullOrWhiteSpace(primaryIdentifier)
|
||||
&& string.IsNullOrWhiteSpace(fallbackIdentifier))
|
||||
{
|
||||
return fallbackAgent.Value.AgentName;
|
||||
}
|
||||
|
||||
if (pattern.Agents.Count == 1
|
||||
&& string.IsNullOrWhiteSpace(primaryIdentifier)
|
||||
&& string.IsNullOrWhiteSpace(fallbackIdentifier))
|
||||
{
|
||||
PatternAgentDefinitionDto singleAgent = pattern.Agents[0];
|
||||
return AgentIdentityResolver.ResolveDisplayAuthorName(pattern, singleAgent.Id, singleAgent.Name);
|
||||
}
|
||||
|
||||
return AgentIdentityResolver.ResolveDisplayAuthorName(
|
||||
pattern,
|
||||
primaryIdentifier,
|
||||
fallbackIdentifier);
|
||||
}
|
||||
|
||||
private static bool TryGetAssistantMessageData(
|
||||
object? rawRepresentation,
|
||||
out AssistantMessageData? assistantMessageData)
|
||||
{
|
||||
switch (rawRepresentation)
|
||||
{
|
||||
case AssistantMessageEvent assistantMessage when !string.IsNullOrWhiteSpace(assistantMessage.Data.Content):
|
||||
assistantMessageData = assistantMessage.Data;
|
||||
return true;
|
||||
case AssistantMessageData data when !string.IsNullOrWhiteSpace(data.Content):
|
||||
assistantMessageData = data;
|
||||
return true;
|
||||
default:
|
||||
assistantMessageData = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static string? FirstNonBlank(params string?[] values)
|
||||
{
|
||||
foreach (string? value in values)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class StreamingTranscriptBuffer
|
||||
|
||||
@@ -124,6 +124,66 @@ public sealed class AgentInstructionComposerTests
|
||||
Assert.DoesNotContain("Do not inspect, modify, create, or delete files", instructions, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Compose_AddsPlanModeGuidanceWhenRequested()
|
||||
{
|
||||
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,
|
||||
interactionMode: "plan");
|
||||
|
||||
Assert.Contains("operating in plan mode", instructions, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("produce a concrete implementation plan", instructions, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("exit_plan_mode", instructions, StringComparison.OrdinalIgnoreCase);
|
||||
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
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
using Aryx.AgentHost.Contracts;
|
||||
using Aryx.AgentHost.Services;
|
||||
using GitHub.Copilot.SDK;
|
||||
using Microsoft.Extensions.AI;
|
||||
|
||||
namespace Aryx.AgentHost.Tests;
|
||||
|
||||
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 = attachmentPath,
|
||||
DisplayName = "diagram.png",
|
||||
},
|
||||
});
|
||||
message.Contents.Add(new AIContent
|
||||
{
|
||||
RawRepresentation = new ChatMessageAttachmentDto
|
||||
{
|
||||
Type = "blob",
|
||||
Data = "QUJDRA==",
|
||||
MimeType = "image/png",
|
||||
DisplayName = "clipboard.png",
|
||||
},
|
||||
});
|
||||
message.Contents.Add(new AIContent
|
||||
{
|
||||
RawRepresentation = new CopilotMessageOptionsMetadata("immediate"),
|
||||
});
|
||||
|
||||
(List<UserMessageDataAttachmentsItem>? attachments, string? messageMode, string? tempDir) =
|
||||
await AryxCopilotAgent.ProcessMessageAttachmentsAsync([message], CancellationToken.None);
|
||||
|
||||
Assert.Equal("immediate", messageMode);
|
||||
Assert.Null(tempDir);
|
||||
|
||||
Assert.NotNull(attachments);
|
||||
Assert.Collection(
|
||||
attachments!,
|
||||
first =>
|
||||
{
|
||||
UserMessageDataAttachmentsItemFile file = Assert.IsType<UserMessageDataAttachmentsItemFile>(first);
|
||||
Assert.Equal(attachmentPath, file.Path);
|
||||
Assert.Equal("diagram.png", file.DisplayName);
|
||||
},
|
||||
second =>
|
||||
{
|
||||
UserMessageDataAttachmentsItemBlob blob = Assert.IsType<UserMessageDataAttachmentsItemBlob>(second);
|
||||
Assert.Equal("QUJDRA==", blob.Data);
|
||||
Assert.Equal("image/png", blob.MimeType);
|
||||
Assert.Equal("clipboard.png", blob.DisplayName);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ProcessMessageAttachmentsAsync_RejectsRelativeFileAttachments()
|
||||
{
|
||||
ChatMessage message = new(ChatRole.User, "Inspect this file.");
|
||||
message.Contents.Add(new AIContent
|
||||
{
|
||||
RawRepresentation = new ChatMessageAttachmentDto
|
||||
{
|
||||
Type = "file",
|
||||
Path = "relative\\image.png",
|
||||
},
|
||||
});
|
||||
|
||||
InvalidOperationException error = await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
AryxCopilotAgent.ProcessMessageAttachmentsAsync([message], CancellationToken.None));
|
||||
|
||||
Assert.Contains("absolute", error.Message, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
using System.Reflection;
|
||||
using Aryx.AgentHost.Services;
|
||||
using System.Text.Json;
|
||||
using Aryx.AgentHost.Contracts;
|
||||
using GitHub.Copilot.SDK;
|
||||
using Aryx.AgentHost.Services;
|
||||
using Microsoft.Agents.AI;
|
||||
using Microsoft.Extensions.AI;
|
||||
|
||||
namespace Aryx.AgentHost.Tests;
|
||||
@@ -50,6 +53,298 @@ public sealed class CopilotAgentBundleTests
|
||||
Assert.Equal(["glob", "view"], sessionConfig.AvailableTools);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_StoresWhetherHooksAreConfigured()
|
||||
{
|
||||
CopilotAgentBundle bundle = new([], hasConfiguredHooks: true);
|
||||
|
||||
Assert.True(bundle.HasConfiguredHooks);
|
||||
Assert.Empty(bundle.Agents);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateConfiguredSessionConfig_MergesInstructionsAndConvertsHandoffDeclarations()
|
||||
{
|
||||
SessionConfig baseConfig = new()
|
||||
{
|
||||
Model = "gpt-5.4",
|
||||
SystemMessage = new SystemMessageConfig
|
||||
{
|
||||
Content = "Base instructions",
|
||||
},
|
||||
Tools = [CreateTool()],
|
||||
};
|
||||
ChatClientAgentRunOptions options = new(new ChatOptions
|
||||
{
|
||||
Instructions = "Workflow handoff instructions",
|
||||
Tools = [CreateHandoffDeclaration()],
|
||||
});
|
||||
|
||||
SessionConfig effective = AryxCopilotAgent.CreateConfiguredSessionConfig(baseConfig, options);
|
||||
|
||||
Assert.Equal("gpt-5.4", effective.Model);
|
||||
Assert.Equal("Base instructions\n\nWorkflow handoff instructions", effective.SystemMessage?.Content);
|
||||
Assert.Equal("Base instructions", baseConfig.SystemMessage?.Content);
|
||||
|
||||
AIFunction[] tools = Assert.IsAssignableFrom<IEnumerable<AIFunction>>(effective.Tools).ToArray();
|
||||
Assert.Equal(2, tools.Length);
|
||||
AIFunction handoffTool = Assert.Single(tools, tool => tool.Name == "handoff_to_1");
|
||||
Assert.True(handoffTool.AdditionalProperties.TryGetValue("skip_permission", out object? skipPermission));
|
||||
Assert.Equal(true, skipPermission);
|
||||
|
||||
object? result = await handoffTool.InvokeAsync(new AIFunctionArguments
|
||||
{
|
||||
["reasonForHandoff"] = "UI specialist",
|
||||
});
|
||||
|
||||
Assert.Equal("Transferred.", result?.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateConfiguredSessionConfig_RejectsUnsupportedRuntimeDeclarations()
|
||||
{
|
||||
ChatClientAgentRunOptions options = new(new ChatOptions
|
||||
{
|
||||
Tools = [AIFunctionFactory.CreateDeclaration("route_elsewhere", "Unsupported declaration", CreateTool().JsonSchema)],
|
||||
});
|
||||
|
||||
Assert.Throws<NotSupportedException>(() => AryxCopilotAgent.CreateConfiguredSessionConfig(new SessionConfig(), options));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConvertToolRequestsToFunctionCalls_MapsCallIdsNamesAndArguments()
|
||||
{
|
||||
AssistantMessageDataToolRequestsItem[] toolRequests =
|
||||
{
|
||||
new()
|
||||
{
|
||||
ToolCallId = "call-123",
|
||||
Name = "handoff_to_1",
|
||||
Arguments = JsonSerializer.SerializeToElement(new Dictionary<string, object?>
|
||||
{
|
||||
["reasonForHandoff"] = "frontend specialist",
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
FunctionCallContent functionCall = Assert.Single(AryxCopilotAgent.ConvertToolRequestsToFunctionCalls(toolRequests));
|
||||
|
||||
Assert.Equal("call-123", functionCall.CallId);
|
||||
Assert.Equal("handoff_to_1", functionCall.Name);
|
||||
Assert.NotNull(functionCall.Arguments);
|
||||
Assert.Equal("frontend specialist", functionCall.Arguments["reasonForHandoff"]?.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConvertToolRequestsToFunctionCalls_SkipsNonHandoffToolCalls()
|
||||
{
|
||||
AssistantMessageDataToolRequestsItem[] toolRequests =
|
||||
{
|
||||
new() { ToolCallId = "call-001", Name = "ask_user" },
|
||||
new() { ToolCallId = "call-002", Name = "web_fetch" },
|
||||
new() { ToolCallId = "call-003", Name = "handoff_to_reviewer" },
|
||||
new() { ToolCallId = "call-004", Name = "grep" },
|
||||
};
|
||||
|
||||
IReadOnlyList<FunctionCallContent> result = AryxCopilotAgent.ConvertToolRequestsToFunctionCalls(toolRequests);
|
||||
|
||||
FunctionCallContent single = Assert.Single(result);
|
||||
Assert.Equal("call-003", single.CallId);
|
||||
Assert.Equal("handoff_to_reviewer", single.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateCustomAgents_MapsSdkCustomAgentConfiguration()
|
||||
{
|
||||
List<CustomAgentConfig> customAgents = Assert.IsType<List<CustomAgentConfig>>(CopilotAgentBundle.CreateCustomAgents(
|
||||
[
|
||||
new RunTurnCustomAgentConfigDto
|
||||
{
|
||||
Name = "designer",
|
||||
DisplayName = "Designer",
|
||||
Description = "Design specialist",
|
||||
Tools = ["view", "glob"],
|
||||
Prompt = "Focus on UX design.",
|
||||
Infer = true,
|
||||
McpServers =
|
||||
[
|
||||
new RunTurnMcpServerConfigDto
|
||||
{
|
||||
Id = "designer-mcp",
|
||||
Name = "Designer MCP",
|
||||
Transport = "local",
|
||||
Command = "node",
|
||||
Args = ["designer.js"],
|
||||
},
|
||||
],
|
||||
},
|
||||
]));
|
||||
|
||||
CustomAgentConfig customAgent = Assert.Single(customAgents);
|
||||
Assert.Equal("designer", customAgent.Name);
|
||||
Assert.Equal("Designer", customAgent.DisplayName);
|
||||
Assert.Equal("Design specialist", customAgent.Description);
|
||||
Assert.Equal(["view", "glob"], customAgent.Tools);
|
||||
Assert.Equal("Focus on UX design.", customAgent.Prompt);
|
||||
Assert.True(customAgent.Infer);
|
||||
|
||||
KeyValuePair<string, object> mcpServer = Assert.Single(customAgent.McpServers!);
|
||||
Assert.Equal("Designer MCP", mcpServer.Key);
|
||||
McpLocalServerConfig localServer = Assert.IsType<McpLocalServerConfig>(mcpServer.Value);
|
||||
Assert.Equal("node", localServer.Command);
|
||||
Assert.Equal(["designer.js"], localServer.Args);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateInfiniteSessions_MapsSdkInfiniteSessionConfiguration()
|
||||
{
|
||||
InfiniteSessionConfig config = Assert.IsType<InfiniteSessionConfig>(CopilotAgentBundle.CreateInfiniteSessions(
|
||||
new RunTurnInfiniteSessionsConfigDto
|
||||
{
|
||||
Enabled = true,
|
||||
BackgroundCompactionThreshold = 0.75,
|
||||
BufferExhaustionThreshold = 0.9,
|
||||
}));
|
||||
|
||||
Assert.True(config.Enabled);
|
||||
Assert.Equal(0.75, config.BackgroundCompactionThreshold);
|
||||
Assert.Equal(0.9, config.BufferExhaustionThreshold);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateSessionConfig_DoesNotForceSessionId()
|
||||
{
|
||||
RunTurnCommandDto command = new()
|
||||
{
|
||||
SessionId = "session-1",
|
||||
ProjectPath = @"C:\workspace\project",
|
||||
WorkspaceKind = "project",
|
||||
Mode = "interactive",
|
||||
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.Null(sessionConfig.SessionId);
|
||||
Assert.Equal(@"C:\workspace\project", sessionConfig.WorkingDirectory);
|
||||
Assert.True(sessionConfig.Streaming);
|
||||
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()
|
||||
{
|
||||
RunTurnCommandDto command = new()
|
||||
{
|
||||
RequestId = "turn-1",
|
||||
SessionId = "session-1",
|
||||
Pattern = new PatternDefinitionDto
|
||||
{
|
||||
Id = "pattern-1",
|
||||
Name = "Pattern",
|
||||
Mode = "single",
|
||||
Availability = "available",
|
||||
ApprovalPolicy = new ApprovalPolicyDto
|
||||
{
|
||||
Rules =
|
||||
[
|
||||
new ApprovalCheckpointRuleDto
|
||||
{
|
||||
Kind = "tool-call",
|
||||
AgentIds = ["agent-1"],
|
||||
},
|
||||
],
|
||||
},
|
||||
Agents =
|
||||
[
|
||||
new PatternAgentDefinitionDto
|
||||
{
|
||||
Id = "agent-1",
|
||||
Name = "Primary",
|
||||
Model = "gpt-5.4",
|
||||
Instructions = "Help.",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0]);
|
||||
PreToolUseHookOutput? decision = await hooks.OnPreToolUse!(
|
||||
new PreToolUseHookInput
|
||||
{
|
||||
ToolName = "view",
|
||||
},
|
||||
null!);
|
||||
|
||||
Assert.Equal("ask", decision?.PermissionDecision);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CopilotManagedSessionIds_BuildsAndParsesStableIds()
|
||||
{
|
||||
string sessionId = CopilotManagedSessionIds.Build("session-1", "agent-ux");
|
||||
|
||||
Assert.True(CopilotManagedSessionIds.TryParse(sessionId, out string aryxSessionId, out string agentId));
|
||||
Assert.Equal("session-1", aryxSessionId);
|
||||
Assert.Equal("agent-ux", agentId);
|
||||
}
|
||||
|
||||
private static AIFunction CreateTool()
|
||||
{
|
||||
ToolTarget target = new();
|
||||
@@ -66,6 +361,14 @@ public sealed class CopilotAgentBundleTests
|
||||
});
|
||||
}
|
||||
|
||||
private static AIFunctionDeclaration CreateHandoffDeclaration()
|
||||
{
|
||||
return AIFunctionFactory.CreateDeclaration(
|
||||
"handoff_to_1",
|
||||
"Transfer ownership to a specialist",
|
||||
CreateTool().JsonSchema);
|
||||
}
|
||||
|
||||
private sealed class ToolTarget
|
||||
{
|
||||
public string Echo() => "ok";
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
using Aryx.AgentHost.Contracts;
|
||||
using Aryx.AgentHost.Services;
|
||||
using GitHub.Copilot.SDK;
|
||||
|
||||
namespace Aryx.AgentHost.Tests;
|
||||
|
||||
public sealed class CopilotExitPlanModeCoordinatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void RecordExitPlanModeRequest_BuildsEventAndMakesItConsumable()
|
||||
{
|
||||
CopilotExitPlanModeCoordinator coordinator = new();
|
||||
RunTurnCommandDto command = CreateCommand();
|
||||
|
||||
ExitPlanModeRequestedEventDto exitPlanEvent = coordinator.RecordExitPlanModeRequest(
|
||||
command,
|
||||
command.Pattern.Agents[0],
|
||||
new ExitPlanModeRequestedEvent
|
||||
{
|
||||
Data = new ExitPlanModeRequestedData
|
||||
{
|
||||
RequestId = "exit-plan-1",
|
||||
Summary = "Proposed plan",
|
||||
PlanContent = "1. Investigate\n2. Implement",
|
||||
Actions = ["interactive", "autopilot"],
|
||||
RecommendedAction = "interactive",
|
||||
},
|
||||
});
|
||||
|
||||
Assert.Equal("exit-plan-mode-requested", exitPlanEvent.Type);
|
||||
Assert.Equal("turn-1", exitPlanEvent.RequestId);
|
||||
Assert.Equal("session-1", exitPlanEvent.SessionId);
|
||||
Assert.Equal("exit-plan-1", exitPlanEvent.ExitPlanId);
|
||||
Assert.Equal("agent-1", exitPlanEvent.AgentId);
|
||||
Assert.Equal("Primary", exitPlanEvent.AgentName);
|
||||
Assert.Equal("Proposed plan", exitPlanEvent.Summary);
|
||||
Assert.Equal("1. Investigate\n2. Implement", exitPlanEvent.PlanContent);
|
||||
Assert.Equal(["interactive", "autopilot"], exitPlanEvent.Actions);
|
||||
Assert.Equal("interactive", exitPlanEvent.RecommendedAction);
|
||||
|
||||
ExitPlanModeRequestedEventDto? consumed = coordinator.ConsumePendingRequest(command.RequestId);
|
||||
Assert.NotNull(consumed);
|
||||
Assert.Equal("exit-plan-1", consumed!.ExitPlanId);
|
||||
Assert.Null(coordinator.ConsumePendingRequest(command.RequestId));
|
||||
}
|
||||
|
||||
private static RunTurnCommandDto CreateCommand()
|
||||
{
|
||||
return new RunTurnCommandDto
|
||||
{
|
||||
RequestId = "turn-1",
|
||||
SessionId = "session-1",
|
||||
Pattern = new PatternDefinitionDto
|
||||
{
|
||||
Id = "pattern-1",
|
||||
Name = "Plan Mode Pattern",
|
||||
Mode = "single",
|
||||
Availability = "available",
|
||||
Agents =
|
||||
[
|
||||
new PatternAgentDefinitionDto
|
||||
{
|
||||
Id = "agent-1",
|
||||
Name = "Primary",
|
||||
Model = "gpt-5.4",
|
||||
Instructions = "Help with the request.",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using Aryx.AgentHost.Contracts;
|
||||
using Aryx.AgentHost.Services;
|
||||
using GitHub.Copilot.SDK;
|
||||
|
||||
namespace Aryx.AgentHost.Tests;
|
||||
|
||||
public sealed class CopilotMcpOAuthCoordinatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void BuildMcpOauthRequiredEvent_MapsSdkEventToProtocolEvent()
|
||||
{
|
||||
CopilotMcpOAuthCoordinator coordinator = new();
|
||||
RunTurnCommandDto command = CreateCommand();
|
||||
|
||||
McpOauthRequiredEventDto oauthEvent = coordinator.BuildMcpOauthRequiredEvent(
|
||||
command,
|
||||
command.Pattern.Agents[0],
|
||||
new McpOauthRequiredEvent
|
||||
{
|
||||
Data = new McpOauthRequiredData
|
||||
{
|
||||
RequestId = " oauth-request-1 ",
|
||||
ServerName = " Example MCP ",
|
||||
ServerUrl = " https://example.com/mcp ",
|
||||
StaticClientConfig = new McpOauthRequiredDataStaticClientConfig
|
||||
{
|
||||
ClientId = " aryx-client ",
|
||||
PublicClient = true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
Assert.Equal("mcp-oauth-required", oauthEvent.Type);
|
||||
Assert.Equal("turn-1", oauthEvent.RequestId);
|
||||
Assert.Equal("session-1", oauthEvent.SessionId);
|
||||
Assert.Equal("oauth-request-1", oauthEvent.OauthRequestId);
|
||||
Assert.Equal("agent-1", oauthEvent.AgentId);
|
||||
Assert.Equal("Primary", oauthEvent.AgentName);
|
||||
Assert.Equal("Example MCP", oauthEvent.ServerName);
|
||||
Assert.Equal("https://example.com/mcp", oauthEvent.ServerUrl);
|
||||
Assert.NotNull(oauthEvent.StaticClientConfig);
|
||||
Assert.Equal("aryx-client", oauthEvent.StaticClientConfig!.ClientId);
|
||||
Assert.True(oauthEvent.StaticClientConfig.PublicClient);
|
||||
}
|
||||
|
||||
private static RunTurnCommandDto CreateCommand()
|
||||
{
|
||||
return new RunTurnCommandDto
|
||||
{
|
||||
RequestId = "turn-1",
|
||||
SessionId = "session-1",
|
||||
Pattern = new PatternDefinitionDto
|
||||
{
|
||||
Id = "pattern-1",
|
||||
Name = "MCP OAuth Pattern",
|
||||
Mode = "single",
|
||||
Availability = "available",
|
||||
Agents =
|
||||
[
|
||||
new PatternAgentDefinitionDto
|
||||
{
|
||||
Id = "agent-1",
|
||||
Name = "Primary",
|
||||
Model = "gpt-5.4",
|
||||
Instructions = "Help with the request.",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
using System.Text.Json;
|
||||
using Aryx.AgentHost.Contracts;
|
||||
using Aryx.AgentHost.Services;
|
||||
using GitHub.Copilot.SDK;
|
||||
|
||||
namespace Aryx.AgentHost.Tests;
|
||||
|
||||
public sealed class CopilotSessionHooksTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Create_FileBasedPreToolUseDenyOverridesApprovalPolicy()
|
||||
{
|
||||
RunTurnCommandDto command = CreateCommandWithToolApproval();
|
||||
RecordingHookCommandRunner runner = new(
|
||||
[
|
||||
"""{"permissionDecision":"deny","permissionDecisionReason":"Blocked by repository hook"}""",
|
||||
]);
|
||||
ResolvedHookSet configuredHooks = new()
|
||||
{
|
||||
PreToolUse =
|
||||
[
|
||||
CreateHookCommand("deny-pre-tool"),
|
||||
],
|
||||
};
|
||||
|
||||
SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], configuredHooks, runner);
|
||||
|
||||
PreToolUseHookOutput? decision = await hooks.OnPreToolUse!(
|
||||
new PreToolUseHookInput
|
||||
{
|
||||
Timestamp = 1710000000000,
|
||||
Cwd = command.ProjectPath,
|
||||
ToolName = "view",
|
||||
ToolArgs = JsonSerializer.SerializeToElement(new
|
||||
{
|
||||
path = "README.md",
|
||||
}),
|
||||
},
|
||||
null!);
|
||||
|
||||
Assert.Equal("deny", decision?.PermissionDecision);
|
||||
Assert.Equal("Blocked by repository hook", decision?.PermissionDecisionReason);
|
||||
|
||||
RecordedHookInvocation invocation = Assert.Single(runner.Invocations);
|
||||
JsonDocument payload = JsonDocument.Parse(invocation.InputJson);
|
||||
Assert.Equal("view", payload.RootElement.GetProperty("toolName").GetString());
|
||||
Assert.Equal("{\"path\":\"README.md\"}", payload.RootElement.GetProperty("toolArgs").GetString());
|
||||
Assert.Equal(command.ProjectPath, invocation.ProjectPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_PreToolUseFallsThroughWhenFileHooksDoNotDeny()
|
||||
{
|
||||
RunTurnCommandDto command = CreateCommandWithToolApproval();
|
||||
RecordingHookCommandRunner runner = new(
|
||||
[
|
||||
"""{"permissionDecision":"allow"}""",
|
||||
]);
|
||||
ResolvedHookSet configuredHooks = new()
|
||||
{
|
||||
PreToolUse =
|
||||
[
|
||||
CreateHookCommand("allow-pre-tool"),
|
||||
],
|
||||
};
|
||||
|
||||
SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], configuredHooks, runner);
|
||||
|
||||
PreToolUseHookOutput? decision = await hooks.OnPreToolUse!(
|
||||
new PreToolUseHookInput
|
||||
{
|
||||
ToolName = "view",
|
||||
},
|
||||
null!);
|
||||
|
||||
Assert.Equal("ask", decision?.PermissionDecision);
|
||||
Assert.Single(runner.Invocations);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_PreToolUseIgnoresInvalidHookOutputAndFallsThrough()
|
||||
{
|
||||
RunTurnCommandDto command = CreateCommandWithToolApproval();
|
||||
RecordingHookCommandRunner runner = new(
|
||||
[
|
||||
"not-json",
|
||||
]);
|
||||
ResolvedHookSet configuredHooks = new()
|
||||
{
|
||||
PreToolUse =
|
||||
[
|
||||
CreateHookCommand("invalid-pre-tool"),
|
||||
],
|
||||
};
|
||||
|
||||
SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], configuredHooks, runner);
|
||||
|
||||
PreToolUseHookOutput? decision = await hooks.OnPreToolUse!(
|
||||
new PreToolUseHookInput
|
||||
{
|
||||
ToolName = "view",
|
||||
},
|
||||
null!);
|
||||
|
||||
Assert.Equal("ask", decision?.PermissionDecision);
|
||||
Assert.Single(runner.Invocations);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("ask_user")]
|
||||
[InlineData("report_intent")]
|
||||
[InlineData("task_complete")]
|
||||
[InlineData("handoff_to_2")]
|
||||
[InlineData("handoff_to_specialist")]
|
||||
public async Task Create_PreToolUseAutoAllowsInfrastructureTools(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_RunsConfiguredNonPreToolHooks()
|
||||
{
|
||||
RunTurnCommandDto command = CreateCommandWithoutApprovalRules();
|
||||
RecordingHookCommandRunner runner = new();
|
||||
ResolvedHookSet configuredHooks = new()
|
||||
{
|
||||
SessionStart = [CreateHookCommand("session-start-hook")],
|
||||
UserPromptSubmitted = [CreateHookCommand("prompt-hook")],
|
||||
PostToolUse = [CreateHookCommand("post-tool-hook")],
|
||||
SessionEnd = [CreateHookCommand("session-end-hook")],
|
||||
ErrorOccurred = [CreateHookCommand("error-hook")],
|
||||
};
|
||||
|
||||
SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], configuredHooks, runner);
|
||||
|
||||
await hooks.OnSessionStart!(
|
||||
new SessionStartHookInput
|
||||
{
|
||||
Timestamp = 1,
|
||||
Cwd = command.ProjectPath,
|
||||
Source = "new",
|
||||
InitialPrompt = "Create the feature",
|
||||
},
|
||||
null!);
|
||||
await hooks.OnUserPromptSubmitted!(
|
||||
new UserPromptSubmittedHookInput
|
||||
{
|
||||
Timestamp = 2,
|
||||
Cwd = command.ProjectPath,
|
||||
Prompt = "Refactor the API",
|
||||
},
|
||||
null!);
|
||||
await hooks.OnPostToolUse!(
|
||||
new PostToolUseHookInput
|
||||
{
|
||||
Timestamp = 3,
|
||||
Cwd = command.ProjectPath,
|
||||
ToolName = "view",
|
||||
ToolArgs = JsonSerializer.SerializeToElement(new
|
||||
{
|
||||
path = "README.md",
|
||||
}),
|
||||
ToolResult = JsonSerializer.SerializeToElement(new
|
||||
{
|
||||
resultType = "success",
|
||||
textResultForLlm = "Read 1 file",
|
||||
}),
|
||||
},
|
||||
null!);
|
||||
await hooks.OnSessionEnd!(
|
||||
new SessionEndHookInput
|
||||
{
|
||||
Timestamp = 4,
|
||||
Cwd = command.ProjectPath,
|
||||
Reason = "complete",
|
||||
FinalMessage = "Done",
|
||||
},
|
||||
null!);
|
||||
await hooks.OnErrorOccurred!(
|
||||
new ErrorOccurredHookInput
|
||||
{
|
||||
Timestamp = 5,
|
||||
Cwd = command.ProjectPath,
|
||||
Error = "Network timeout",
|
||||
ErrorContext = "tool_execution",
|
||||
Recoverable = true,
|
||||
},
|
||||
null!);
|
||||
|
||||
Assert.Equal(
|
||||
["session-start-hook", "prompt-hook", "post-tool-hook", "session-end-hook", "error-hook"],
|
||||
runner.Invocations.Select(invocation => GetCommandText(invocation.Hook)).ToArray());
|
||||
|
||||
JsonDocument postToolPayload = JsonDocument.Parse(runner.Invocations[2].InputJson);
|
||||
Assert.Equal("view", postToolPayload.RootElement.GetProperty("toolName").GetString());
|
||||
Assert.Equal("success", postToolPayload.RootElement.GetProperty("toolResult").GetProperty("resultType").GetString());
|
||||
|
||||
JsonDocument errorPayload = JsonDocument.Parse(runner.Invocations[4].InputJson);
|
||||
Assert.Equal("Network timeout", errorPayload.RootElement.GetProperty("error").GetProperty("message").GetString());
|
||||
Assert.Equal("tool_execution", errorPayload.RootElement.GetProperty("error").GetProperty("context").GetString());
|
||||
Assert.True(errorPayload.RootElement.GetProperty("error").GetProperty("recoverable").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_WithoutConfiguredFileHooksPreservesExistingApprovalBehavior()
|
||||
{
|
||||
RunTurnCommandDto command = CreateCommandWithoutApprovalRules();
|
||||
SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], ResolvedHookSet.Empty, new RecordingHookCommandRunner());
|
||||
|
||||
PreToolUseHookOutput? decision = await hooks.OnPreToolUse!(
|
||||
new PreToolUseHookInput
|
||||
{
|
||||
ToolName = "view",
|
||||
},
|
||||
null!);
|
||||
|
||||
Assert.Equal("allow", decision?.PermissionDecision);
|
||||
}
|
||||
|
||||
private static RunTurnCommandDto CreateCommandWithToolApproval()
|
||||
{
|
||||
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"],
|
||||
},
|
||||
],
|
||||
},
|
||||
Agents =
|
||||
[
|
||||
new PatternAgentDefinitionDto
|
||||
{
|
||||
Id = "agent-1",
|
||||
Name = "Primary",
|
||||
Model = "gpt-5.4",
|
||||
Instructions = "Help.",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private static RunTurnCommandDto CreateCommandWithoutApprovalRules()
|
||||
{
|
||||
RunTurnCommandDto command = CreateCommandWithToolApproval();
|
||||
return new RunTurnCommandDto
|
||||
{
|
||||
RequestId = command.RequestId,
|
||||
SessionId = command.SessionId,
|
||||
ProjectPath = command.ProjectPath,
|
||||
Pattern = new PatternDefinitionDto
|
||||
{
|
||||
Id = command.Pattern.Id,
|
||||
Name = command.Pattern.Name,
|
||||
Mode = command.Pattern.Mode,
|
||||
Availability = command.Pattern.Availability,
|
||||
ApprovalPolicy = new ApprovalPolicyDto(),
|
||||
Agents = command.Pattern.Agents,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private static HookCommandDefinition CreateHookCommand(string name)
|
||||
=> new()
|
||||
{
|
||||
Type = "command",
|
||||
Bash = name,
|
||||
PowerShell = name,
|
||||
};
|
||||
|
||||
private static string GetCommandText(HookCommandDefinition hook)
|
||||
=> hook.PowerShell ?? hook.Bash ?? string.Empty;
|
||||
|
||||
private sealed class RecordingHookCommandRunner : IHookCommandRunner
|
||||
{
|
||||
private readonly Queue<string?> _outputs;
|
||||
|
||||
public List<RecordedHookInvocation> Invocations { get; } = [];
|
||||
|
||||
public RecordingHookCommandRunner(IEnumerable<string?>? outputs = null)
|
||||
{
|
||||
_outputs = outputs is null ? new Queue<string?>() : new Queue<string?>(outputs);
|
||||
}
|
||||
|
||||
public Task<string?> RunAsync(
|
||||
HookCommandDefinition hook,
|
||||
string inputJson,
|
||||
string projectPath,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Invocations.Add(new RecordedHookInvocation(hook, inputJson, projectPath));
|
||||
return Task.FromResult(_outputs.Count > 0 ? _outputs.Dequeue() : string.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record RecordedHookInvocation(
|
||||
HookCommandDefinition Hook,
|
||||
string InputJson,
|
||||
string ProjectPath);
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
using Aryx.AgentHost.Contracts;
|
||||
using Aryx.AgentHost.Services;
|
||||
using GitHub.Copilot.SDK;
|
||||
|
||||
namespace Aryx.AgentHost.Tests;
|
||||
|
||||
public sealed class CopilotTurnExecutionStateTests
|
||||
{
|
||||
[Fact]
|
||||
public void ObserveSessionEvent_McpOauthRequired_SetsActiveAgent()
|
||||
{
|
||||
RunTurnCommandDto command = CreateCommand();
|
||||
CopilotTurnExecutionState state = new(command);
|
||||
|
||||
state.ObserveSessionEvent(
|
||||
command.Pattern.Agents[0],
|
||||
new McpOauthRequiredEvent
|
||||
{
|
||||
Data = new McpOauthRequiredData
|
||||
{
|
||||
RequestId = "oauth-request-1",
|
||||
ServerName = "Example MCP",
|
||||
ServerUrl = "https://example.com/mcp",
|
||||
},
|
||||
});
|
||||
|
||||
Assert.True(state.ActiveAgent.HasValue);
|
||||
Assert.Equal("agent-1", state.ActiveAgent.Value.AgentId);
|
||||
Assert.Equal("Primary", state.ActiveAgent.Value.AgentName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ObserveSessionEvent_AssistantMessageDelta_QueuesThinkingActivity()
|
||||
{
|
||||
RunTurnCommandDto command = CreateCommand();
|
||||
CopilotTurnExecutionState state = new(command);
|
||||
|
||||
state.ObserveSessionEvent(
|
||||
command.Pattern.Agents[0],
|
||||
SessionEvent.FromJson(
|
||||
"""
|
||||
{
|
||||
"type": "assistant.message_delta",
|
||||
"data": {
|
||||
"messageId": "msg-1",
|
||||
"deltaContent": "Hello"
|
||||
},
|
||||
"id": "11111111-1111-1111-1111-111111111111",
|
||||
"timestamp": "2026-03-27T00:00:00Z"
|
||||
}
|
||||
"""));
|
||||
|
||||
AgentActivityEventDto activity = Assert.Single(state.DrainPendingEvents().OfType<AgentActivityEventDto>());
|
||||
Assert.Equal("thinking", activity.ActivityType);
|
||||
Assert.Equal("agent-1", activity.AgentId);
|
||||
Assert.Equal("Primary", activity.AgentName);
|
||||
Assert.True(state.TryResolveObservedAgentForMessage("msg-1", out AgentIdentity observedAgent));
|
||||
Assert.Equal("agent-1", observedAgent.AgentId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ObserveSessionEvent_ToolExecutionStart_TracksToolNameByCallId()
|
||||
{
|
||||
RunTurnCommandDto command = CreateCommand();
|
||||
CopilotTurnExecutionState state = new(command);
|
||||
|
||||
state.ObserveSessionEvent(
|
||||
command.Pattern.Agents[0],
|
||||
SessionEvent.FromJson(
|
||||
"""
|
||||
{
|
||||
"type": "tool.execution_start",
|
||||
"data": {
|
||||
"toolCallId": "tool-call-1",
|
||||
"toolName": "view"
|
||||
},
|
||||
"id": "33333333-3333-3333-3333-333333333333",
|
||||
"timestamp": "2026-03-27T00:00:00Z"
|
||||
}
|
||||
"""));
|
||||
|
||||
Assert.True(state.ToolNamesByCallId.TryGetValue("tool-call-1", out string? toolName));
|
||||
Assert.Equal("view", toolName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EmitThinkingIfNeeded_DoesNotDuplicateQueuedThinkingActivity()
|
||||
{
|
||||
RunTurnCommandDto command = CreateCommand();
|
||||
CopilotTurnExecutionState state = new(command);
|
||||
|
||||
state.ObserveSessionEvent(
|
||||
command.Pattern.Agents[0],
|
||||
SessionEvent.FromJson(
|
||||
"""
|
||||
{
|
||||
"type": "assistant.reasoning_delta",
|
||||
"data": {
|
||||
"reasoningId": "reasoning-1",
|
||||
"deltaContent": "Planning"
|
||||
},
|
||||
"id": "22222222-2222-2222-2222-222222222222",
|
||||
"timestamp": "2026-03-27T00:00:00Z"
|
||||
}
|
||||
"""));
|
||||
|
||||
List<AgentActivityEventDto> activities = [.. state.DrainPendingEvents().OfType<AgentActivityEventDto>()];
|
||||
|
||||
await state.EmitThinkingIfNeeded(
|
||||
new AgentIdentity("agent-1", "Primary"),
|
||||
sidecarEvent =>
|
||||
{
|
||||
activities.Add(Assert.IsType<AgentActivityEventDto>(sidecarEvent));
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
|
||||
AgentActivityEventDto thinking = Assert.Single(activities);
|
||||
Assert.Equal("thinking", thinking.ActivityType);
|
||||
Assert.Equal("agent-1", thinking.AgentId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DrainPendingMcpOauthRequests_ReturnsQueuedRequestsAndClearsQueue()
|
||||
{
|
||||
RunTurnCommandDto command = CreateCommand();
|
||||
CopilotTurnExecutionState state = new(command);
|
||||
McpOauthRequiredEventDto request = new()
|
||||
{
|
||||
Type = "mcp-oauth-required",
|
||||
RequestId = command.RequestId,
|
||||
SessionId = command.SessionId,
|
||||
OauthRequestId = "oauth-request-1",
|
||||
ServerName = "Example MCP",
|
||||
ServerUrl = "https://example.com/mcp",
|
||||
};
|
||||
|
||||
state.EnqueuePendingMcpOauthRequest(request);
|
||||
|
||||
IReadOnlyList<McpOauthRequiredEventDto> firstDrain = state.DrainPendingMcpOauthRequests();
|
||||
IReadOnlyList<McpOauthRequiredEventDto> secondDrain = state.DrainPendingMcpOauthRequests();
|
||||
|
||||
McpOauthRequiredEventDto drained = Assert.Single(firstDrain);
|
||||
Assert.Equal("oauth-request-1", drained.OauthRequestId);
|
||||
Assert.Empty(secondDrain);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ObserveSessionEvent_SubagentStarted_QueuesSubagentEvent()
|
||||
{
|
||||
RunTurnCommandDto command = CreateCommand();
|
||||
CopilotTurnExecutionState state = new(command);
|
||||
|
||||
state.ObserveSessionEvent(
|
||||
command.Pattern.Agents[0],
|
||||
SessionEvent.FromJson(
|
||||
"""
|
||||
{
|
||||
"type": "subagent.started",
|
||||
"data": {
|
||||
"toolCallId": "tool-call-1",
|
||||
"agentName": "designer",
|
||||
"agentDisplayName": "Designer",
|
||||
"agentDescription": "Design specialist"
|
||||
},
|
||||
"id": "44444444-4444-4444-4444-444444444444",
|
||||
"timestamp": "2026-03-27T00:00:00Z"
|
||||
}
|
||||
"""));
|
||||
|
||||
SubagentEventDto evt = Assert.Single(state.DrainPendingEvents().OfType<SubagentEventDto>());
|
||||
Assert.Equal("started", evt.EventKind);
|
||||
Assert.Equal("tool-call-1", evt.ToolCallId);
|
||||
Assert.Equal("designer", evt.CustomAgentName);
|
||||
Assert.Equal("Designer", evt.CustomAgentDisplayName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ObserveSessionEvent_SkillInvoked_QueuesSkillEvent()
|
||||
{
|
||||
RunTurnCommandDto command = CreateCommand();
|
||||
CopilotTurnExecutionState state = new(command);
|
||||
|
||||
state.ObserveSessionEvent(
|
||||
command.Pattern.Agents[0],
|
||||
SessionEvent.FromJson(
|
||||
"""
|
||||
{
|
||||
"type": "skill.invoked",
|
||||
"data": {
|
||||
"name": "reviewer",
|
||||
"path": "C:\\skills\\reviewer\\SKILL.md",
|
||||
"content": "# Reviewer",
|
||||
"allowedTools": ["view"],
|
||||
"pluginName": "aryx-plugin",
|
||||
"pluginVersion": "1.0.0"
|
||||
},
|
||||
"id": "55555555-5555-5555-5555-555555555555",
|
||||
"timestamp": "2026-03-27T00:00:00Z"
|
||||
}
|
||||
"""));
|
||||
|
||||
SkillInvokedEventDto evt = Assert.Single(state.DrainPendingEvents().OfType<SkillInvokedEventDto>());
|
||||
Assert.Equal("reviewer", evt.SkillName);
|
||||
Assert.Equal(@"C:\skills\reviewer\SKILL.md", evt.Path);
|
||||
Assert.Equal(["view"], evt.AllowedTools);
|
||||
Assert.Equal("aryx-plugin", evt.PluginName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ObserveSessionEvent_HookStart_QueuesHookLifecycleEvent()
|
||||
{
|
||||
RunTurnCommandDto command = CreateCommand();
|
||||
CopilotTurnExecutionState state = new(command);
|
||||
|
||||
state.ObserveSessionEvent(command.Pattern.Agents[0], CreateHookStartEvent());
|
||||
|
||||
HookLifecycleEventDto evt = Assert.Single(state.DrainPendingEvents().OfType<HookLifecycleEventDto>());
|
||||
Assert.Equal("start", evt.Phase);
|
||||
Assert.Equal("postToolUse", evt.HookType);
|
||||
Assert.Equal("hook-1", evt.HookInvocationId);
|
||||
Assert.NotNull(evt.Input);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ObserveSessionEvent_HookEnd_QueuesHookLifecycleEvent()
|
||||
{
|
||||
RunTurnCommandDto command = CreateCommand();
|
||||
CopilotTurnExecutionState state = new(command);
|
||||
|
||||
state.ObserveSessionEvent(command.Pattern.Agents[0], CreateHookEndEvent());
|
||||
|
||||
HookLifecycleEventDto evt = Assert.Single(state.DrainPendingEvents().OfType<HookLifecycleEventDto>());
|
||||
Assert.Equal("end", evt.Phase);
|
||||
Assert.Equal("postToolUse", evt.HookType);
|
||||
Assert.Equal("hook-1", evt.HookInvocationId);
|
||||
Assert.True(evt.Success);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ObserveSessionEvent_HookLifecycleEvents_AreSuppressedWhenConfigured()
|
||||
{
|
||||
RunTurnCommandDto command = CreateCommand();
|
||||
CopilotTurnExecutionState state = new(command)
|
||||
{
|
||||
SuppressHookLifecycleEvents = true,
|
||||
};
|
||||
|
||||
state.ObserveSessionEvent(command.Pattern.Agents[0], CreateHookStartEvent());
|
||||
state.ObserveSessionEvent(command.Pattern.Agents[0], CreateHookEndEvent());
|
||||
|
||||
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()
|
||||
{
|
||||
RunTurnCommandDto command = CreateCommand();
|
||||
CopilotTurnExecutionState state = new(command);
|
||||
|
||||
state.ObserveSessionEvent(
|
||||
command.Pattern.Agents[0],
|
||||
SessionEvent.FromJson(
|
||||
"""
|
||||
{
|
||||
"type": "session.compaction_complete",
|
||||
"data": {
|
||||
"success": true,
|
||||
"preCompactionTokens": 1000,
|
||||
"postCompactionTokens": 400,
|
||||
"messagesRemoved": 8,
|
||||
"tokensRemoved": 600,
|
||||
"summaryContent": "Compacted summary",
|
||||
"checkpointNumber": 2,
|
||||
"checkpointPath": "C:\\Users\\me\\.copilot\\session-state\\checkpoint-2.json"
|
||||
},
|
||||
"id": "77777777-7777-7777-7777-777777777777",
|
||||
"timestamp": "2026-03-27T00:00:00Z"
|
||||
}
|
||||
"""));
|
||||
|
||||
SessionCompactionEventDto evt = Assert.Single(state.DrainPendingEvents().OfType<SessionCompactionEventDto>());
|
||||
Assert.Equal("complete", evt.Phase);
|
||||
Assert.True(evt.Success);
|
||||
Assert.Equal(1000, evt.PreCompactionTokens);
|
||||
Assert.Equal(400, evt.PostCompactionTokens);
|
||||
Assert.Equal("Compacted summary", evt.SummaryContent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ObserveSessionEvent_PendingMessagesModified_QueuesPendingMessageSignal()
|
||||
{
|
||||
RunTurnCommandDto command = CreateCommand();
|
||||
CopilotTurnExecutionState state = new(command);
|
||||
|
||||
state.ObserveSessionEvent(
|
||||
command.Pattern.Agents[0],
|
||||
SessionEvent.FromJson(
|
||||
"""
|
||||
{
|
||||
"type": "pending_messages.modified",
|
||||
"data": {},
|
||||
"id": "88888888-8888-8888-8888-888888888888",
|
||||
"timestamp": "2026-03-27T00:00:00Z"
|
||||
}
|
||||
"""));
|
||||
|
||||
PendingMessagesModifiedEventDto evt = Assert.Single(state.DrainPendingEvents().OfType<PendingMessagesModifiedEventDto>());
|
||||
Assert.Equal("session-1", evt.SessionId);
|
||||
Assert.Equal("agent-1", evt.AgentId);
|
||||
}
|
||||
|
||||
private static SessionEvent CreateHookStartEvent()
|
||||
{
|
||||
return SessionEvent.FromJson(
|
||||
"""
|
||||
{
|
||||
"type": "hook.start",
|
||||
"data": {
|
||||
"hookInvocationId": "hook-1",
|
||||
"hookType": "postToolUse",
|
||||
"input": {
|
||||
"toolName": "view"
|
||||
}
|
||||
},
|
||||
"id": "66666666-6666-6666-6666-666666666666",
|
||||
"timestamp": "2026-03-27T00:00:00Z"
|
||||
}
|
||||
""");
|
||||
}
|
||||
|
||||
private static SessionEvent CreateHookEndEvent()
|
||||
{
|
||||
return SessionEvent.FromJson(
|
||||
"""
|
||||
{
|
||||
"type": "hook.end",
|
||||
"data": {
|
||||
"hookInvocationId": "hook-1",
|
||||
"hookType": "postToolUse",
|
||||
"success": true,
|
||||
"output": {
|
||||
"status": "ok"
|
||||
}
|
||||
},
|
||||
"id": "99999999-9999-9999-9999-999999999999",
|
||||
"timestamp": "2026-03-27T00:00:00Z"
|
||||
}
|
||||
""");
|
||||
}
|
||||
|
||||
private static RunTurnCommandDto CreateCommand()
|
||||
{
|
||||
return new RunTurnCommandDto
|
||||
{
|
||||
RequestId = "turn-1",
|
||||
SessionId = "session-1",
|
||||
Pattern = new PatternDefinitionDto
|
||||
{
|
||||
Id = "pattern-1",
|
||||
Name = "MCP OAuth Pattern",
|
||||
Mode = "single",
|
||||
Availability = "available",
|
||||
Agents =
|
||||
[
|
||||
new PatternAgentDefinitionDto
|
||||
{
|
||||
Id = "agent-1",
|
||||
Name = "Primary",
|
||||
Model = "gpt-5.4",
|
||||
Instructions = "Help with the request.",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
using Aryx.AgentHost.Contracts;
|
||||
using Aryx.AgentHost.Services;
|
||||
using GitHub.Copilot.SDK;
|
||||
|
||||
namespace Aryx.AgentHost.Tests;
|
||||
|
||||
public sealed class CopilotUserInputCoordinatorTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task RequestUserInputAsync_RaisesUserInputEventAndCompletesAfterResolution()
|
||||
{
|
||||
CopilotUserInputCoordinator coordinator = new();
|
||||
UserInputRequestedEventDto? observedEvent = null;
|
||||
RunTurnCommandDto command = CreateUserInputCommand();
|
||||
|
||||
Task<UserInputResponse> pending = coordinator.RequestUserInputAsync(
|
||||
command,
|
||||
command.Pattern.Agents[0],
|
||||
new UserInputRequest
|
||||
{
|
||||
Question = "How should I proceed?",
|
||||
Choices = ["Continue", "Stop"],
|
||||
AllowFreeform = true,
|
||||
},
|
||||
new UserInputInvocation
|
||||
{
|
||||
SessionId = "copilot-session-1",
|
||||
},
|
||||
userInputEvent =>
|
||||
{
|
||||
observedEvent = userInputEvent;
|
||||
return Task.CompletedTask;
|
||||
},
|
||||
CancellationToken.None);
|
||||
|
||||
Assert.False(pending.IsCompleted);
|
||||
Assert.NotNull(observedEvent);
|
||||
Assert.Equal("user-input-requested", observedEvent!.Type);
|
||||
Assert.Equal("turn-1", observedEvent.RequestId);
|
||||
Assert.Equal("session-1", observedEvent.SessionId);
|
||||
Assert.Equal("agent-1", observedEvent.AgentId);
|
||||
Assert.Equal("Primary", observedEvent.AgentName);
|
||||
Assert.Equal("How should I proceed?", observedEvent.Question);
|
||||
Assert.Equal(["Continue", "Stop"], observedEvent.Choices);
|
||||
Assert.True(observedEvent.AllowFreeform);
|
||||
|
||||
await coordinator.ResolveUserInputAsync(
|
||||
new ResolveUserInputCommandDto
|
||||
{
|
||||
UserInputId = observedEvent.UserInputId,
|
||||
Answer = "Continue",
|
||||
WasFreeform = false,
|
||||
},
|
||||
CancellationToken.None);
|
||||
|
||||
UserInputResponse response = await pending;
|
||||
Assert.Equal("Continue", response.Answer);
|
||||
Assert.False(response.WasFreeform);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveUserInputAsync_RejectsUnknownUserInputIds()
|
||||
{
|
||||
CopilotUserInputCoordinator coordinator = new();
|
||||
|
||||
InvalidOperationException error = await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
coordinator.ResolveUserInputAsync(
|
||||
new ResolveUserInputCommandDto
|
||||
{
|
||||
UserInputId = "user-input-missing",
|
||||
Answer = "Continue",
|
||||
WasFreeform = false,
|
||||
},
|
||||
CancellationToken.None));
|
||||
|
||||
Assert.Contains("is not pending", error.Message);
|
||||
}
|
||||
|
||||
private static PatternAgentDefinitionDto CreateAgent(string id, string name)
|
||||
{
|
||||
return new PatternAgentDefinitionDto
|
||||
{
|
||||
Id = id,
|
||||
Name = name,
|
||||
Model = "gpt-5.4",
|
||||
Instructions = "Help with the request.",
|
||||
};
|
||||
}
|
||||
|
||||
private static RunTurnCommandDto CreateUserInputCommand()
|
||||
{
|
||||
return new RunTurnCommandDto
|
||||
{
|
||||
RequestId = "turn-1",
|
||||
SessionId = "session-1",
|
||||
Pattern = new PatternDefinitionDto
|
||||
{
|
||||
Id = "pattern-1",
|
||||
Name = "User Input Pattern",
|
||||
Mode = "single",
|
||||
Availability = "available",
|
||||
Agents =
|
||||
[
|
||||
CreateAgent("agent-1", "Primary"),
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,28 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using Aryx.AgentHost.Contracts;
|
||||
using Aryx.AgentHost.Services;
|
||||
using GitHub.Copilot.SDK;
|
||||
using Microsoft.Agents.AI;
|
||||
using Microsoft.Agents.AI.Workflows;
|
||||
using Microsoft.Extensions.AI;
|
||||
|
||||
namespace Aryx.AgentHost.Tests;
|
||||
|
||||
public sealed class CopilotWorkflowRunnerTests
|
||||
{
|
||||
[Fact]
|
||||
public void ConfigureHookLifecycleEventSuppression_SetsStateFromBundle()
|
||||
{
|
||||
RunTurnCommandDto command = CreateApprovalCommand();
|
||||
CopilotTurnExecutionState state = new(command);
|
||||
CopilotAgentBundle bundle = new(Array.Empty<AIAgent>(), hasConfiguredHooks: false);
|
||||
|
||||
CopilotWorkflowRunner.ConfigureHookLifecycleEventSuppression(state, bundle);
|
||||
|
||||
Assert.True(state.SuppressHookLifecycleEvents);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SelectNewOutputMessages_SkipsFullTranscriptPrefix()
|
||||
{
|
||||
@@ -156,6 +172,50 @@ public sealed class CopilotWorkflowRunnerTests
|
||||
Assert.Equal("Hello", message.Content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProjectCompletedMessages_UsesFinalAssistantPayloadWhenStreamingTextIsMissing()
|
||||
{
|
||||
RunTurnCommandDto command = new()
|
||||
{
|
||||
RequestId = "turn-1",
|
||||
SessionId = "session-1",
|
||||
Pattern = new PatternDefinitionDto
|
||||
{
|
||||
Id = "pattern-single",
|
||||
Name = "Single Agent",
|
||||
Mode = "single",
|
||||
Availability = "available",
|
||||
Agents =
|
||||
[
|
||||
CreateAgent(id: "agent-single-primary", name: "Primary Agent"),
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
IReadOnlyList<ChatMessageDto> messages = WorkflowTranscriptProjector.ProjectCompletedMessages(
|
||||
command,
|
||||
[
|
||||
new ChatMessage(ChatRole.Assistant, string.Empty)
|
||||
{
|
||||
MessageId = "msg-1",
|
||||
RawRepresentation = new AssistantMessageEvent
|
||||
{
|
||||
Data = new AssistantMessageData
|
||||
{
|
||||
MessageId = "msg-1",
|
||||
Content = "Hello from the final assistant payload.",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
[]);
|
||||
|
||||
ChatMessageDto message = Assert.Single(messages);
|
||||
Assert.Equal("msg-1", message.Id);
|
||||
Assert.Equal("Primary Agent", message.AuthorName);
|
||||
Assert.Equal("Hello from the final assistant payload.", message.Content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProjectCompletedMessages_PreservesSequentialConversationHistory()
|
||||
{
|
||||
@@ -645,6 +705,9 @@ public sealed class CopilotWorkflowRunnerTests
|
||||
Assert.Equal("agent-handoff-ux", observedAgent.AgentId);
|
||||
Assert.Equal("UX Specialist", observedAgent.AgentName);
|
||||
Assert.Equal("agent-handoff-ux", state.ActiveAgent?.AgentId);
|
||||
AgentActivityEventDto activity = Assert.Single(state.DrainPendingEvents().OfType<AgentActivityEventDto>());
|
||||
Assert.Equal("thinking", activity.ActivityType);
|
||||
Assert.Equal("agent-handoff-ux", activity.AgentId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -668,6 +731,71 @@ public sealed class CopilotWorkflowRunnerTests
|
||||
|
||||
Assert.Equal("agent-handoff-ux", state.ActiveAgent?.AgentId);
|
||||
Assert.Equal("UX Specialist", state.ActiveAgent?.AgentName);
|
||||
AgentActivityEventDto activity = Assert.Single(state.DrainPendingEvents().OfType<AgentActivityEventDto>());
|
||||
Assert.Equal("thinking", activity.ActivityType);
|
||||
Assert.Equal("agent-handoff-ux", activity.AgentId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleWorkflowEventAsync_EmitsThinkingForHandoffTargets()
|
||||
{
|
||||
RunTurnCommandDto command = CreateHandoffCommand();
|
||||
CopilotTurnExecutionState state = new(command);
|
||||
state.ObserveSessionEvent(
|
||||
CreateAgent("agent-handoff-triage", "Triage"),
|
||||
SessionEvent.FromJson(
|
||||
"""
|
||||
{
|
||||
"type": "assistant.reasoning_delta",
|
||||
"data": {
|
||||
"reasoningId": "reasoning-1",
|
||||
"deltaContent": "Delegating."
|
||||
},
|
||||
"id": "33333333-3333-3333-3333-333333333333",
|
||||
"timestamp": "2026-03-27T00:00:00Z"
|
||||
}
|
||||
"""));
|
||||
_ = state.DrainPendingEvents();
|
||||
RequestInfoEvent requestInfo = CreateRequestInfoEvent(
|
||||
CreateHandoffTarget("agent-handoff-ux", "UX Specialist"));
|
||||
List<AgentActivityEventDto> activities = [];
|
||||
|
||||
MethodInfo handleWorkflowEvent = typeof(CopilotWorkflowRunner).GetMethod(
|
||||
"HandleWorkflowEventAsync",
|
||||
BindingFlags.NonPublic | BindingFlags.Static)!;
|
||||
Task<bool> handleTask = (Task<bool>)handleWorkflowEvent.Invoke(
|
||||
null,
|
||||
[
|
||||
command,
|
||||
requestInfo,
|
||||
Array.Empty<ChatMessage>(),
|
||||
state,
|
||||
(Func<TurnDeltaEventDto, Task>)(_ => Task.CompletedTask),
|
||||
(Func<SidecarEventDto, Task>)(sidecarEvent =>
|
||||
{
|
||||
activities.Add(Assert.IsType<AgentActivityEventDto>(sidecarEvent));
|
||||
return Task.CompletedTask;
|
||||
}),
|
||||
])!;
|
||||
|
||||
bool shouldEndTurn = await handleTask;
|
||||
|
||||
Assert.False(shouldEndTurn);
|
||||
Assert.Collection(
|
||||
activities,
|
||||
handoff =>
|
||||
{
|
||||
Assert.Equal("handoff", handoff.ActivityType);
|
||||
Assert.Equal("agent-handoff-ux", handoff.AgentId);
|
||||
Assert.Equal("UX Specialist", handoff.AgentName);
|
||||
Assert.Equal("agent-handoff-triage", handoff.SourceAgentId);
|
||||
},
|
||||
thinking =>
|
||||
{
|
||||
Assert.Equal("thinking", thinking.ActivityType);
|
||||
Assert.Equal("agent-handoff-ux", thinking.AgentId);
|
||||
Assert.Equal("UX Specialist", thinking.AgentName);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -694,7 +822,59 @@ public sealed class CopilotWorkflowRunnerTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryGetApprovalToolName_ReadsMcpCustomAndHookRequests()
|
||||
public void RequiresToolCallApproval_HonorsRuntimeApprovalAliases()
|
||||
{
|
||||
ApprovalPolicyDto policy = new()
|
||||
{
|
||||
Rules =
|
||||
[
|
||||
new ApprovalCheckpointRuleDto
|
||||
{
|
||||
Kind = "tool-call",
|
||||
AgentIds = ["agent-1"],
|
||||
},
|
||||
],
|
||||
AutoApprovedToolNames = ["read", "store_memory"],
|
||||
};
|
||||
|
||||
Assert.False(CopilotApprovalCoordinator.RequiresToolCallApproval(policy, "agent-1", "view", "read"));
|
||||
Assert.False(CopilotApprovalCoordinator.RequiresToolCallApproval(policy, "agent-1", "remember_fact", "store_memory"));
|
||||
Assert.True(CopilotApprovalCoordinator.RequiresToolCallApproval(policy, "agent-1", "write_file", "write"));
|
||||
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()
|
||||
{
|
||||
Assert.True(
|
||||
CopilotApprovalCoordinator.TryGetApprovalToolName(
|
||||
@@ -732,7 +912,7 @@ public sealed class CopilotWorkflowRunnerTests
|
||||
out string? hookToolName));
|
||||
Assert.Equal("web_fetch", hookToolName);
|
||||
|
||||
Assert.False(
|
||||
Assert.True(
|
||||
CopilotApprovalCoordinator.TryGetApprovalToolName(
|
||||
new PermissionRequestShell
|
||||
{
|
||||
@@ -746,7 +926,49 @@ public sealed class CopilotWorkflowRunnerTests
|
||||
CanOfferSessionApproval = false,
|
||||
},
|
||||
out string? shellToolName));
|
||||
Assert.Null(shellToolName);
|
||||
Assert.Equal("shell", shellToolName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryGetApprovalToolName_FallsBackToRuntimeApprovalAliasesWhenLookupMissing()
|
||||
{
|
||||
Assert.True(
|
||||
CopilotApprovalCoordinator.TryGetApprovalToolName(
|
||||
new PermissionRequestRead
|
||||
{
|
||||
Kind = "read",
|
||||
ToolCallId = "tool-call-read",
|
||||
Intention = "Inspect a file",
|
||||
Path = "README.md",
|
||||
},
|
||||
out string? readToolName));
|
||||
Assert.Equal("read", readToolName);
|
||||
|
||||
Assert.True(
|
||||
CopilotApprovalCoordinator.TryGetApprovalToolName(
|
||||
new PermissionRequestWrite
|
||||
{
|
||||
Kind = "write",
|
||||
ToolCallId = "tool-call-write",
|
||||
Intention = "Update a file",
|
||||
FileName = "README.md",
|
||||
Diff = "@@ -1 +1 @@",
|
||||
},
|
||||
out string? writeToolName));
|
||||
Assert.Equal("write", writeToolName);
|
||||
|
||||
Assert.True(
|
||||
CopilotApprovalCoordinator.TryGetApprovalToolName(
|
||||
new PermissionRequestMemory
|
||||
{
|
||||
Kind = "memory",
|
||||
ToolCallId = "tool-call-memory",
|
||||
Subject = "repo conventions",
|
||||
Fact = "Use Bun for script execution.",
|
||||
Citations = "package.json",
|
||||
},
|
||||
out string? memoryToolName));
|
||||
Assert.Equal("store_memory", memoryToolName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -876,6 +1098,9 @@ public sealed class CopilotWorkflowRunnerTests
|
||||
Assert.Equal("lsp_ts_hover", approvalEvent.ToolName);
|
||||
Assert.Equal("Approve lsp_ts_hover", approvalEvent.Title);
|
||||
Assert.Contains("tool \"lsp_ts_hover\"", approvalEvent.Detail);
|
||||
Assert.NotNull(approvalEvent.PermissionDetail);
|
||||
Assert.Equal("custom-tool", approvalEvent.PermissionDetail!.Kind);
|
||||
Assert.Equal("Hover information", approvalEvent.PermissionDetail.ToolDescription);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -907,6 +1132,197 @@ public sealed class CopilotWorkflowRunnerTests
|
||||
Assert.Contains("url permission", approvalEvent.Detail);
|
||||
Assert.Contains("tool \"web_fetch\"", approvalEvent.Detail);
|
||||
Assert.Contains("https://example.com/docs", approvalEvent.Detail);
|
||||
Assert.NotNull(approvalEvent.PermissionDetail);
|
||||
Assert.Equal("url", approvalEvent.PermissionDetail!.Kind);
|
||||
Assert.Equal("Fetch the requested page", approvalEvent.PermissionDetail.Intention);
|
||||
Assert.Equal("https://example.com/docs", approvalEvent.PermissionDetail.Url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildPermissionDetail_ExtractsShellRequestData()
|
||||
{
|
||||
PermissionDetailDto detail = CopilotApprovalCoordinator.BuildPermissionDetail(
|
||||
new PermissionRequestShell
|
||||
{
|
||||
Kind = "shell",
|
||||
ToolCallId = "tool-call-shell",
|
||||
FullCommandText = "curl https://example.com/docs > docs.json",
|
||||
Intention = "Fetch documentation with curl",
|
||||
Commands =
|
||||
[
|
||||
new PermissionRequestShellCommandsItem
|
||||
{
|
||||
Identifier = "curl",
|
||||
ReadOnly = true,
|
||||
},
|
||||
],
|
||||
PossiblePaths = ["docs.json"],
|
||||
PossibleUrls =
|
||||
[
|
||||
new PermissionRequestShellPossibleUrlsItem
|
||||
{
|
||||
Url = "https://example.com/docs",
|
||||
},
|
||||
],
|
||||
HasWriteFileRedirection = true,
|
||||
CanOfferSessionApproval = false,
|
||||
Warning = "Downloads remote content and writes it to disk.",
|
||||
});
|
||||
|
||||
Assert.Equal("shell", detail.Kind);
|
||||
Assert.Equal("curl https://example.com/docs > docs.json", detail.Command);
|
||||
Assert.Equal("Fetch documentation with curl", detail.Intention);
|
||||
Assert.Equal("Downloads remote content and writes it to disk.", detail.Warning);
|
||||
Assert.Equal(["docs.json"], detail.PossiblePaths);
|
||||
Assert.Equal(["https://example.com/docs"], detail.PossibleUrls);
|
||||
Assert.True(detail.HasWriteFileRedirection);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildPermissionDetail_ExtractsWriteRequestData()
|
||||
{
|
||||
PermissionDetailDto detail = CopilotApprovalCoordinator.BuildPermissionDetail(
|
||||
new PermissionRequestWrite
|
||||
{
|
||||
Kind = "write",
|
||||
ToolCallId = "tool-call-write",
|
||||
Intention = "Update README guidance",
|
||||
FileName = "README.md",
|
||||
Diff = "@@ -1 +1 @@\n-Hello\n+Hello world",
|
||||
NewFileContents = "# README",
|
||||
});
|
||||
|
||||
Assert.Equal("write", detail.Kind);
|
||||
Assert.Equal("Update README guidance", detail.Intention);
|
||||
Assert.Equal("README.md", detail.FileName);
|
||||
Assert.Equal("@@ -1 +1 @@\n-Hello\n+Hello world", detail.Diff);
|
||||
Assert.Equal("# README", detail.NewFileContents);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildPermissionDetail_ExtractsReadRequestData()
|
||||
{
|
||||
PermissionDetailDto detail = CopilotApprovalCoordinator.BuildPermissionDetail(
|
||||
new PermissionRequestRead
|
||||
{
|
||||
Kind = "read",
|
||||
ToolCallId = "tool-call-read",
|
||||
Intention = "Inspect the README",
|
||||
Path = "README.md",
|
||||
});
|
||||
|
||||
Assert.Equal("read", detail.Kind);
|
||||
Assert.Equal("Inspect the README", detail.Intention);
|
||||
Assert.Equal("README.md", detail.Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildPermissionDetail_ExtractsMcpRequestData()
|
||||
{
|
||||
PermissionDetailDto detail = CopilotApprovalCoordinator.BuildPermissionDetail(
|
||||
new PermissionRequestMcp
|
||||
{
|
||||
Kind = "mcp",
|
||||
ToolCallId = "tool-call-mcp",
|
||||
ServerName = "Git MCP",
|
||||
ToolName = "git.status",
|
||||
ToolTitle = "Git Status",
|
||||
Args = new Dictionary<string, object?>
|
||||
{
|
||||
["path"] = ".",
|
||||
},
|
||||
ReadOnly = true,
|
||||
});
|
||||
|
||||
Assert.Equal("mcp", detail.Kind);
|
||||
Assert.Equal("Git MCP", detail.ServerName);
|
||||
Assert.Equal("Git Status", detail.ToolTitle);
|
||||
Assert.True(detail.ReadOnly);
|
||||
|
||||
Dictionary<string, object?> args = Assert.IsType<Dictionary<string, object?>>(detail.Args);
|
||||
Assert.Equal(".", args["path"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildPermissionDetail_ExtractsUrlRequestData()
|
||||
{
|
||||
PermissionDetailDto detail = CopilotApprovalCoordinator.BuildPermissionDetail(
|
||||
new PermissionRequestUrl
|
||||
{
|
||||
Kind = "url",
|
||||
ToolCallId = "tool-call-url",
|
||||
Intention = "Fetch the requested page",
|
||||
Url = "https://example.com/docs",
|
||||
});
|
||||
|
||||
Assert.Equal("url", detail.Kind);
|
||||
Assert.Equal("Fetch the requested page", detail.Intention);
|
||||
Assert.Equal("https://example.com/docs", detail.Url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildPermissionDetail_ExtractsMemoryRequestData()
|
||||
{
|
||||
PermissionDetailDto detail = CopilotApprovalCoordinator.BuildPermissionDetail(
|
||||
new PermissionRequestMemory
|
||||
{
|
||||
Kind = "memory",
|
||||
ToolCallId = "tool-call-memory",
|
||||
Subject = "repo conventions",
|
||||
Fact = "Use Bun for script execution.",
|
||||
Citations = "package.json",
|
||||
});
|
||||
|
||||
Assert.Equal("memory", detail.Kind);
|
||||
Assert.Equal("repo conventions", detail.Subject);
|
||||
Assert.Equal("Use Bun for script execution.", detail.Fact);
|
||||
Assert.Equal("package.json", detail.Citations);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildPermissionDetail_ExtractsCustomToolRequestData()
|
||||
{
|
||||
PermissionDetailDto detail = CopilotApprovalCoordinator.BuildPermissionDetail(
|
||||
new PermissionRequestCustomTool
|
||||
{
|
||||
Kind = "custom tool",
|
||||
ToolName = "lsp_ts_hover",
|
||||
ToolDescription = "Hover information",
|
||||
Args = new Dictionary<string, object?>
|
||||
{
|
||||
["file"] = "src/index.ts",
|
||||
["line"] = 12,
|
||||
},
|
||||
});
|
||||
|
||||
Assert.Equal("custom-tool", detail.Kind);
|
||||
Assert.Equal("Hover information", detail.ToolDescription);
|
||||
|
||||
Dictionary<string, object?> args = Assert.IsType<Dictionary<string, object?>>(detail.Args);
|
||||
Assert.Equal("src/index.ts", args["file"]);
|
||||
Assert.Equal(12, args["line"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildPermissionDetail_ExtractsHookRequestData()
|
||||
{
|
||||
PermissionDetailDto detail = CopilotApprovalCoordinator.BuildPermissionDetail(
|
||||
new PermissionRequestHook
|
||||
{
|
||||
Kind = "hook",
|
||||
ToolName = "web_fetch",
|
||||
ToolArgs = new Dictionary<string, object?>
|
||||
{
|
||||
["url"] = "https://example.com",
|
||||
},
|
||||
HookMessage = "Review required before fetch",
|
||||
});
|
||||
|
||||
Assert.Equal("hook", detail.Kind);
|
||||
Assert.Equal("Review required before fetch", detail.HookMessage);
|
||||
|
||||
Dictionary<string, object?> args = Assert.IsType<Dictionary<string, object?>>(detail.Args);
|
||||
Assert.Equal("https://example.com", args["url"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -952,6 +1368,70 @@ public sealed class CopilotWorkflowRunnerTests
|
||||
Assert.Equal(PermissionRequestResultKind.Approved, result.Kind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RequestApprovalAsync_EmitsFileChangeActivityForWriteRequests()
|
||||
{
|
||||
CopilotApprovalCoordinator coordinator = new();
|
||||
AgentActivityEventDto? observedActivity = null;
|
||||
ApprovalRequestedEventDto? observedApproval = null;
|
||||
RunTurnCommandDto command = CreateApprovalCommand();
|
||||
|
||||
Task<PermissionRequestResult> pending = coordinator.RequestApprovalAsync(
|
||||
command,
|
||||
command.Pattern.Agents[0],
|
||||
new PermissionRequestWrite
|
||||
{
|
||||
Kind = "write",
|
||||
ToolCallId = "tool-call-write-1",
|
||||
Intention = "Update the README",
|
||||
FileName = "README.md",
|
||||
Diff = "@@ -1 +1 @@",
|
||||
NewFileContents = "# Aryx\n",
|
||||
},
|
||||
new PermissionInvocation
|
||||
{
|
||||
SessionId = "copilot-session-1",
|
||||
},
|
||||
new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["tool-call-write-1"] = "apply_patch",
|
||||
},
|
||||
activity =>
|
||||
{
|
||||
observedActivity = activity;
|
||||
return Task.CompletedTask;
|
||||
},
|
||||
approval =>
|
||||
{
|
||||
observedApproval = approval;
|
||||
return Task.CompletedTask;
|
||||
},
|
||||
CancellationToken.None);
|
||||
|
||||
Assert.False(pending.IsCompleted);
|
||||
Assert.NotNull(observedActivity);
|
||||
Assert.NotNull(observedApproval);
|
||||
Assert.Equal("tool-calling", observedActivity!.ActivityType);
|
||||
Assert.Equal("apply_patch", observedActivity.ToolName);
|
||||
Assert.Equal("tool-call-write-1", observedActivity.ToolCallId);
|
||||
|
||||
ToolCallFileChangeDto preview = Assert.Single(observedActivity.FileChanges!);
|
||||
Assert.Equal("README.md", preview.Path);
|
||||
Assert.Equal("@@ -1 +1 @@", preview.Diff);
|
||||
Assert.Equal("# Aryx\n", preview.NewFileContents);
|
||||
|
||||
await coordinator.ResolveApprovalAsync(
|
||||
new ResolveApprovalCommandDto
|
||||
{
|
||||
ApprovalId = observedApproval!.ApprovalId,
|
||||
Decision = "approved",
|
||||
},
|
||||
CancellationToken.None);
|
||||
|
||||
PermissionRequestResult result = await pending;
|
||||
Assert.Equal(PermissionRequestResultKind.Approved, result.Kind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RequestApprovalAsync_AutoApprovesToolsThatDoNotRequireApproval()
|
||||
{
|
||||
@@ -984,6 +1464,170 @@ public sealed class CopilotWorkflowRunnerTests
|
||||
Assert.Equal(PermissionRequestResultKind.Approved, result.Kind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RequestApprovalAsync_AlwaysApproveCachesRuntimeApprovalForCurrentTurn()
|
||||
{
|
||||
CopilotApprovalCoordinator coordinator = new();
|
||||
ApprovalRequestedEventDto? firstApproval = null;
|
||||
RunTurnCommandDto command = CreateApprovalCommand();
|
||||
|
||||
Task<PermissionRequestResult> firstPending = coordinator.RequestApprovalAsync(
|
||||
command,
|
||||
command.Pattern.Agents[0],
|
||||
new PermissionRequestRead
|
||||
{
|
||||
Kind = "read",
|
||||
ToolCallId = "tool-call-read-1",
|
||||
Intention = "Inspect README guidance",
|
||||
Path = "README.md",
|
||||
},
|
||||
new PermissionInvocation
|
||||
{
|
||||
SessionId = "copilot-session-1",
|
||||
},
|
||||
new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["tool-call-read-1"] = "view",
|
||||
},
|
||||
approval =>
|
||||
{
|
||||
firstApproval = approval;
|
||||
return Task.CompletedTask;
|
||||
},
|
||||
CancellationToken.None);
|
||||
|
||||
Assert.False(firstPending.IsCompleted);
|
||||
Assert.NotNull(firstApproval);
|
||||
|
||||
await coordinator.ResolveApprovalAsync(
|
||||
new ResolveApprovalCommandDto
|
||||
{
|
||||
ApprovalId = firstApproval!.ApprovalId,
|
||||
Decision = "approved",
|
||||
AlwaysApprove = true,
|
||||
},
|
||||
CancellationToken.None);
|
||||
|
||||
PermissionRequestResult firstResult = await firstPending;
|
||||
Assert.Equal(PermissionRequestResultKind.Approved, firstResult.Kind);
|
||||
|
||||
bool sawSecondApproval = false;
|
||||
PermissionRequestResult secondResult = await coordinator.RequestApprovalAsync(
|
||||
command,
|
||||
command.Pattern.Agents[0],
|
||||
new PermissionRequestRead
|
||||
{
|
||||
Kind = "read",
|
||||
ToolCallId = "tool-call-read-2",
|
||||
Intention = "Inspect docs guidance",
|
||||
Path = "docs\\guide.md",
|
||||
},
|
||||
new PermissionInvocation
|
||||
{
|
||||
SessionId = "copilot-session-1",
|
||||
},
|
||||
new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["tool-call-read-2"] = "grep",
|
||||
},
|
||||
approval =>
|
||||
{
|
||||
sawSecondApproval = true;
|
||||
return Task.CompletedTask;
|
||||
},
|
||||
CancellationToken.None);
|
||||
|
||||
Assert.False(sawSecondApproval);
|
||||
Assert.Equal(PermissionRequestResultKind.Approved, secondResult.Kind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RequestApprovalAsync_AlwaysApproveCacheDoesNotCarryAcrossTurnRequests()
|
||||
{
|
||||
CopilotApprovalCoordinator coordinator = new();
|
||||
ApprovalRequestedEventDto? firstApproval = null;
|
||||
RunTurnCommandDto firstCommand = CreateApprovalCommand();
|
||||
|
||||
Task<PermissionRequestResult> firstPending = coordinator.RequestApprovalAsync(
|
||||
firstCommand,
|
||||
firstCommand.Pattern.Agents[0],
|
||||
new PermissionRequestRead
|
||||
{
|
||||
Kind = "read",
|
||||
ToolCallId = "tool-call-read-1",
|
||||
Intention = "Inspect README guidance",
|
||||
Path = "README.md",
|
||||
},
|
||||
new PermissionInvocation
|
||||
{
|
||||
SessionId = "copilot-session-1",
|
||||
},
|
||||
new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["tool-call-read-1"] = "view",
|
||||
},
|
||||
approval =>
|
||||
{
|
||||
firstApproval = approval;
|
||||
return Task.CompletedTask;
|
||||
},
|
||||
CancellationToken.None);
|
||||
|
||||
Assert.NotNull(firstApproval);
|
||||
|
||||
await coordinator.ResolveApprovalAsync(
|
||||
new ResolveApprovalCommandDto
|
||||
{
|
||||
ApprovalId = firstApproval!.ApprovalId,
|
||||
Decision = "approved",
|
||||
AlwaysApprove = true,
|
||||
},
|
||||
CancellationToken.None);
|
||||
|
||||
await firstPending;
|
||||
|
||||
ApprovalRequestedEventDto? secondApproval = null;
|
||||
RunTurnCommandDto secondCommand = CreateApprovalCommand(requestId: "turn-2");
|
||||
Task<PermissionRequestResult> secondPending = coordinator.RequestApprovalAsync(
|
||||
secondCommand,
|
||||
secondCommand.Pattern.Agents[0],
|
||||
new PermissionRequestRead
|
||||
{
|
||||
Kind = "read",
|
||||
ToolCallId = "tool-call-read-2",
|
||||
Intention = "Inspect docs guidance",
|
||||
Path = "docs\\guide.md",
|
||||
},
|
||||
new PermissionInvocation
|
||||
{
|
||||
SessionId = "copilot-session-1",
|
||||
},
|
||||
new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["tool-call-read-2"] = "grep",
|
||||
},
|
||||
approval =>
|
||||
{
|
||||
secondApproval = approval;
|
||||
return Task.CompletedTask;
|
||||
},
|
||||
CancellationToken.None);
|
||||
|
||||
Assert.False(secondPending.IsCompleted);
|
||||
Assert.NotNull(secondApproval);
|
||||
|
||||
await coordinator.ResolveApprovalAsync(
|
||||
new ResolveApprovalCommandDto
|
||||
{
|
||||
ApprovalId = secondApproval!.ApprovalId,
|
||||
Decision = "approved",
|
||||
},
|
||||
CancellationToken.None);
|
||||
|
||||
PermissionRequestResult secondResult = await secondPending;
|
||||
Assert.Equal(PermissionRequestResultKind.Approved, secondResult.Kind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveApprovalAsync_RejectsUnknownApprovalIds()
|
||||
{
|
||||
@@ -1033,11 +1677,38 @@ public sealed class CopilotWorkflowRunnerTests
|
||||
};
|
||||
}
|
||||
|
||||
private static RunTurnCommandDto CreateApprovalCommand()
|
||||
private static RequestInfoEvent CreateRequestInfoEvent(object payload)
|
||||
{
|
||||
RequestPort port = RequestPort.Create<object, object>("test-port");
|
||||
ExternalRequest request = ExternalRequest.Create(port, payload, "request-1");
|
||||
return new RequestInfoEvent(request);
|
||||
}
|
||||
|
||||
private static object CreateHandoffTarget(string id, string name)
|
||||
{
|
||||
Type type = Type.GetType(
|
||||
"Microsoft.Agents.AI.Workflows.Specialized.HandoffTarget, Microsoft.Agents.AI.Workflows",
|
||||
throwOnError: true)!;
|
||||
return Activator.CreateInstance(type, CreateChatClientAgent(id, name), "Handle the UX work.")!;
|
||||
}
|
||||
|
||||
private static ChatClientAgent CreateChatClientAgent(string id, string name)
|
||||
{
|
||||
return new ChatClientAgent(
|
||||
new StubChatClient(),
|
||||
id,
|
||||
name,
|
||||
"Stub agent for handoff tests.",
|
||||
[],
|
||||
null!,
|
||||
null!);
|
||||
}
|
||||
|
||||
private static RunTurnCommandDto CreateApprovalCommand(string requestId = "turn-1")
|
||||
{
|
||||
return new RunTurnCommandDto
|
||||
{
|
||||
RequestId = "turn-1",
|
||||
RequestId = requestId,
|
||||
SessionId = "session-1",
|
||||
Pattern = new PatternDefinitionDto
|
||||
{
|
||||
@@ -1064,4 +1735,33 @@ public sealed class CopilotWorkflowRunnerTests
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private sealed class StubChatClient : IChatClient
|
||||
{
|
||||
public Task<ChatResponse> GetResponseAsync(
|
||||
IEnumerable<ChatMessage> messages,
|
||||
ChatOptions? options,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
|
||||
IEnumerable<ChatMessage> messages,
|
||||
ChatOptions? options,
|
||||
[EnumeratorCancellation]
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
public object? GetService(Type serviceType, object? serviceKey)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
using Aryx.AgentHost.Contracts;
|
||||
using Aryx.AgentHost.Services;
|
||||
|
||||
namespace Aryx.AgentHost.Tests;
|
||||
|
||||
public sealed class HookCommandRunnerTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task RunAsync_PipesJsonIntoHookStandardInput()
|
||||
{
|
||||
HookCommandRunner runner = new();
|
||||
using TestDirectory project = new();
|
||||
HookCommandDefinition hook = CreatePlatformHook(
|
||||
OperatingSystem.IsWindows()
|
||||
? "$payload = [Console]::In.ReadToEnd(); Write-Output $payload"
|
||||
: "payload=$(cat); printf '%s' \"$payload\"");
|
||||
|
||||
string input = """{"toolName":"view","toolArgs":"{\"path\":\"README.md\"}"}""";
|
||||
|
||||
string? output = await runner.RunAsync(hook, input, project.Path, CancellationToken.None);
|
||||
|
||||
Assert.Equal(input, output?.Trim());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunAsync_ReturnsNullWhenHookTimesOut()
|
||||
{
|
||||
HookCommandRunner runner = new();
|
||||
using TestDirectory project = new();
|
||||
HookCommandDefinition hook = CreatePlatformHook(
|
||||
OperatingSystem.IsWindows() ? "Start-Sleep -Seconds 5" : "sleep 5",
|
||||
timeoutSec: 1);
|
||||
|
||||
string? output = await runner.RunAsync(hook, "{}", project.Path, CancellationToken.None);
|
||||
|
||||
Assert.Null(output);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunAsync_ReturnsNullWhenHookFails()
|
||||
{
|
||||
HookCommandRunner runner = new();
|
||||
using TestDirectory project = new();
|
||||
HookCommandDefinition hook = CreatePlatformHook(
|
||||
OperatingSystem.IsWindows() ? "Write-Error 'boom'; exit 1" : "echo boom >&2; exit 1");
|
||||
|
||||
string? output = await runner.RunAsync(hook, "{}", project.Path, CancellationToken.None);
|
||||
|
||||
Assert.Null(output);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunAsync_ReturnsNullWhenCurrentPlatformCommandIsMissing()
|
||||
{
|
||||
HookCommandRunner runner = new();
|
||||
using TestDirectory project = new();
|
||||
HookCommandDefinition hook = OperatingSystem.IsWindows()
|
||||
? new HookCommandDefinition { Type = "command", Bash = "echo unsupported" }
|
||||
: new HookCommandDefinition { Type = "command", PowerShell = "Write-Output unsupported" };
|
||||
|
||||
string? output = await runner.RunAsync(hook, "{}", project.Path, CancellationToken.None);
|
||||
|
||||
Assert.Null(output);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunAsync_UsesConfiguredWorkingDirectoryAndEnvironment()
|
||||
{
|
||||
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()
|
||||
? "$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>
|
||||
{
|
||||
["HOOK_TEST_ENV"] = "configured",
|
||||
});
|
||||
|
||||
string? output = await runner.RunAsync(hook, "{}", project.Path, CancellationToken.None);
|
||||
|
||||
Assert.Equal("present|configured", output?.Trim());
|
||||
}
|
||||
|
||||
private static HookCommandDefinition CreatePlatformHook(
|
||||
string command,
|
||||
int? timeoutSec = null,
|
||||
string? cwd = null,
|
||||
IReadOnlyDictionary<string, string>? env = null)
|
||||
{
|
||||
return OperatingSystem.IsWindows()
|
||||
? new HookCommandDefinition
|
||||
{
|
||||
Type = "command",
|
||||
PowerShell = command,
|
||||
TimeoutSec = timeoutSec,
|
||||
Cwd = cwd,
|
||||
Env = env,
|
||||
}
|
||||
: new HookCommandDefinition
|
||||
{
|
||||
Type = "command",
|
||||
Bash = command,
|
||||
TimeoutSec = timeoutSec,
|
||||
Cwd = cwd,
|
||||
Env = env,
|
||||
};
|
||||
}
|
||||
|
||||
private sealed class TestDirectory : IDisposable
|
||||
{
|
||||
private readonly DirectoryInfo _directory = Directory.CreateTempSubdirectory("aryx-hooks-runner-");
|
||||
|
||||
public string Path => _directory.FullName;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_directory.Exists)
|
||||
{
|
||||
_directory.Delete(recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
using Aryx.AgentHost.Contracts;
|
||||
using Aryx.AgentHost.Services;
|
||||
|
||||
namespace Aryx.AgentHost.Tests;
|
||||
|
||||
public sealed class HookConfigLoaderTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task LoadAsync_ParsesSupportedHookTypes()
|
||||
{
|
||||
using TestDirectory project = new();
|
||||
string hooksDirectory = Directory.CreateDirectory(Path.Combine(project.Path, ".github", "hooks")).FullName;
|
||||
|
||||
await File.WriteAllTextAsync(
|
||||
Path.Combine(hooksDirectory, "hooks.json"),
|
||||
"""
|
||||
{
|
||||
"version": 1,
|
||||
"hooks": {
|
||||
"sessionStart": [
|
||||
{
|
||||
"type": "command",
|
||||
"bash": "echo session-start",
|
||||
"powershell": "Write-Output session-start",
|
||||
"cwd": ".",
|
||||
"env": { "HOOK_MODE": "audit" },
|
||||
"timeoutSec": 15
|
||||
}
|
||||
],
|
||||
"preToolUse": [
|
||||
{
|
||||
"type": "command",
|
||||
"bash": "echo pre-tool",
|
||||
"powershell": "Write-Output pre-tool"
|
||||
}
|
||||
],
|
||||
"errorOccurred": [
|
||||
{
|
||||
"type": "command",
|
||||
"bash": "echo error-hook",
|
||||
"powershell": "Write-Output error-hook"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
""");
|
||||
|
||||
ResolvedHookSet hooks = await HookConfigLoader.LoadAsync(project.Path, CancellationToken.None);
|
||||
|
||||
HookCommandDefinition sessionStart = Assert.Single(hooks.SessionStart);
|
||||
Assert.Equal("command", sessionStart.Type);
|
||||
Assert.Equal("echo session-start", sessionStart.Bash);
|
||||
Assert.Equal("Write-Output session-start", sessionStart.PowerShell);
|
||||
Assert.Equal(".", sessionStart.Cwd);
|
||||
Assert.Equal(15, sessionStart.TimeoutSec);
|
||||
Assert.NotNull(sessionStart.Env);
|
||||
Assert.Equal("audit", sessionStart.Env["HOOK_MODE"]);
|
||||
Assert.Single(hooks.PreToolUse);
|
||||
Assert.Single(hooks.ErrorOccurred);
|
||||
Assert.False(hooks.IsEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LoadAsync_MergesHookFilesInFileNameOrder()
|
||||
{
|
||||
using TestDirectory project = new();
|
||||
string hooksDirectory = Directory.CreateDirectory(Path.Combine(project.Path, ".github", "hooks")).FullName;
|
||||
|
||||
await File.WriteAllTextAsync(
|
||||
Path.Combine(hooksDirectory, "20-second.json"),
|
||||
"""
|
||||
{
|
||||
"version": 1,
|
||||
"hooks": {
|
||||
"preToolUse": [
|
||||
{
|
||||
"type": "command",
|
||||
"bash": "echo second",
|
||||
"powershell": "Write-Output second"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
""");
|
||||
await File.WriteAllTextAsync(
|
||||
Path.Combine(hooksDirectory, "10-first.json"),
|
||||
"""
|
||||
{
|
||||
"version": 1,
|
||||
"hooks": {
|
||||
"preToolUse": [
|
||||
{
|
||||
"type": "command",
|
||||
"bash": "echo first",
|
||||
"powershell": "Write-Output first"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
""");
|
||||
|
||||
ResolvedHookSet hooks = await HookConfigLoader.LoadAsync(project.Path, CancellationToken.None);
|
||||
|
||||
string[] commands = hooks.PreToolUse.Select(GetCommandText).ToArray();
|
||||
Assert.Equal(2, commands.Length);
|
||||
Assert.Contains("first", commands[0], StringComparison.Ordinal);
|
||||
Assert.Contains("second", commands[1], StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LoadAsync_ReturnsEmptyWhenHooksDirectoryIsMissing()
|
||||
{
|
||||
using TestDirectory project = new();
|
||||
|
||||
ResolvedHookSet hooks = await HookConfigLoader.LoadAsync(project.Path, CancellationToken.None);
|
||||
|
||||
Assert.Same(ResolvedHookSet.Empty, hooks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LoadAsync_SkipsInvalidFilesAndUnsupportedVersions()
|
||||
{
|
||||
using TestDirectory project = new();
|
||||
string hooksDirectory = Directory.CreateDirectory(Path.Combine(project.Path, ".github", "hooks")).FullName;
|
||||
|
||||
await File.WriteAllTextAsync(Path.Combine(hooksDirectory, "00-invalid.json"), "{ not-json");
|
||||
await File.WriteAllTextAsync(
|
||||
Path.Combine(hooksDirectory, "10-unsupported.json"),
|
||||
"""
|
||||
{
|
||||
"version": 2,
|
||||
"hooks": {
|
||||
"sessionStart": [
|
||||
{
|
||||
"type": "command",
|
||||
"bash": "echo unsupported",
|
||||
"powershell": "Write-Output unsupported"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
""");
|
||||
await File.WriteAllTextAsync(
|
||||
Path.Combine(hooksDirectory, "20-valid.json"),
|
||||
"""
|
||||
{
|
||||
"version": 1,
|
||||
"hooks": {
|
||||
"sessionEnd": [
|
||||
{
|
||||
"type": "command",
|
||||
"bash": "echo valid",
|
||||
"powershell": "Write-Output valid"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
""");
|
||||
|
||||
ResolvedHookSet hooks = await HookConfigLoader.LoadAsync(project.Path, CancellationToken.None);
|
||||
|
||||
HookCommandDefinition valid = Assert.Single(hooks.SessionEnd);
|
||||
Assert.Contains("valid", GetCommandText(valid), StringComparison.Ordinal);
|
||||
Assert.Empty(hooks.SessionStart);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LoadAsync_ReturnsEmptyForEmptyHooksObject()
|
||||
{
|
||||
using TestDirectory project = new();
|
||||
string hooksDirectory = Directory.CreateDirectory(Path.Combine(project.Path, ".github", "hooks")).FullName;
|
||||
|
||||
await File.WriteAllTextAsync(
|
||||
Path.Combine(hooksDirectory, "hooks.json"),
|
||||
"""
|
||||
{
|
||||
"version": 1,
|
||||
"hooks": {}
|
||||
}
|
||||
""");
|
||||
|
||||
ResolvedHookSet hooks = await HookConfigLoader.LoadAsync(project.Path, CancellationToken.None);
|
||||
|
||||
Assert.Same(ResolvedHookSet.Empty, hooks);
|
||||
}
|
||||
|
||||
private static string GetCommandText(HookCommandDefinition hook)
|
||||
=> hook.PowerShell ?? hook.Bash ?? string.Empty;
|
||||
|
||||
private sealed class TestDirectory : IDisposable
|
||||
{
|
||||
private readonly DirectoryInfo _directory = Directory.CreateTempSubdirectory("aryx-hooks-loader-");
|
||||
|
||||
public string Path => _directory.FullName;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_directory.Exists)
|
||||
{
|
||||
_directory.Delete(recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Text.Json;
|
||||
using Aryx.AgentHost.Contracts;
|
||||
using Aryx.AgentHost.Services;
|
||||
using GitHub.Copilot.SDK.Rpc;
|
||||
|
||||
namespace Aryx.AgentHost.Tests;
|
||||
|
||||
@@ -112,7 +113,7 @@ public sealed class SidecarProtocolHostTests
|
||||
{
|
||||
SidecarProtocolHost host = new(
|
||||
new PatternValidator(),
|
||||
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, cancellationToken) =>
|
||||
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) =>
|
||||
{
|
||||
await onActivity(new AgentActivityEventDto
|
||||
{
|
||||
@@ -231,12 +232,49 @@ public sealed class SidecarProtocolHostTests
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunTurnCommand_DeserializesInteractionMode()
|
||||
{
|
||||
string? capturedMode = null;
|
||||
SidecarProtocolHost host = new(
|
||||
new PatternValidator(),
|
||||
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) =>
|
||||
{
|
||||
capturedMode = command.Mode;
|
||||
return [];
|
||||
}));
|
||||
|
||||
await RunHostAsync(
|
||||
new RunTurnCommandDto
|
||||
{
|
||||
Type = "run-turn",
|
||||
RequestId = "turn-plan",
|
||||
SessionId = "session-1",
|
||||
ProjectPath = "C:\\workspace\\project",
|
||||
Mode = "plan",
|
||||
Pattern = new PatternDefinitionDto
|
||||
{
|
||||
Id = "pattern-1",
|
||||
Name = "Single Agent",
|
||||
Mode = "single",
|
||||
Availability = "available",
|
||||
Agents =
|
||||
[
|
||||
CreateAgent(name: "Primary"),
|
||||
],
|
||||
},
|
||||
},
|
||||
host);
|
||||
|
||||
Assert.Equal("plan", capturedMode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunTurnCommand_ReturnsApprovalEvents()
|
||||
{
|
||||
SidecarProtocolHost host = new(
|
||||
new PatternValidator(),
|
||||
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, cancellationToken) =>
|
||||
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) =>
|
||||
{
|
||||
await onApproval(new ApprovalRequestedEventDto
|
||||
{
|
||||
@@ -249,6 +287,13 @@ public sealed class SidecarProtocolHostTests
|
||||
AgentName = "Primary",
|
||||
PermissionKind = "tool access",
|
||||
Title = "Approve tool access",
|
||||
PermissionDetail = new PermissionDetailDto
|
||||
{
|
||||
Kind = "shell",
|
||||
Command = "git status",
|
||||
Intention = "Inspect repository state",
|
||||
PossiblePaths = ["README.md"],
|
||||
},
|
||||
});
|
||||
|
||||
return [];
|
||||
@@ -284,6 +329,11 @@ public sealed class SidecarProtocolHostTests
|
||||
Assert.Equal("approval-1", approvalEvent.GetProperty("approvalId").GetString());
|
||||
Assert.Equal("tool-call", approvalEvent.GetProperty("approvalKind").GetString());
|
||||
Assert.Equal("Approve tool access", approvalEvent.GetProperty("title").GetString());
|
||||
JsonElement permissionDetail = approvalEvent.GetProperty("permissionDetail");
|
||||
Assert.Equal("shell", permissionDetail.GetProperty("kind").GetString());
|
||||
Assert.Equal("git status", permissionDetail.GetProperty("command").GetString());
|
||||
Assert.Equal("Inspect repository state", permissionDetail.GetProperty("intention").GetString());
|
||||
Assert.Equal("README.md", Assert.Single(permissionDetail.GetProperty("possiblePaths").EnumerateArray()).GetString());
|
||||
},
|
||||
completionEvent =>
|
||||
{
|
||||
@@ -297,12 +347,218 @@ public sealed class SidecarProtocolHostTests
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunTurnCommand_ReturnsUserInputEvents()
|
||||
{
|
||||
SidecarProtocolHost host = new(
|
||||
new PatternValidator(),
|
||||
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) =>
|
||||
{
|
||||
await onUserInput(new UserInputRequestedEventDto
|
||||
{
|
||||
Type = "user-input-requested",
|
||||
RequestId = command.RequestId,
|
||||
SessionId = command.SessionId,
|
||||
UserInputId = "user-input-1",
|
||||
AgentId = "agent-1",
|
||||
AgentName = "Primary",
|
||||
Question = "What should I do next?",
|
||||
Choices = ["Continue", "Stop"],
|
||||
AllowFreeform = true,
|
||||
});
|
||||
|
||||
return [];
|
||||
}));
|
||||
|
||||
IReadOnlyList<JsonElement> events = await RunHostAsync(
|
||||
new RunTurnCommandDto
|
||||
{
|
||||
Type = "run-turn",
|
||||
RequestId = "turn-user-input",
|
||||
SessionId = "session-1",
|
||||
ProjectPath = "C:\\workspace\\project",
|
||||
Pattern = new PatternDefinitionDto
|
||||
{
|
||||
Id = "pattern-1",
|
||||
Name = "Single Agent",
|
||||
Mode = "single",
|
||||
Availability = "available",
|
||||
Agents =
|
||||
[
|
||||
CreateAgent(name: "Primary"),
|
||||
],
|
||||
},
|
||||
},
|
||||
host);
|
||||
|
||||
Assert.Collection(
|
||||
events,
|
||||
userInputEvent =>
|
||||
{
|
||||
Assert.Equal("user-input-requested", userInputEvent.GetProperty("type").GetString());
|
||||
Assert.Equal("turn-user-input", userInputEvent.GetProperty("requestId").GetString());
|
||||
Assert.Equal("session-1", userInputEvent.GetProperty("sessionId").GetString());
|
||||
Assert.Equal("user-input-1", userInputEvent.GetProperty("userInputId").GetString());
|
||||
Assert.Equal("Primary", userInputEvent.GetProperty("agentName").GetString());
|
||||
Assert.Equal("What should I do next?", userInputEvent.GetProperty("question").GetString());
|
||||
string[] choices = userInputEvent.GetProperty("choices")
|
||||
.EnumerateArray()
|
||||
.Select(choice => choice.GetString() ?? string.Empty)
|
||||
.ToArray();
|
||||
Assert.Equal(["Continue", "Stop"], choices);
|
||||
Assert.True(userInputEvent.GetProperty("allowFreeform").GetBoolean());
|
||||
},
|
||||
completionEvent =>
|
||||
{
|
||||
Assert.Equal("turn-complete", completionEvent.GetProperty("type").GetString());
|
||||
Assert.False(completionEvent.GetProperty("cancelled").GetBoolean());
|
||||
},
|
||||
commandCompleteEvent =>
|
||||
{
|
||||
Assert.Equal("command-complete", commandCompleteEvent.GetProperty("type").GetString());
|
||||
Assert.Equal("turn-user-input", commandCompleteEvent.GetProperty("requestId").GetString());
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunTurnCommand_ReturnsMcpOauthRequiredEvents()
|
||||
{
|
||||
SidecarProtocolHost host = new(
|
||||
new PatternValidator(),
|
||||
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) =>
|
||||
{
|
||||
await onMcpOAuthRequired(new McpOauthRequiredEventDto
|
||||
{
|
||||
Type = "mcp-oauth-required",
|
||||
RequestId = command.RequestId,
|
||||
SessionId = command.SessionId,
|
||||
OauthRequestId = "oauth-request-1",
|
||||
AgentId = "agent-1",
|
||||
AgentName = "Primary",
|
||||
ServerName = "Example MCP",
|
||||
ServerUrl = "https://example.com/mcp",
|
||||
StaticClientConfig = new McpOauthStaticClientConfigDto
|
||||
{
|
||||
ClientId = "aryx-client",
|
||||
PublicClient = true,
|
||||
},
|
||||
});
|
||||
|
||||
return [];
|
||||
}));
|
||||
|
||||
IReadOnlyList<JsonElement> events = await RunHostAsync(
|
||||
CreateRunTurnCommand(requestId: "turn-mcp-oauth"),
|
||||
host);
|
||||
|
||||
Assert.Collection(
|
||||
events,
|
||||
oauthEvent =>
|
||||
{
|
||||
Assert.Equal("mcp-oauth-required", oauthEvent.GetProperty("type").GetString());
|
||||
Assert.Equal("turn-mcp-oauth", oauthEvent.GetProperty("requestId").GetString());
|
||||
Assert.Equal("session-1", oauthEvent.GetProperty("sessionId").GetString());
|
||||
Assert.Equal("oauth-request-1", oauthEvent.GetProperty("oauthRequestId").GetString());
|
||||
Assert.Equal("Primary", oauthEvent.GetProperty("agentName").GetString());
|
||||
Assert.Equal("Example MCP", oauthEvent.GetProperty("serverName").GetString());
|
||||
Assert.Equal("https://example.com/mcp", oauthEvent.GetProperty("serverUrl").GetString());
|
||||
JsonElement staticClientConfig = oauthEvent.GetProperty("staticClientConfig");
|
||||
Assert.Equal("aryx-client", staticClientConfig.GetProperty("clientId").GetString());
|
||||
Assert.True(staticClientConfig.GetProperty("publicClient").GetBoolean());
|
||||
},
|
||||
completionEvent =>
|
||||
{
|
||||
Assert.Equal("turn-complete", completionEvent.GetProperty("type").GetString());
|
||||
Assert.False(completionEvent.GetProperty("cancelled").GetBoolean());
|
||||
},
|
||||
commandCompleteEvent =>
|
||||
{
|
||||
Assert.Equal("command-complete", commandCompleteEvent.GetProperty("type").GetString());
|
||||
Assert.Equal("turn-mcp-oauth", commandCompleteEvent.GetProperty("requestId").GetString());
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunTurnCommand_ReturnsExitPlanModeEvents()
|
||||
{
|
||||
SidecarProtocolHost host = new(
|
||||
new PatternValidator(),
|
||||
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) =>
|
||||
{
|
||||
await onExitPlanMode(new ExitPlanModeRequestedEventDto
|
||||
{
|
||||
Type = "exit-plan-mode-requested",
|
||||
RequestId = command.RequestId,
|
||||
SessionId = command.SessionId,
|
||||
ExitPlanId = "exit-plan-1",
|
||||
AgentId = "agent-1",
|
||||
AgentName = "Primary",
|
||||
Summary = "Proposed implementation plan",
|
||||
PlanContent = "1. Inspect\n2. Change\n3. Validate",
|
||||
Actions = ["interactive", "autopilot"],
|
||||
RecommendedAction = "interactive",
|
||||
});
|
||||
|
||||
return [];
|
||||
}));
|
||||
|
||||
IReadOnlyList<JsonElement> events = await RunHostAsync(
|
||||
new RunTurnCommandDto
|
||||
{
|
||||
Type = "run-turn",
|
||||
RequestId = "turn-plan-mode",
|
||||
SessionId = "session-1",
|
||||
ProjectPath = "C:\\workspace\\project",
|
||||
Mode = "plan",
|
||||
Pattern = new PatternDefinitionDto
|
||||
{
|
||||
Id = "pattern-1",
|
||||
Name = "Single Agent",
|
||||
Mode = "single",
|
||||
Availability = "available",
|
||||
Agents =
|
||||
[
|
||||
CreateAgent(name: "Primary"),
|
||||
],
|
||||
},
|
||||
},
|
||||
host);
|
||||
|
||||
Assert.Collection(
|
||||
events,
|
||||
exitPlanEvent =>
|
||||
{
|
||||
Assert.Equal("exit-plan-mode-requested", exitPlanEvent.GetProperty("type").GetString());
|
||||
Assert.Equal("turn-plan-mode", exitPlanEvent.GetProperty("requestId").GetString());
|
||||
Assert.Equal("exit-plan-1", exitPlanEvent.GetProperty("exitPlanId").GetString());
|
||||
Assert.Equal("Primary", exitPlanEvent.GetProperty("agentName").GetString());
|
||||
Assert.Equal("Proposed implementation plan", exitPlanEvent.GetProperty("summary").GetString());
|
||||
Assert.Equal("1. Inspect\n2. Change\n3. Validate", exitPlanEvent.GetProperty("planContent").GetString());
|
||||
string[] actions = exitPlanEvent.GetProperty("actions")
|
||||
.EnumerateArray()
|
||||
.Select(action => action.GetString() ?? string.Empty)
|
||||
.ToArray();
|
||||
Assert.Equal(["interactive", "autopilot"], actions);
|
||||
Assert.Equal("interactive", exitPlanEvent.GetProperty("recommendedAction").GetString());
|
||||
},
|
||||
completionEvent =>
|
||||
{
|
||||
Assert.Equal("turn-complete", completionEvent.GetProperty("type").GetString());
|
||||
Assert.False(completionEvent.GetProperty("cancelled").GetBoolean());
|
||||
},
|
||||
commandCompleteEvent =>
|
||||
{
|
||||
Assert.Equal("command-complete", commandCompleteEvent.GetProperty("type").GetString());
|
||||
Assert.Equal("turn-plan-mode", commandCompleteEvent.GetProperty("requestId").GetString());
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CancelTurnCommand_CancelsInProgressTurnAndCompletesBothCommands()
|
||||
{
|
||||
SidecarProtocolHost host = new(
|
||||
new PatternValidator(),
|
||||
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, cancellationToken) =>
|
||||
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) =>
|
||||
{
|
||||
await Task.Delay(Timeout.Infinite, cancellationToken);
|
||||
return [];
|
||||
@@ -350,7 +606,7 @@ public sealed class SidecarProtocolHostTests
|
||||
{
|
||||
SidecarProtocolHost host = new(
|
||||
new PatternValidator(),
|
||||
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, cancellationToken) => []));
|
||||
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) => []));
|
||||
|
||||
await RunHostAsync(CreateRunTurnCommand(requestId: "turn-completed"), host);
|
||||
|
||||
@@ -373,7 +629,7 @@ public sealed class SidecarProtocolHostTests
|
||||
SidecarProtocolHost host = new(
|
||||
new PatternValidator(),
|
||||
new FakeWorkflowRunner(
|
||||
handler: async (command, onDelta, onActivity, onApproval, cancellationToken) => [],
|
||||
handler: async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) => [],
|
||||
resolveApprovalHandler: (command, cancellationToken) =>
|
||||
{
|
||||
captured = command;
|
||||
@@ -387,6 +643,7 @@ public sealed class SidecarProtocolHostTests
|
||||
RequestId = "approval-command-1",
|
||||
ApprovalId = "approval-1",
|
||||
Decision = "approved",
|
||||
AlwaysApprove = true,
|
||||
},
|
||||
host);
|
||||
|
||||
@@ -395,6 +652,93 @@ public sealed class SidecarProtocolHostTests
|
||||
Assert.Equal("approval-command-1", completionEvent.GetProperty("requestId").GetString());
|
||||
Assert.Equal("approval-1", captured?.ApprovalId);
|
||||
Assert.Equal("approved", captured?.Decision);
|
||||
Assert.True(captured?.AlwaysApprove ?? false);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveUserInputCommand_DelegatesToWorkflowRunnerAndCompletes()
|
||||
{
|
||||
ResolveUserInputCommandDto? captured = null;
|
||||
SidecarProtocolHost host = new(
|
||||
new PatternValidator(),
|
||||
new FakeWorkflowRunner(
|
||||
handler: async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) => [],
|
||||
resolveUserInputHandler: (command, cancellationToken) =>
|
||||
{
|
||||
captured = command;
|
||||
return Task.CompletedTask;
|
||||
}));
|
||||
|
||||
IReadOnlyList<JsonElement> events = await RunHostAsync(
|
||||
new ResolveUserInputCommandDto
|
||||
{
|
||||
Type = "resolve-user-input",
|
||||
RequestId = "user-input-command-1",
|
||||
UserInputId = "user-input-1",
|
||||
Answer = "Continue",
|
||||
WasFreeform = false,
|
||||
},
|
||||
host);
|
||||
|
||||
JsonElement completionEvent = Assert.Single(events);
|
||||
Assert.Equal("command-complete", completionEvent.GetProperty("type").GetString());
|
||||
Assert.Equal("user-input-command-1", completionEvent.GetProperty("requestId").GetString());
|
||||
Assert.Equal("user-input-1", captured?.UserInputId);
|
||||
Assert.Equal("Continue", captured?.Answer);
|
||||
Assert.False(captured?.WasFreeform);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MapRuntimeTools_ExcludesOnlyInternalMetaToolsAndDeduplicatesByName()
|
||||
{
|
||||
IReadOnlyList<SidecarRuntimeToolDto> runtimeTools = SidecarProtocolHost.MapRuntimeTools(
|
||||
[
|
||||
new Tool
|
||||
{
|
||||
Name = "ask_user",
|
||||
Description = "Ask the user a question.",
|
||||
},
|
||||
new Tool
|
||||
{
|
||||
Name = "report_intent",
|
||||
Description = "Report current intent.",
|
||||
},
|
||||
new Tool
|
||||
{
|
||||
Name = "task_complete",
|
||||
Description = "Signal task completion.",
|
||||
},
|
||||
new Tool
|
||||
{
|
||||
Name = "exit_plan_mode",
|
||||
Description = "Exit plan mode.",
|
||||
},
|
||||
new Tool
|
||||
{
|
||||
Name = " web_fetch ",
|
||||
Description = " Fetch content from the web. ",
|
||||
},
|
||||
new Tool
|
||||
{
|
||||
Name = "WEB_FETCH",
|
||||
Description = "Duplicate entry",
|
||||
},
|
||||
]);
|
||||
|
||||
Assert.Collection(
|
||||
runtimeTools,
|
||||
exitPlanTool =>
|
||||
{
|
||||
Assert.Equal("exit_plan_mode", exitPlanTool.Id);
|
||||
Assert.Equal("exit_plan_mode", exitPlanTool.Label);
|
||||
Assert.Equal("Exit plan mode.", exitPlanTool.Description);
|
||||
},
|
||||
runtimeTool =>
|
||||
{
|
||||
Assert.Equal("web_fetch", runtimeTool.Id);
|
||||
Assert.Equal("web_fetch", runtimeTool.Label);
|
||||
Assert.Equal("Fetch content from the web.", runtimeTool.Description);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -436,6 +780,147 @@ public sealed class SidecarProtocolHostTests
|
||||
Assert.False(string.IsNullOrWhiteSpace(diagnostics.CheckedAt));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListSessionsCommand_ReturnsSessionsListedEvent()
|
||||
{
|
||||
SidecarProtocolHost host = new(
|
||||
new PatternValidator(),
|
||||
sessionManager: new FakeSessionManager
|
||||
{
|
||||
Sessions =
|
||||
[
|
||||
new CopilotSessionInfoDto
|
||||
{
|
||||
CopilotSessionId = "aryx::session-1::agent-1",
|
||||
ManagedByAryx = true,
|
||||
SessionId = "session-1",
|
||||
AgentId = "agent-1",
|
||||
Summary = "Review session",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
IReadOnlyList<JsonElement> events = await RunHostAsync(
|
||||
new ListSessionsCommandDto
|
||||
{
|
||||
Type = "list-sessions",
|
||||
RequestId = "list-1",
|
||||
},
|
||||
host);
|
||||
|
||||
JsonElement listedEvent = AssertSingleEvent(events, "sessions-listed", "list-1");
|
||||
JsonElement session = Assert.Single(listedEvent.GetProperty("sessions").EnumerateArray());
|
||||
Assert.Equal("aryx::session-1::agent-1", session.GetProperty("copilotSessionId").GetString());
|
||||
Assert.Equal("session-1", session.GetProperty("sessionId").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteSessionCommand_ReturnsDeletedSessionsEvent()
|
||||
{
|
||||
FakeSessionManager sessionManager = new()
|
||||
{
|
||||
DeletedSessions =
|
||||
[
|
||||
new CopilotSessionInfoDto
|
||||
{
|
||||
CopilotSessionId = "aryx::session-1::agent-1",
|
||||
ManagedByAryx = true,
|
||||
SessionId = "session-1",
|
||||
AgentId = "agent-1",
|
||||
},
|
||||
],
|
||||
};
|
||||
SidecarProtocolHost host = new(
|
||||
new PatternValidator(),
|
||||
sessionManager: sessionManager);
|
||||
|
||||
IReadOnlyList<JsonElement> events = await RunHostAsync(
|
||||
new DeleteSessionCommandDto
|
||||
{
|
||||
Type = "delete-session",
|
||||
RequestId = "delete-1",
|
||||
SessionId = "session-1",
|
||||
},
|
||||
host);
|
||||
|
||||
JsonElement deletedEvent = AssertSingleEvent(events, "sessions-deleted", "delete-1");
|
||||
JsonElement session = Assert.Single(deletedEvent.GetProperty("sessions").EnumerateArray());
|
||||
Assert.Equal("session-1", deletedEvent.GetProperty("sessionId").GetString());
|
||||
Assert.Equal("aryx::session-1::agent-1", session.GetProperty("copilotSessionId").GetString());
|
||||
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()
|
||||
{
|
||||
FakeWorkflowRunner runner = new(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) =>
|
||||
{
|
||||
await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken);
|
||||
return [];
|
||||
});
|
||||
SidecarProtocolHost host = new(new PatternValidator(), runner);
|
||||
|
||||
IReadOnlyList<JsonElement> events = await RunHostAsync(
|
||||
[
|
||||
CreateRunTurnCommand(requestId: "turn-1", sessionId: "session-1"),
|
||||
new DisconnectSessionCommandDto
|
||||
{
|
||||
Type = "disconnect-session",
|
||||
RequestId = "disconnect-1",
|
||||
SessionId = "session-1",
|
||||
},
|
||||
],
|
||||
host);
|
||||
|
||||
JsonElement disconnectedEvent = AssertSingleEvent(events, "session-disconnected", "disconnect-1");
|
||||
string[] cancelledRequestIds = disconnectedEvent.GetProperty("cancelledRequestIds")
|
||||
.EnumerateArray()
|
||||
.Select(value => value.GetString() ?? string.Empty)
|
||||
.ToArray();
|
||||
Assert.Equal(["turn-1"], cancelledRequestIds);
|
||||
|
||||
JsonElement turnComplete = AssertSingleEvent(events, "turn-complete", "turn-1");
|
||||
Assert.True(turnComplete.GetProperty("cancelled").GetBoolean());
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<JsonElement>> RunHostAsync(
|
||||
object command,
|
||||
SidecarProtocolHost? host = null)
|
||||
@@ -464,9 +949,9 @@ public sealed class SidecarProtocolHostTests
|
||||
string eventType,
|
||||
string requestId)
|
||||
{
|
||||
return Assert.Single(events.Where(evt =>
|
||||
return Assert.Single(events, evt =>
|
||||
evt.GetProperty("type").GetString() == eventType
|
||||
&& evt.GetProperty("requestId").GetString() == requestId));
|
||||
&& evt.GetProperty("requestId").GetString() == requestId);
|
||||
}
|
||||
|
||||
private static SidecarProtocolHost CreateHostForTests()
|
||||
@@ -605,34 +1090,46 @@ public sealed class SidecarProtocolHostTests
|
||||
private readonly Func<
|
||||
RunTurnCommandDto,
|
||||
Func<TurnDeltaEventDto, Task>,
|
||||
Func<AgentActivityEventDto, Task>,
|
||||
Func<SidecarEventDto, Task>,
|
||||
Func<ApprovalRequestedEventDto, Task>,
|
||||
Func<UserInputRequestedEventDto, Task>,
|
||||
Func<McpOauthRequiredEventDto, Task>,
|
||||
Func<ExitPlanModeRequestedEventDto, Task>,
|
||||
CancellationToken,
|
||||
Task<IReadOnlyList<ChatMessageDto>>> _handler;
|
||||
private readonly Func<ResolveApprovalCommandDto, CancellationToken, Task> _resolveApprovalHandler;
|
||||
private readonly Func<ResolveUserInputCommandDto, CancellationToken, Task> _resolveUserInputHandler;
|
||||
|
||||
public FakeWorkflowRunner(
|
||||
Func<
|
||||
RunTurnCommandDto,
|
||||
Func<TurnDeltaEventDto, Task>,
|
||||
Func<AgentActivityEventDto, Task>,
|
||||
Func<SidecarEventDto, Task>,
|
||||
Func<ApprovalRequestedEventDto, Task>,
|
||||
Func<UserInputRequestedEventDto, Task>,
|
||||
Func<McpOauthRequiredEventDto, Task>,
|
||||
Func<ExitPlanModeRequestedEventDto, Task>,
|
||||
CancellationToken,
|
||||
Task<IReadOnlyList<ChatMessageDto>>> handler,
|
||||
Func<ResolveApprovalCommandDto, CancellationToken, Task>? resolveApprovalHandler = null)
|
||||
Func<ResolveApprovalCommandDto, CancellationToken, Task>? resolveApprovalHandler = null,
|
||||
Func<ResolveUserInputCommandDto, CancellationToken, Task>? resolveUserInputHandler = null)
|
||||
{
|
||||
_handler = handler;
|
||||
_resolveApprovalHandler = resolveApprovalHandler ?? ((_, _) => Task.CompletedTask);
|
||||
_resolveUserInputHandler = resolveUserInputHandler ?? ((_, _) => Task.CompletedTask);
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<ChatMessageDto>> RunTurnAsync(
|
||||
RunTurnCommandDto command,
|
||||
Func<TurnDeltaEventDto, Task> onDelta,
|
||||
Func<AgentActivityEventDto, Task> onActivity,
|
||||
Func<SidecarEventDto, Task> onActivity,
|
||||
Func<ApprovalRequestedEventDto, Task> onApproval,
|
||||
Func<UserInputRequestedEventDto, Task> onUserInput,
|
||||
Func<McpOauthRequiredEventDto, Task> onMcpOAuthRequired,
|
||||
Func<ExitPlanModeRequestedEventDto, Task> onExitPlanMode,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return _handler(command, onDelta, onActivity, onApproval, cancellationToken);
|
||||
return _handler(command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken);
|
||||
}
|
||||
|
||||
public Task ResolveApprovalAsync(
|
||||
@@ -641,5 +1138,49 @@ public sealed class SidecarProtocolHostTests
|
||||
{
|
||||
return _resolveApprovalHandler(command, cancellationToken);
|
||||
}
|
||||
|
||||
public Task ResolveUserInputAsync(
|
||||
ResolveUserInputCommandDto command,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return _resolveUserInputHandler(command, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FakeSessionManager : ICopilotSessionManager
|
||||
{
|
||||
public IReadOnlyList<CopilotSessionInfoDto> Sessions { get; init; } = [];
|
||||
|
||||
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; }
|
||||
|
||||
public Task<IReadOnlyList<CopilotSessionInfoDto>> ListSessionsAsync(
|
||||
CopilotSessionListFilterDto? filter,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(Sessions);
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<CopilotSessionInfoDto>> DeleteSessionsAsync(
|
||||
string? aryxSessionId,
|
||||
string? copilotSessionId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
DeletedAryxSessionId = aryxSessionId;
|
||||
DeletedCopilotSessionId = copilotSessionId;
|
||||
return Task.FromResult(DeletedSessions);
|
||||
}
|
||||
|
||||
public Task<IReadOnlyDictionary<string, QuotaSnapshotDto>> GetQuotaAsync(
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(QuotaSnapshots);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1372
-110
File diff suppressed because it is too large
Load Diff
+45
-4
@@ -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();
|
||||
});
|
||||
|
||||
@@ -3,34 +3,55 @@ import type { BrowserWindow } from 'electron';
|
||||
|
||||
import { ipcChannels } from '@shared/contracts/channels';
|
||||
import type {
|
||||
BranchSessionInput,
|
||||
CancelSessionTurnInput,
|
||||
CreateSessionInput,
|
||||
ResolveProjectDiscoveredToolingInput,
|
||||
ResolveWorkspaceDiscoveredToolingInput,
|
||||
DismissSessionMcpAuthInput,
|
||||
DismissSessionPlanReviewInput,
|
||||
DeleteSessionInput,
|
||||
EditAndResendSessionMessageInput,
|
||||
RegenerateSessionMessageInput,
|
||||
StartSessionMcpAuthInput,
|
||||
DuplicateSessionInput,
|
||||
RenameSessionInput,
|
||||
RescanProjectConfigsInput,
|
||||
RescanProjectCustomizationInput,
|
||||
ResolveProjectDiscoveredToolingInput,
|
||||
ResolveSessionApprovalInput,
|
||||
ResolveSessionUserInputInput,
|
||||
ResolveWorkspaceDiscoveredToolingInput,
|
||||
SaveLspProfileInput,
|
||||
SaveMcpServerInput,
|
||||
SavePatternInput,
|
||||
SendSessionMessageInput,
|
||||
SetPatternFavoriteInput,
|
||||
SetProjectAgentProfileEnabledInput,
|
||||
SetSessionArchivedInput,
|
||||
SetSessionInteractionModeInput,
|
||||
SetSessionMessagePinnedInput,
|
||||
SetSessionPinnedInput,
|
||||
SetTerminalHeightInput,
|
||||
ResizeTerminalInput,
|
||||
UpdateSessionModelConfigInput,
|
||||
UpdateSessionApprovalSettingsInput,
|
||||
UpdateSessionToolingInput,
|
||||
UpdateSessionModelConfigInput,
|
||||
} from '@shared/contracts/ipc';
|
||||
import type { QuerySessionsInput } from '@shared/domain/sessionLibrary';
|
||||
import type { AppearanceTheme } from '@shared/domain/tooling';
|
||||
|
||||
import { AryxAppService } from '@main/AryxAppService';
|
||||
import { AutoUpdateService } from '@main/services/autoUpdater';
|
||||
import { createDesktopNotificationHandler } from '@main/services/desktopNotifications';
|
||||
import { applyTitleBarTheme } from '@main/windows/titleBarTheme';
|
||||
import type { UpdateStatus } from '@shared/contracts/ipc';
|
||||
|
||||
const { ipcMain } = electron;
|
||||
|
||||
export function registerIpcHandlers(window: BrowserWindow, service: AryxAppService): void {
|
||||
export function registerIpcHandlers(
|
||||
window: BrowserWindow,
|
||||
service: AryxAppService,
|
||||
autoUpdateService: AutoUpdateService,
|
||||
): void {
|
||||
ipcMain.handle(ipcChannels.describeSidecarCapabilities, () => service.describeSidecarCapabilities());
|
||||
ipcMain.handle(ipcChannels.refreshSidecarCapabilities, () => service.refreshSidecarCapabilities());
|
||||
ipcMain.handle(ipcChannels.loadWorkspace, () => service.loadWorkspace());
|
||||
@@ -47,11 +68,21 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
|
||||
ipcMain.handle(ipcChannels.rescanProjectConfigs, (_event, input: RescanProjectConfigsInput) =>
|
||||
service.rescanProjectConfigs(input.projectId),
|
||||
);
|
||||
ipcMain.handle(
|
||||
ipcChannels.rescanProjectCustomization,
|
||||
(_event, input: RescanProjectCustomizationInput) =>
|
||||
service.rescanProjectCustomization(input.projectId),
|
||||
);
|
||||
ipcMain.handle(
|
||||
ipcChannels.resolveProjectDiscoveredTooling,
|
||||
(_event, input: ResolveProjectDiscoveredToolingInput) =>
|
||||
service.resolveProjectDiscoveredTooling(input.projectId, input.serverIds, input.resolution),
|
||||
);
|
||||
ipcMain.handle(
|
||||
ipcChannels.setProjectAgentProfileEnabled,
|
||||
(_event, input: SetProjectAgentProfileEnabledInput) =>
|
||||
service.setProjectAgentProfileEnabled(input.projectId, input.agentProfileId, input.enabled),
|
||||
);
|
||||
ipcMain.handle(ipcChannels.savePattern, (_event, input: SavePatternInput) => service.savePattern(input.pattern));
|
||||
ipcMain.handle(ipcChannels.deletePattern, (_event, patternId: string) => service.deletePattern(patternId));
|
||||
ipcMain.handle(ipcChannels.setPatternFavorite, (_event, input: SetPatternFavoriteInput) =>
|
||||
@@ -62,6 +93,22 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
|
||||
applyTitleBarTheme(window, theme);
|
||||
return result;
|
||||
});
|
||||
ipcMain.handle(
|
||||
ipcChannels.setTerminalHeight,
|
||||
(_event, input: SetTerminalHeightInput) => service.setTerminalHeight(input.height),
|
||||
);
|
||||
ipcMain.handle(
|
||||
ipcChannels.setNotificationsEnabled,
|
||||
(_event, enabled: boolean) => service.setNotificationsEnabled(enabled),
|
||||
);
|
||||
ipcMain.handle(
|
||||
ipcChannels.setMinimizeToTray,
|
||||
(_event, enabled: boolean) => service.setMinimizeToTray(enabled),
|
||||
);
|
||||
ipcMain.handle(ipcChannels.checkForUpdates, () => autoUpdateService.checkForUpdates());
|
||||
ipcMain.handle(ipcChannels.installUpdate, () => {
|
||||
autoUpdateService.installUpdate();
|
||||
});
|
||||
ipcMain.handle(ipcChannels.saveMcpServer, (_event, input: SaveMcpServerInput) =>
|
||||
service.saveMcpServer(input.server),
|
||||
);
|
||||
@@ -74,6 +121,16 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
|
||||
ipcMain.handle(ipcChannels.deleteLspProfile, (_event, profileId: string) =>
|
||||
service.deleteLspProfile(profileId),
|
||||
);
|
||||
ipcMain.handle(ipcChannels.describeTerminal, () => service.describeTerminal());
|
||||
ipcMain.handle(ipcChannels.createTerminal, () => service.createTerminal());
|
||||
ipcMain.handle(ipcChannels.restartTerminal, () => service.restartTerminal());
|
||||
ipcMain.handle(ipcChannels.killTerminal, () => service.killTerminal());
|
||||
ipcMain.on(ipcChannels.writeTerminal, (_event, data: string) => {
|
||||
service.writeTerminal(data);
|
||||
});
|
||||
ipcMain.on(ipcChannels.resizeTerminal, (_event, input: ResizeTerminalInput) => {
|
||||
service.resizeTerminal(input.cols, input.rows);
|
||||
});
|
||||
ipcMain.handle(ipcChannels.updateSessionTooling, (_event, input: UpdateSessionToolingInput) =>
|
||||
service.updateSessionTooling(
|
||||
input.sessionId,
|
||||
@@ -92,6 +149,12 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
|
||||
ipcMain.handle(ipcChannels.duplicateSession, (_event, input: DuplicateSessionInput) =>
|
||||
service.duplicateSession(input.sessionId),
|
||||
);
|
||||
ipcMain.handle(ipcChannels.branchSession, (_event, input: BranchSessionInput) =>
|
||||
service.branchSession(input.sessionId, input.messageId),
|
||||
);
|
||||
ipcMain.handle(ipcChannels.setSessionMessagePinned, (_event, input: SetSessionMessagePinnedInput) =>
|
||||
service.setSessionMessagePinned(input.sessionId, input.messageId, input.isPinned),
|
||||
);
|
||||
ipcMain.handle(ipcChannels.renameSession, (_event, input: RenameSessionInput) =>
|
||||
service.renameSession(input.sessionId, input.title),
|
||||
);
|
||||
@@ -101,14 +164,38 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
|
||||
ipcMain.handle(ipcChannels.setSessionArchived, (_event, input: SetSessionArchivedInput) =>
|
||||
service.setSessionArchived(input.sessionId, input.isArchived),
|
||||
);
|
||||
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),
|
||||
service.sendSessionMessage(input.sessionId, input.content, input.attachments, input.messageMode),
|
||||
);
|
||||
ipcMain.handle(ipcChannels.cancelSessionTurn, (_event, input: CancelSessionTurnInput) =>
|
||||
service.cancelSessionTurn(input.sessionId),
|
||||
);
|
||||
ipcMain.handle(ipcChannels.resolveSessionApproval, (_event, input: ResolveSessionApprovalInput) =>
|
||||
service.resolveSessionApproval(input.sessionId, input.approvalId, input.decision),
|
||||
service.resolveSessionApproval(input.sessionId, input.approvalId, input.decision, input.alwaysApprove),
|
||||
);
|
||||
ipcMain.handle(ipcChannels.resolveSessionUserInput, (_event, input: ResolveSessionUserInputInput) =>
|
||||
service.resolveSessionUserInput(input.sessionId, input.userInputId, input.answer, input.wasFreeform),
|
||||
);
|
||||
ipcMain.handle(ipcChannels.setSessionInteractionMode, (_event, input: SetSessionInteractionModeInput) =>
|
||||
service.setSessionInteractionMode(input.sessionId, input.mode),
|
||||
);
|
||||
ipcMain.handle(ipcChannels.dismissSessionPlanReview, (_event, input: DismissSessionPlanReviewInput) =>
|
||||
service.dismissSessionPlanReview(input.sessionId),
|
||||
);
|
||||
ipcMain.handle(ipcChannels.dismissSessionMcpAuth, (_event, input: DismissSessionMcpAuthInput) =>
|
||||
service.dismissSessionMcpAuth(input.sessionId),
|
||||
);
|
||||
ipcMain.handle(ipcChannels.startSessionMcpAuth, (_event, input: StartSessionMcpAuthInput) =>
|
||||
service.startSessionMcpAuth(input.sessionId),
|
||||
);
|
||||
ipcMain.handle(
|
||||
ipcChannels.updateSessionModelConfig,
|
||||
@@ -121,6 +208,7 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
|
||||
ipcMain.handle(ipcChannels.selectSession, (_event, sessionId?: string) => service.selectSession(sessionId));
|
||||
ipcMain.handle(ipcChannels.openAppDataFolder, () => service.openAppDataFolder());
|
||||
ipcMain.handle(ipcChannels.resetLocalWorkspace, () => service.resetLocalWorkspace());
|
||||
ipcMain.handle(ipcChannels.getQuota, () => service.getQuota());
|
||||
|
||||
service.on('workspace-updated', (workspace) => {
|
||||
window.webContents.send(ipcChannels.workspaceUpdated, workspace);
|
||||
@@ -129,4 +217,30 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
|
||||
service.on('session-event', (event) => {
|
||||
window.webContents.send(ipcChannels.sessionEvent, event);
|
||||
});
|
||||
|
||||
// Desktop notifications for run completion, failure, and approval requests
|
||||
const handleNotification = createDesktopNotificationHandler(
|
||||
() => window,
|
||||
() => service.getCachedWorkspace(),
|
||||
(sessionId) => service.selectSession(sessionId),
|
||||
);
|
||||
service.on('session-event', handleNotification);
|
||||
|
||||
const sendUpdateStatus = (status: UpdateStatus) => {
|
||||
if (!window.isDestroyed()) {
|
||||
window.webContents.send(ipcChannels.updateStatus, status);
|
||||
}
|
||||
};
|
||||
autoUpdateService.onStatus(sendUpdateStatus);
|
||||
window.webContents.on('did-finish-load', () => {
|
||||
sendUpdateStatus(autoUpdateService.getStatus());
|
||||
});
|
||||
|
||||
service.on('terminal-data', (data) => {
|
||||
window.webContents.send(ipcChannels.terminalData, data);
|
||||
});
|
||||
|
||||
service.on('terminal-exit', (info) => {
|
||||
window.webContents.send(ipcChannels.terminalExit, info);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -10,3 +10,7 @@ export function getWorkspaceFilePath(): string {
|
||||
export function getScratchpadDirectoryPath(): string {
|
||||
return join(app.getPath('userData'), 'scratchpad');
|
||||
}
|
||||
|
||||
export function getScratchpadSessionPath(sessionId: string): string {
|
||||
return join(getScratchpadDirectoryPath(), sessionId);
|
||||
}
|
||||
|
||||
@@ -2,9 +2,11 @@ import { mkdir } from 'node:fs/promises';
|
||||
|
||||
import { createBuiltinPatterns, resolvePatternGraph } from '@shared/domain/pattern';
|
||||
import type { PatternDefinition } from '@shared/domain/pattern';
|
||||
import { mergeScratchpadProject } from '@shared/domain/project';
|
||||
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 { normalizeSessionBranchOrigin, type SessionRecord } from '@shared/domain/session';
|
||||
import {
|
||||
normalizeSessionToolingSelection,
|
||||
normalizeWorkspaceSettings,
|
||||
@@ -17,7 +19,11 @@ import {
|
||||
import { createWorkspaceSeed, type WorkspaceState } from '@shared/domain/workspace';
|
||||
import { nowIso } from '@shared/utils/ids';
|
||||
|
||||
import { getScratchpadDirectoryPath, getWorkspaceFilePath } from '@main/persistence/appPaths';
|
||||
import {
|
||||
getScratchpadDirectoryPath,
|
||||
getScratchpadSessionPath,
|
||||
getWorkspaceFilePath,
|
||||
} from '@main/persistence/appPaths';
|
||||
import { readJsonFile, writeJsonFile } from '@main/persistence/jsonStore';
|
||||
|
||||
function mergePatterns(existingPatterns: PatternDefinition[]): PatternDefinition[] {
|
||||
@@ -68,9 +74,33 @@ 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),
|
||||
...normalizePendingApprovalState({
|
||||
pendingApproval: session.pendingApproval,
|
||||
pendingApprovalQueue: session.pendingApprovalQueue,
|
||||
}),
|
||||
};
|
||||
if (!isScratchpadProject(normalizedSession.projectId)) {
|
||||
return normalizedSession;
|
||||
}
|
||||
|
||||
const cwd = normalizedSession.cwd ?? getScratchpadSessionPath(normalizedSession.id);
|
||||
await mkdir(cwd, { recursive: true });
|
||||
return {
|
||||
...normalizedSession,
|
||||
cwd,
|
||||
};
|
||||
}));
|
||||
const settings = normalizeWorkspaceSettings(stored.settings);
|
||||
|
||||
const workspace: WorkspaceState = {
|
||||
@@ -81,16 +111,7 @@ export class WorkspaceRepository {
|
||||
graph: resolvePatternGraph(pattern),
|
||||
})),
|
||||
projects,
|
||||
sessions: (stored.sessions ?? []).map((session) => ({
|
||||
...session,
|
||||
runs: normalizeSessionRunRecords(session.runs),
|
||||
tooling: normalizeSessionToolingSelection(session.tooling),
|
||||
approvalSettings: normalizeSessionApprovalSettings(session.approvalSettings),
|
||||
...normalizePendingApprovalState({
|
||||
pendingApproval: session.pendingApproval,
|
||||
pendingApprovalQueue: session.pendingApprovalQueue,
|
||||
}),
|
||||
})),
|
||||
sessions,
|
||||
settings,
|
||||
selectedProjectId: projects.some((project) => project.id === stored.selectedProjectId)
|
||||
? stored.selectedProjectId
|
||||
@@ -103,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(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
import electronUpdater from 'electron-updater';
|
||||
|
||||
import type {
|
||||
UpdateDownloadProgress,
|
||||
UpdateStatus,
|
||||
} from '@shared/contracts/ipc';
|
||||
|
||||
interface AutoUpdateInfoLike {
|
||||
version?: string | null;
|
||||
releaseDate?: string | null;
|
||||
releaseNotes?: unknown;
|
||||
}
|
||||
|
||||
interface AutoUpdateProgressLike {
|
||||
bytesPerSecond: number;
|
||||
percent: number;
|
||||
total: number;
|
||||
transferred: number;
|
||||
}
|
||||
|
||||
type AutoUpdateListener = (...args: any[]) => void;
|
||||
|
||||
interface AutoUpdaterLike {
|
||||
autoDownload: boolean;
|
||||
autoInstallOnAppQuit: boolean;
|
||||
on(event: string, listener: AutoUpdateListener): this;
|
||||
removeListener(event: string, listener: AutoUpdateListener): this;
|
||||
checkForUpdates(): Promise<unknown>;
|
||||
quitAndInstall(): void;
|
||||
}
|
||||
|
||||
export interface AutoUpdateScheduler {
|
||||
setTimeout(callback: () => void, delayMs: number): unknown;
|
||||
clearTimeout(handle: unknown): void;
|
||||
setInterval(callback: () => void, delayMs: number): unknown;
|
||||
clearInterval(handle: unknown): void;
|
||||
}
|
||||
|
||||
export interface AutoUpdateServiceOptions {
|
||||
isPackaged: boolean;
|
||||
startupDelayMs?: number;
|
||||
recheckIntervalMs?: number;
|
||||
updater?: AutoUpdaterLike;
|
||||
scheduler?: AutoUpdateScheduler;
|
||||
}
|
||||
|
||||
const DEFAULT_STARTUP_DELAY_MS = 10_000;
|
||||
const DEFAULT_RECHECK_INTERVAL_MS = 4 * 60 * 60 * 1000;
|
||||
|
||||
const defaultScheduler: AutoUpdateScheduler = {
|
||||
setTimeout: (callback, delayMs) => globalThis.setTimeout(callback, delayMs),
|
||||
clearTimeout: (handle) => globalThis.clearTimeout(handle as ReturnType<typeof setTimeout>),
|
||||
setInterval: (callback, delayMs) => globalThis.setInterval(callback, delayMs),
|
||||
clearInterval: (handle) => globalThis.clearInterval(handle as ReturnType<typeof setInterval>),
|
||||
};
|
||||
|
||||
function normalizeOptionalString(value: string | null | undefined): string | undefined {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function normalizeReleaseNotes(value: unknown): string | undefined {
|
||||
if (typeof value === 'string') {
|
||||
return normalizeOptionalString(value);
|
||||
}
|
||||
|
||||
if (!Array.isArray(value)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const notes = value
|
||||
.map((item) => {
|
||||
if (typeof item === 'string') {
|
||||
return normalizeOptionalString(item);
|
||||
}
|
||||
|
||||
if (!item || typeof item !== 'object') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const record = item as { note?: unknown; version?: unknown };
|
||||
const version = typeof record.version === 'string' ? normalizeOptionalString(record.version) : undefined;
|
||||
const note = typeof record.note === 'string' ? normalizeOptionalString(record.note) : undefined;
|
||||
if (version && note) {
|
||||
return `${version}\n${note}`;
|
||||
}
|
||||
|
||||
return note ?? version;
|
||||
})
|
||||
.filter((entry): entry is string => Boolean(entry));
|
||||
|
||||
return notes.length > 0 ? notes.join('\n\n') : undefined;
|
||||
}
|
||||
|
||||
function normalizeProgress(progress: AutoUpdateProgressLike): UpdateDownloadProgress {
|
||||
return {
|
||||
bytesPerSecond: progress.bytesPerSecond,
|
||||
percent: progress.percent,
|
||||
total: progress.total,
|
||||
transferred: progress.transferred,
|
||||
};
|
||||
}
|
||||
|
||||
function createStatusFromInfo(
|
||||
state: Extract<UpdateStatus['state'], 'available' | 'downloaded'>,
|
||||
info: AutoUpdateInfoLike,
|
||||
): UpdateStatus {
|
||||
return {
|
||||
state,
|
||||
version: normalizeOptionalString(info.version),
|
||||
releaseDate: normalizeOptionalString(info.releaseDate),
|
||||
releaseNotes: normalizeReleaseNotes(info.releaseNotes),
|
||||
};
|
||||
}
|
||||
|
||||
function resolveErrorMessage(error: unknown): string {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
if (typeof error === 'string') {
|
||||
return error;
|
||||
}
|
||||
|
||||
return 'Unknown update error.';
|
||||
}
|
||||
|
||||
export class AutoUpdateService {
|
||||
private readonly updater: AutoUpdaterLike;
|
||||
|
||||
private readonly scheduler: AutoUpdateScheduler;
|
||||
|
||||
private readonly listeners = new Set<(status: UpdateStatus) => void>();
|
||||
|
||||
private status: UpdateStatus = { state: 'idle' };
|
||||
|
||||
private started = false;
|
||||
|
||||
private initialCheckHandle?: unknown;
|
||||
|
||||
private periodicCheckHandle?: unknown;
|
||||
|
||||
private pendingCheck?: Promise<UpdateStatus>;
|
||||
|
||||
private readonly checkingListener = () => {
|
||||
this.publishStatus({ state: 'checking' });
|
||||
};
|
||||
|
||||
private readonly availableListener = (info: AutoUpdateInfoLike) => {
|
||||
this.publishStatus(createStatusFromInfo('available', info));
|
||||
};
|
||||
|
||||
private readonly notAvailableListener = () => {
|
||||
this.publishStatus({ state: 'idle' });
|
||||
};
|
||||
|
||||
private readonly progressListener = (progress: AutoUpdateProgressLike) => {
|
||||
this.publishStatus({
|
||||
...this.status,
|
||||
state: 'downloading',
|
||||
downloadProgress: normalizeProgress(progress),
|
||||
});
|
||||
};
|
||||
|
||||
private readonly downloadedListener = (info: AutoUpdateInfoLike) => {
|
||||
this.publishStatus(createStatusFromInfo('downloaded', info));
|
||||
};
|
||||
|
||||
private readonly errorListener = (error: unknown) => {
|
||||
this.publishStatus({
|
||||
...this.status,
|
||||
state: 'error',
|
||||
error: resolveErrorMessage(error),
|
||||
});
|
||||
};
|
||||
|
||||
constructor(private readonly options: AutoUpdateServiceOptions) {
|
||||
this.updater = options.updater
|
||||
?? (electronUpdater as { autoUpdater: AutoUpdaterLike }).autoUpdater;
|
||||
this.scheduler = options.scheduler ?? defaultScheduler;
|
||||
this.updater.autoDownload = true;
|
||||
this.updater.autoInstallOnAppQuit = false;
|
||||
|
||||
this.updater.on('checking-for-update', this.checkingListener);
|
||||
this.updater.on('update-available', this.availableListener);
|
||||
this.updater.on('update-not-available', this.notAvailableListener);
|
||||
this.updater.on('download-progress', this.progressListener);
|
||||
this.updater.on('update-downloaded', this.downloadedListener);
|
||||
this.updater.on('error', this.errorListener);
|
||||
}
|
||||
|
||||
start(): void {
|
||||
if (this.started || !this.options.isPackaged) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.started = true;
|
||||
this.initialCheckHandle = this.scheduler.setTimeout(() => {
|
||||
void this.checkForUpdates();
|
||||
}, this.options.startupDelayMs ?? DEFAULT_STARTUP_DELAY_MS);
|
||||
this.periodicCheckHandle = this.scheduler.setInterval(() => {
|
||||
void this.checkForUpdates();
|
||||
}, this.options.recheckIntervalMs ?? DEFAULT_RECHECK_INTERVAL_MS);
|
||||
}
|
||||
|
||||
getStatus(): UpdateStatus {
|
||||
return this.cloneStatus(this.status);
|
||||
}
|
||||
|
||||
onStatus(listener: (status: UpdateStatus) => void): () => void {
|
||||
this.listeners.add(listener);
|
||||
return () => {
|
||||
this.listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
async checkForUpdates(): Promise<UpdateStatus> {
|
||||
if (!this.options.isPackaged) {
|
||||
return this.getStatus();
|
||||
}
|
||||
|
||||
if (this.pendingCheck) {
|
||||
return this.pendingCheck;
|
||||
}
|
||||
|
||||
const request = this.updater.checkForUpdates()
|
||||
.catch((error) => {
|
||||
this.errorListener(error);
|
||||
})
|
||||
.then(() => this.getStatus())
|
||||
.finally(() => {
|
||||
if (this.pendingCheck === request) {
|
||||
this.pendingCheck = undefined;
|
||||
}
|
||||
});
|
||||
|
||||
this.pendingCheck = request;
|
||||
return request;
|
||||
}
|
||||
|
||||
installUpdate(): void {
|
||||
if (this.status.state !== 'downloaded') {
|
||||
return;
|
||||
}
|
||||
|
||||
this.updater.quitAndInstall();
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.initialCheckHandle !== undefined) {
|
||||
this.scheduler.clearTimeout(this.initialCheckHandle);
|
||||
this.initialCheckHandle = undefined;
|
||||
}
|
||||
|
||||
if (this.periodicCheckHandle !== undefined) {
|
||||
this.scheduler.clearInterval(this.periodicCheckHandle);
|
||||
this.periodicCheckHandle = undefined;
|
||||
}
|
||||
|
||||
this.updater.removeListener('checking-for-update', this.checkingListener);
|
||||
this.updater.removeListener('update-available', this.availableListener);
|
||||
this.updater.removeListener('update-not-available', this.notAvailableListener);
|
||||
this.updater.removeListener('download-progress', this.progressListener);
|
||||
this.updater.removeListener('update-downloaded', this.downloadedListener);
|
||||
this.updater.removeListener('error', this.errorListener);
|
||||
this.listeners.clear();
|
||||
}
|
||||
|
||||
private publishStatus(status: UpdateStatus): void {
|
||||
this.status = this.cloneStatus(status);
|
||||
for (const listener of this.listeners) {
|
||||
listener(this.cloneStatus(this.status));
|
||||
}
|
||||
}
|
||||
|
||||
private cloneStatus(status: UpdateStatus): UpdateStatus {
|
||||
return status.downloadProgress
|
||||
? { ...status, downloadProgress: { ...status.downloadProgress } }
|
||||
: { ...status };
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -0,0 +1,563 @@
|
||||
import { randomBytes, createHash } from 'node:crypto';
|
||||
import { createServer, type Server, type IncomingMessage, type ServerResponse } from 'node:http';
|
||||
|
||||
import electron from 'electron';
|
||||
|
||||
import type { McpOauthStaticClientConfig } from '@shared/domain/mcpAuth';
|
||||
|
||||
import { storeToken, buildWellKnownUrl, buildWellKnownUrlFallback, buildWellKnownUrlOriginOnly, type McpOAuthToken } from './mcpTokenStore';
|
||||
|
||||
const { shell } = electron;
|
||||
|
||||
/* ── Public API ──────────────────────────────────────────────── */
|
||||
|
||||
export interface McpOAuthFlowOptions {
|
||||
serverUrl: string;
|
||||
staticClientConfig?: McpOauthStaticClientConfig;
|
||||
onStatusChange?: (status: 'discovering' | 'awaiting-consent' | 'exchanging') => void;
|
||||
}
|
||||
|
||||
export interface McpOAuthFlowResult {
|
||||
success: boolean;
|
||||
token?: McpOAuthToken;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
const VSCODE_REDIRECT_URI = 'https://vscode.dev/redirect';
|
||||
|
||||
interface KnownOAuthProvider {
|
||||
id: 'github' | 'entra';
|
||||
clientId: string;
|
||||
redirectMode: 'vscode-dev';
|
||||
authorizationEndpoint?: string;
|
||||
tokenEndpoint?: string;
|
||||
scopes?: readonly string[];
|
||||
authorizationParams?: Readonly<Record<string, string>>;
|
||||
includeOfflineAccess?: boolean;
|
||||
}
|
||||
|
||||
interface KnownOAuthProviderConfig extends KnownOAuthProvider {
|
||||
matches: (url: URL) => boolean;
|
||||
}
|
||||
|
||||
const GITHUB_PROVIDER_SCOPES = [
|
||||
'codespace',
|
||||
'gist',
|
||||
'notifications',
|
||||
'project',
|
||||
'read:org',
|
||||
'read:packages',
|
||||
'read:project',
|
||||
'read:user',
|
||||
'repo',
|
||||
'user:email',
|
||||
'workflow',
|
||||
'write:packages',
|
||||
] as const;
|
||||
|
||||
const knownOAuthProviders: readonly KnownOAuthProviderConfig[] = [
|
||||
{
|
||||
id: 'github',
|
||||
clientId: '01ab8ac9400c4e429b23',
|
||||
redirectMode: 'vscode-dev',
|
||||
authorizationEndpoint: 'https://github.com/login/oauth/authorize',
|
||||
tokenEndpoint: 'https://github.com/login/oauth/access_token',
|
||||
scopes: GITHUB_PROVIDER_SCOPES,
|
||||
authorizationParams: { prompt: 'select_account' },
|
||||
includeOfflineAccess: false,
|
||||
matches: (url) => url.hostname === 'github.com',
|
||||
},
|
||||
{
|
||||
id: 'entra',
|
||||
clientId: 'aebc6443-996d-45c2-90f0-388ff96faa56',
|
||||
redirectMode: 'vscode-dev',
|
||||
includeOfflineAccess: true,
|
||||
matches: (url) => url.hostname === 'login.microsoftonline.com',
|
||||
},
|
||||
] as const;
|
||||
|
||||
export function resolveKnownProvider(authServerUrl: string): KnownOAuthProvider | undefined {
|
||||
try {
|
||||
const parsed = new URL(authServerUrl);
|
||||
const match = knownOAuthProviders.find((candidate) => candidate.matches(parsed));
|
||||
if (!match) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const { matches: _matches, ...provider } = match;
|
||||
return provider;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Probes an MCP server URL to determine if it requires OAuth authentication.
|
||||
* Returns true if the server responds with 401 and has discoverable OAuth metadata.
|
||||
*/
|
||||
export async function requiresOAuth(serverUrl: string): Promise<boolean> {
|
||||
try {
|
||||
const metadata = await fetchWellKnownMetadata(serverUrl, 'oauth-protected-resource');
|
||||
if (!metadata) {
|
||||
console.log(`[aryx oauth] No PRM found for ${serverUrl}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
const hasAuthServers = Array.isArray(metadata.authorization_servers) && metadata.authorization_servers.length > 0;
|
||||
console.log(`[aryx oauth] PRM found for ${serverUrl}: authorization_servers=${hasAuthServers}`);
|
||||
return hasAuthServers;
|
||||
} catch (err) {
|
||||
console.warn(`[aryx oauth] Probe failed for ${serverUrl}:`, err instanceof Error ? err.message : err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the full MCP OAuth 2.1 + PKCE flow:
|
||||
* 1. Discover protected resource metadata (RFC 9728)
|
||||
* 2. Fetch authorization server metadata (RFC 8414)
|
||||
* 3. Resolve client ID (static config or dynamic registration per RFC 7591)
|
||||
* 4. PKCE code verifier + challenge
|
||||
* 5. Open browser for user consent
|
||||
* 6. Local callback server receives auth code
|
||||
* 7. Exchange code for token
|
||||
*/
|
||||
export async function performMcpOAuthFlow(options: McpOAuthFlowOptions): Promise<McpOAuthFlowResult> {
|
||||
const { serverUrl, staticClientConfig, onStatusChange } = options;
|
||||
|
||||
try {
|
||||
onStatusChange?.('discovering');
|
||||
|
||||
const prm = await discoverProtectedResource(serverUrl);
|
||||
const knownProvider = resolveKnownProvider(prm.authorizationServer);
|
||||
const { verifier, challenge } = generatePkceChallenge();
|
||||
const {
|
||||
localRedirectUri,
|
||||
hostedRedirectState,
|
||||
waitForCallback,
|
||||
close,
|
||||
} = await startCallbackServer();
|
||||
|
||||
try {
|
||||
const metadata = await resolveAuthServerMetadata(prm.authorizationServer, knownProvider);
|
||||
const clientId = staticClientConfig?.clientId
|
||||
?? knownProvider?.clientId
|
||||
?? await dynamicClientRegistration(metadata, localRedirectUri, serverUrl);
|
||||
const usesHostedRedirect = knownProvider?.redirectMode === 'vscode-dev';
|
||||
const scopes = buildScopes(knownProvider, prm.resourceScopes, metadata.scopes_supported);
|
||||
const redirectUri = usesHostedRedirect ? VSCODE_REDIRECT_URI : localRedirectUri;
|
||||
const state = usesHostedRedirect ? hostedRedirectState : randomBytes(16).toString('hex');
|
||||
|
||||
const authUrl = buildAuthorizationUrl(metadata.authorization_endpoint, {
|
||||
clientId,
|
||||
redirectUri,
|
||||
codeChallenge: challenge,
|
||||
scope: scopes,
|
||||
state,
|
||||
extraParams: knownProvider?.authorizationParams,
|
||||
});
|
||||
|
||||
onStatusChange?.('awaiting-consent');
|
||||
await shell.openExternal(authUrl);
|
||||
|
||||
const code = await waitForCallback();
|
||||
|
||||
onStatusChange?.('exchanging');
|
||||
const token = await exchangeCodeForToken(metadata.token_endpoint, {
|
||||
code,
|
||||
clientId,
|
||||
redirectUri,
|
||||
codeVerifier: verifier,
|
||||
});
|
||||
|
||||
storeToken(serverUrl, token);
|
||||
return { success: true, token };
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
return { success: false, error: message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the OAuth scope string.
|
||||
* Priority: provider-specific scopes > PRM resource scopes > auth server scopes.
|
||||
* `offline_access` is only appended when the provider supports/needs it.
|
||||
*/
|
||||
export function buildScopes(
|
||||
knownProvider: KnownOAuthProvider | undefined,
|
||||
resourceScopes?: string[],
|
||||
authServerScopes?: string[],
|
||||
): string {
|
||||
const scopes = knownProvider?.scopes ?? resourceScopes ?? authServerScopes ?? [];
|
||||
if (scopes.length === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const set = new Set(scopes);
|
||||
if (knownProvider?.includeOfflineAccess ?? true) {
|
||||
set.add('offline_access');
|
||||
}
|
||||
return [...set].join(' ');
|
||||
}
|
||||
|
||||
/* ── Discovery ───────────────────────────────────────────────── */
|
||||
|
||||
interface ProtectedResourceMetadata {
|
||||
resource: string;
|
||||
authorization_servers?: string[];
|
||||
scopes_supported?: string[];
|
||||
}
|
||||
|
||||
interface AuthServerMetadata {
|
||||
issuer: string;
|
||||
authorization_endpoint: string;
|
||||
token_endpoint: string;
|
||||
registration_endpoint?: string;
|
||||
scopes_supported?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to fetch a well-known metadata document from a base URL.
|
||||
* Attempts the RFC 9728 compliant path first (inserted after origin),
|
||||
* then falls back to the appended path (used by some servers).
|
||||
* Returns the parsed JSON or undefined if neither endpoint responds.
|
||||
*/
|
||||
async function fetchWellKnownMetadata(baseUrl: string, suffix: string): Promise<Record<string, unknown> | undefined> {
|
||||
const rfcUrl = buildWellKnownUrl(baseUrl, suffix);
|
||||
const fallbackUrl = buildWellKnownUrlFallback(baseUrl, suffix);
|
||||
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 {
|
||||
console.log(`[aryx oauth] Trying well-known at ${url}…`);
|
||||
const response = await fetch(url, { signal: AbortSignal.timeout(5_000) });
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
console.log(`[aryx oauth] Found well-known metadata at ${url}`);
|
||||
return data;
|
||||
}
|
||||
console.log(`[aryx oauth] ${url} returned ${response.status}`);
|
||||
} catch {
|
||||
console.log(`[aryx oauth] ${url} unreachable`);
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
interface PrmDiscoveryResult {
|
||||
authorizationServer: string;
|
||||
resourceScopes?: string[];
|
||||
}
|
||||
|
||||
async function discoverProtectedResource(serverUrl: string): Promise<PrmDiscoveryResult> {
|
||||
const metadata = await fetchWellKnownMetadata(serverUrl, 'oauth-protected-resource');
|
||||
if (!metadata) {
|
||||
throw new Error('Protected Resource Metadata discovery failed: no well-known endpoint found');
|
||||
}
|
||||
|
||||
const prm = metadata as unknown as ProtectedResourceMetadata;
|
||||
const authServer = prm.authorization_servers?.[0];
|
||||
if (!authServer) {
|
||||
throw new Error('No authorization server found in Protected Resource Metadata');
|
||||
}
|
||||
|
||||
return { authorizationServer: authServer, resourceScopes: prm.scopes_supported };
|
||||
}
|
||||
|
||||
async function fetchAuthServerMetadata(authServerUrl: string): Promise<AuthServerMetadata> {
|
||||
// RFC 8414 suffix first, then OpenID Connect Discovery suffix (used by Entra ID, Google, etc.)
|
||||
const metadata =
|
||||
(await fetchWellKnownMetadata(authServerUrl, 'oauth-authorization-server')) ??
|
||||
(await fetchWellKnownMetadata(authServerUrl, 'openid-configuration'));
|
||||
|
||||
if (!metadata) {
|
||||
throw new Error('Authorization Server Metadata fetch failed: no well-known endpoint found');
|
||||
}
|
||||
|
||||
const asMeta = metadata as unknown as AuthServerMetadata;
|
||||
if (!asMeta.authorization_endpoint || !asMeta.token_endpoint) {
|
||||
throw new Error('Authorization server metadata is missing required endpoints');
|
||||
}
|
||||
|
||||
return asMeta;
|
||||
}
|
||||
|
||||
async function resolveAuthServerMetadata(
|
||||
authServerUrl: string,
|
||||
knownProvider: KnownOAuthProvider | undefined,
|
||||
): Promise<AuthServerMetadata> {
|
||||
if (knownProvider?.authorizationEndpoint && knownProvider?.tokenEndpoint) {
|
||||
return {
|
||||
issuer: authServerUrl,
|
||||
authorization_endpoint: knownProvider.authorizationEndpoint,
|
||||
token_endpoint: knownProvider.tokenEndpoint,
|
||||
scopes_supported: knownProvider.scopes ? [...knownProvider.scopes] : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
return fetchAuthServerMetadata(authServerUrl);
|
||||
}
|
||||
|
||||
/* ── Dynamic Client Registration (RFC 7591) ──────────────────── */
|
||||
|
||||
async function dynamicClientRegistration(
|
||||
metadata: AuthServerMetadata,
|
||||
redirectUri: string,
|
||||
serverUrl: string,
|
||||
): Promise<string> {
|
||||
if (!metadata.registration_endpoint) {
|
||||
throw new Error(
|
||||
'No static client ID provided and the authorization server does not support dynamic client registration',
|
||||
);
|
||||
}
|
||||
|
||||
const response = await fetch(metadata.registration_endpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
client_name: 'Aryx',
|
||||
redirect_uris: [redirectUri],
|
||||
grant_types: ['authorization_code'],
|
||||
response_types: ['code'],
|
||||
token_endpoint_auth_method: 'none',
|
||||
scope: metadata.scopes_supported?.join(' ') ?? '',
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Dynamic client registration failed: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const registration = await response.json();
|
||||
if (!registration.client_id) {
|
||||
throw new Error('Dynamic client registration response is missing client_id');
|
||||
}
|
||||
|
||||
return registration.client_id;
|
||||
}
|
||||
|
||||
/* ── PKCE ────────────────────────────────────────────────────── */
|
||||
|
||||
function generatePkceChallenge(): { verifier: string; challenge: string } {
|
||||
const verifier = randomBytes(32).toString('base64url');
|
||||
const challenge = createHash('sha256').update(verifier).digest('base64url');
|
||||
return { verifier, challenge };
|
||||
}
|
||||
|
||||
/* ── Authorization URL ───────────────────────────────────────── */
|
||||
|
||||
function buildAuthorizationUrl(
|
||||
authorizationEndpoint: string,
|
||||
params: {
|
||||
clientId: string;
|
||||
redirectUri: string;
|
||||
codeChallenge: string;
|
||||
scope: string;
|
||||
state: string;
|
||||
extraParams?: Readonly<Record<string, string>>;
|
||||
},
|
||||
): string {
|
||||
const url = new URL(authorizationEndpoint);
|
||||
url.searchParams.set('response_type', 'code');
|
||||
url.searchParams.set('client_id', params.clientId);
|
||||
url.searchParams.set('redirect_uri', params.redirectUri);
|
||||
url.searchParams.set('code_challenge', params.codeChallenge);
|
||||
url.searchParams.set('code_challenge_method', 'S256');
|
||||
if (params.scope) {
|
||||
url.searchParams.set('scope', params.scope);
|
||||
}
|
||||
url.searchParams.set('state', params.state);
|
||||
for (const [key, value] of Object.entries(params.extraParams ?? {})) {
|
||||
url.searchParams.set(key, value);
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
/* ── Local callback server ───────────────────────────────────── */
|
||||
|
||||
interface CallbackServerHandle {
|
||||
port: number;
|
||||
localRedirectUri: string;
|
||||
hostedRedirectState: string;
|
||||
waitForCallback: () => Promise<string>;
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
function startCallbackServer(): Promise<CallbackServerHandle> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false;
|
||||
let callbackResolve: (code: string) => void;
|
||||
let callbackReject: (err: Error) => void;
|
||||
|
||||
const callbackPromise = new Promise<string>((res, rej) => {
|
||||
callbackResolve = res;
|
||||
callbackReject = rej;
|
||||
});
|
||||
|
||||
const server: Server = createServer((req: IncomingMessage, res: ServerResponse) => {
|
||||
const url = new URL(req.url ?? '/', `http://127.0.0.1`);
|
||||
const code = url.searchParams.get('code');
|
||||
const error = url.searchParams.get('error');
|
||||
const errorDescription = url.searchParams.get('error_description');
|
||||
|
||||
// Ignore requests without code or error (e.g. favicon)
|
||||
if (!code && !error) {
|
||||
res.writeHead(404);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
res.writeHead(200, { 'Content-Type': 'text/html' });
|
||||
if (code) {
|
||||
res.end('<html><body><h2>Authentication successful</h2><p>You can close this tab.</p></body></html>');
|
||||
callbackResolve(code);
|
||||
} else {
|
||||
const msg = errorDescription ?? error ?? 'Unknown error';
|
||||
res.end(`<html><body><h2>Authentication failed</h2><p>${escapeHtml(msg)}</p></body></html>`);
|
||||
callbackReject(new Error(`OAuth callback error: ${msg}`));
|
||||
}
|
||||
});
|
||||
|
||||
server.on('error', (err) => {
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
settled = true;
|
||||
const addr = server.address();
|
||||
if (!addr || typeof addr === 'string') {
|
||||
reject(new Error('Failed to bind callback server'));
|
||||
return;
|
||||
}
|
||||
|
||||
resolve({
|
||||
port: addr.port,
|
||||
localRedirectUri: `http://127.0.0.1:${addr.port}/callback`,
|
||||
hostedRedirectState: buildHostedRedirectState(`http://127.0.0.1:${addr.port}/callback`),
|
||||
waitForCallback: () => callbackPromise,
|
||||
close: () => server.close(),
|
||||
});
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
server.close();
|
||||
reject(new Error('Callback server start timed out'));
|
||||
}
|
||||
}, 5_000);
|
||||
});
|
||||
}
|
||||
|
||||
function buildHostedRedirectState(localRedirectUri: string): string {
|
||||
const stateUrl = new URL(localRedirectUri);
|
||||
stateUrl.searchParams.set('nonce', randomBytes(16).toString('base64url'));
|
||||
return stateUrl.toString();
|
||||
}
|
||||
|
||||
/* ── Token exchange ──────────────────────────────────────────── */
|
||||
|
||||
async function exchangeCodeForToken(
|
||||
tokenEndpoint: string,
|
||||
params: {
|
||||
code: string;
|
||||
clientId: string;
|
||||
redirectUri: string;
|
||||
codeVerifier: string;
|
||||
},
|
||||
): Promise<McpOAuthToken> {
|
||||
const body = new URLSearchParams({
|
||||
grant_type: 'authorization_code',
|
||||
code: params.code,
|
||||
client_id: params.clientId,
|
||||
redirect_uri: params.redirectUri,
|
||||
code_verifier: params.codeVerifier,
|
||||
});
|
||||
|
||||
const response = await fetch(tokenEndpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
body: body.toString(),
|
||||
});
|
||||
|
||||
const data = parseTokenResponseBody(await response.text(), response.headers.get('content-type'));
|
||||
if (!response.ok) {
|
||||
const errorMessage =
|
||||
typeof data.error_description === 'string'
|
||||
? data.error_description
|
||||
: typeof data.error === 'string'
|
||||
? data.error
|
||||
: `${response.status} ${response.statusText}`;
|
||||
throw new Error(`Token exchange failed: ${errorMessage}`);
|
||||
}
|
||||
|
||||
const accessToken = typeof data.access_token === 'string' ? data.access_token : undefined;
|
||||
const tokenType = typeof data.token_type === 'string' ? data.token_type : 'Bearer';
|
||||
const scope = typeof data.scope === 'string' ? data.scope : undefined;
|
||||
const refreshToken = typeof data.refresh_token === 'string' ? data.refresh_token : undefined;
|
||||
|
||||
if (!accessToken) {
|
||||
throw new Error('Token response is missing access_token');
|
||||
}
|
||||
|
||||
const token: McpOAuthToken = {
|
||||
accessToken,
|
||||
tokenType,
|
||||
scope,
|
||||
};
|
||||
|
||||
if (data.expires_in && typeof data.expires_in === 'number') {
|
||||
token.expiresAt = Date.now() + data.expires_in * 1_000;
|
||||
}
|
||||
|
||||
if (refreshToken) {
|
||||
token.refreshToken = refreshToken;
|
||||
}
|
||||
|
||||
return token;
|
||||
}
|
||||
|
||||
export function parseTokenResponseBody(body: string, contentType?: string | null): Record<string, unknown> {
|
||||
const normalizedContentType = contentType?.toLowerCase() ?? '';
|
||||
if (normalizedContentType.includes('application/json') || body.trim().startsWith('{')) {
|
||||
const parsed = JSON.parse(body) as unknown;
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
return parsed as Record<string, unknown>;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
return Object.fromEntries(new URLSearchParams(body).entries());
|
||||
}
|
||||
|
||||
/* ── Utilities ───────────────────────────────────────────────── */
|
||||
|
||||
function escapeHtml(text: string): string {
|
||||
return text
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* In-memory OAuth token store keyed by MCP server URL.
|
||||
* Tokens are lost on app restart by design (phase 1).
|
||||
*/
|
||||
|
||||
export interface McpOAuthToken {
|
||||
accessToken: string;
|
||||
tokenType: string;
|
||||
expiresAt?: number;
|
||||
refreshToken?: string;
|
||||
scope?: string;
|
||||
}
|
||||
|
||||
const tokens = new Map<string, McpOAuthToken>();
|
||||
|
||||
export function getStoredToken(serverUrl: string): McpOAuthToken | undefined {
|
||||
const token = tokens.get(normalizeUrl(serverUrl));
|
||||
if (!token) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (token.expiresAt && Date.now() >= token.expiresAt) {
|
||||
tokens.delete(normalizeUrl(serverUrl));
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return token;
|
||||
}
|
||||
|
||||
export function storeToken(serverUrl: string, token: McpOAuthToken): void {
|
||||
tokens.set(normalizeUrl(serverUrl), token);
|
||||
}
|
||||
|
||||
export function clearToken(serverUrl: string): void {
|
||||
tokens.delete(normalizeUrl(serverUrl));
|
||||
}
|
||||
|
||||
export function clearAllTokens(): void {
|
||||
tokens.clear();
|
||||
}
|
||||
|
||||
function normalizeUrl(url: string): string {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
return parsed.origin + parsed.pathname.replace(/\/+$/, '');
|
||||
} catch {
|
||||
return url.toLowerCase().replace(/\/+$/, '');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs well-known URL candidates for a given base URL.
|
||||
* Returns the RFC 9728 compliant URL first (inserted after origin),
|
||||
* then the appended fallback (some servers use this instead).
|
||||
*
|
||||
* RFC 9728: `https://example.com/.well-known/oauth-protected-resource/mcp/`
|
||||
* Fallback: `https://example.com/mcp/.well-known/oauth-protected-resource`
|
||||
*/
|
||||
export function buildWellKnownUrl(baseUrl: string, wellKnownSuffix: string): string {
|
||||
const parsed = new URL(baseUrl);
|
||||
const path = parsed.pathname === '/' ? '' : parsed.pathname;
|
||||
return `${parsed.origin}/.well-known/${wellKnownSuffix}${path}`;
|
||||
}
|
||||
|
||||
export function buildWellKnownUrlFallback(baseUrl: string, wellKnownSuffix: string): string {
|
||||
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}`;
|
||||
}
|
||||
@@ -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); },
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -30,6 +30,7 @@ export function validateSessionToolingSelectionIds(
|
||||
export function buildRunTurnToolingConfig(
|
||||
tooling: WorkspaceToolingSettings,
|
||||
selection: SessionToolingSelection,
|
||||
tokenLookup?: (serverUrl: string) => string | undefined,
|
||||
): RunTurnToolingConfig | undefined {
|
||||
const mcpServersById = new Map<string, McpServerDefinition>(
|
||||
tooling.mcpServers.map((server) => [server.id, server]),
|
||||
@@ -68,7 +69,7 @@ export function buildRunTurnToolingConfig(
|
||||
tools: [...server.tools],
|
||||
timeoutMs: server.timeoutMs,
|
||||
url: server.url,
|
||||
headers: server.headers ? { ...server.headers } : undefined,
|
||||
headers: mergeAuthorizationHeader(server.url, server.headers, tokenLookup),
|
||||
},
|
||||
];
|
||||
});
|
||||
@@ -100,3 +101,19 @@ export function buildRunTurnToolingConfig(
|
||||
lspProfiles,
|
||||
};
|
||||
}
|
||||
|
||||
function mergeAuthorizationHeader(
|
||||
serverUrl: string,
|
||||
configHeaders: Record<string, string> | undefined,
|
||||
tokenLookup: ((serverUrl: string) => string | undefined) | undefined,
|
||||
): Record<string, string> | undefined {
|
||||
const bearerToken = tokenLookup?.(serverUrl);
|
||||
if (!bearerToken) {
|
||||
return configHeaders ? { ...configHeaders } : undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
...(configHeaders ?? {}),
|
||||
Authorization: `Bearer ${bearerToken}`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,6 +1,29 @@
|
||||
import type { AgentActivityEvent, ApprovalRequestedEvent, TurnDeltaEvent } from '@shared/contracts/sidecar';
|
||||
import type {
|
||||
AgentActivityEvent,
|
||||
ApprovalRequestedEvent,
|
||||
ExitPlanModeRequestedEvent,
|
||||
McpOauthRequiredEvent,
|
||||
TurnDeltaEvent,
|
||||
UserInputRequestedEvent,
|
||||
SubagentEvent,
|
||||
SkillInvokedEvent,
|
||||
HookLifecycleEvent,
|
||||
SessionUsageEvent,
|
||||
SessionCompactionEvent,
|
||||
PendingMessagesModifiedEvent,
|
||||
AssistantUsageEvent,
|
||||
} from '@shared/contracts/sidecar';
|
||||
import type { ChatMessageRecord } from '@shared/domain/session';
|
||||
|
||||
export type TurnScopedEvent =
|
||||
| SubagentEvent
|
||||
| SkillInvokedEvent
|
||||
| HookLifecycleEvent
|
||||
| SessionUsageEvent
|
||||
| SessionCompactionEvent
|
||||
| PendingMessagesModifiedEvent
|
||||
| AssistantUsageEvent;
|
||||
|
||||
export interface RunTurnPendingCommand {
|
||||
kind: 'run-turn';
|
||||
resolve: (messages: ChatMessageRecord[]) => void;
|
||||
@@ -8,6 +31,10 @@ export interface RunTurnPendingCommand {
|
||||
onDelta: (event: TurnDeltaEvent) => void | Promise<void>;
|
||||
onActivity: (event: AgentActivityEvent) => void | Promise<void>;
|
||||
onApproval: (event: ApprovalRequestedEvent) => void | Promise<void>;
|
||||
onUserInput: (event: UserInputRequestedEvent) => void | Promise<void>;
|
||||
onMcpOAuthRequired: (event: McpOauthRequiredEvent) => void | Promise<void>;
|
||||
onExitPlanMode: (event: ExitPlanModeRequestedEvent) => void | Promise<void>;
|
||||
onTurnScopedEvent: (event: TurnScopedEvent) => void | Promise<void>;
|
||||
errored: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,8 +9,14 @@ import type {
|
||||
SidecarCapabilities,
|
||||
SidecarEvent,
|
||||
TurnDeltaEvent,
|
||||
UserInputRequestedEvent,
|
||||
McpOauthRequiredEvent,
|
||||
ExitPlanModeRequestedEvent,
|
||||
ValidatePatternCommand,
|
||||
RunTurnCommand,
|
||||
CopilotSessionListFilter,
|
||||
CopilotSessionInfo,
|
||||
QuotaSnapshot,
|
||||
} from '@shared/contracts/sidecar';
|
||||
import type { ApprovalDecision } from '@shared/domain/approval';
|
||||
import type { ChatMessageRecord } from '@shared/domain/session';
|
||||
@@ -19,6 +25,7 @@ import {
|
||||
markRunTurnPendingErrored,
|
||||
shouldHandleRunTurnEvent,
|
||||
type RunTurnPendingCommand,
|
||||
type TurnScopedEvent,
|
||||
} from '@main/sidecar/runTurnPending';
|
||||
import { TurnCancelledError } from '@main/sidecar/turnCancelledError';
|
||||
import { resolveSidecarProcess } from '@main/sidecar/sidecarRuntime';
|
||||
@@ -44,12 +51,42 @@ type PendingCommand =
|
||||
resolve: () => void;
|
||||
reject: (error: Error) => void;
|
||||
})
|
||||
| ({
|
||||
processId: number;
|
||||
kind: 'resolve-user-input';
|
||||
resolve: () => void;
|
||||
reject: (error: Error) => void;
|
||||
})
|
||||
| ({
|
||||
processId: number;
|
||||
kind: 'cancel-turn';
|
||||
resolve: () => void;
|
||||
reject: (error: Error) => void;
|
||||
})
|
||||
| ({
|
||||
processId: number;
|
||||
kind: 'list-sessions';
|
||||
resolve: (sessions: CopilotSessionInfo[]) => void;
|
||||
reject: (error: Error) => void;
|
||||
})
|
||||
| ({
|
||||
processId: number;
|
||||
kind: 'delete-session';
|
||||
resolve: (sessions: CopilotSessionInfo[]) => void;
|
||||
reject: (error: Error) => void;
|
||||
})
|
||||
| ({
|
||||
processId: number;
|
||||
kind: 'disconnect-session';
|
||||
resolve: () => void;
|
||||
reject: (error: Error) => void;
|
||||
})
|
||||
| ({
|
||||
processId: number;
|
||||
kind: 'get-quota';
|
||||
resolve: (snapshots: Record<string, QuotaSnapshot>) => void;
|
||||
reject: (error: Error) => void;
|
||||
})
|
||||
| ({
|
||||
processId: number;
|
||||
} & RunTurnPendingCommand);
|
||||
@@ -94,16 +131,31 @@ export class SidecarClient {
|
||||
onDelta: (event: TurnDeltaEvent) => void | Promise<void>,
|
||||
onActivity: (event: AgentActivityEvent) => void | Promise<void>,
|
||||
onApproval: (event: ApprovalRequestedEvent) => void | Promise<void>,
|
||||
onUserInput: (event: UserInputRequestedEvent) => void | Promise<void>,
|
||||
onMcpOAuthRequired: (event: McpOauthRequiredEvent) => void | Promise<void>,
|
||||
onExitPlanMode: (event: ExitPlanModeRequestedEvent) => void | Promise<void>,
|
||||
onTurnScopedEvent: (event: TurnScopedEvent) => void | Promise<void>,
|
||||
): Promise<ChatMessageRecord[]> {
|
||||
return this.dispatch<ChatMessageRecord[]>(command, onDelta, onActivity, onApproval);
|
||||
return this.dispatch<ChatMessageRecord[]>(command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, onTurnScopedEvent);
|
||||
}
|
||||
|
||||
async resolveApproval(approvalId: string, decision: ApprovalDecision): Promise<void> {
|
||||
async resolveUserInput(userInputId: string, answer: string, wasFreeform: boolean): Promise<void> {
|
||||
return this.dispatch<void>({
|
||||
type: 'resolve-user-input',
|
||||
requestId: `user-input-${Date.now()}`,
|
||||
userInputId,
|
||||
answer,
|
||||
wasFreeform,
|
||||
});
|
||||
}
|
||||
|
||||
async resolveApproval(approvalId: string, decision: ApprovalDecision, alwaysApprove?: boolean): Promise<void> {
|
||||
return this.dispatch<void>({
|
||||
type: 'resolve-approval',
|
||||
requestId: `approval-${Date.now()}`,
|
||||
approvalId,
|
||||
decision,
|
||||
alwaysApprove: alwaysApprove ?? false,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -115,6 +167,38 @@ export class SidecarClient {
|
||||
} satisfies CancelTurnCommand);
|
||||
}
|
||||
|
||||
async listSessions(filter?: CopilotSessionListFilter): Promise<CopilotSessionInfo[]> {
|
||||
return this.dispatch<CopilotSessionInfo[]>({
|
||||
type: 'list-sessions',
|
||||
requestId: `list-sessions-${Date.now()}`,
|
||||
filter,
|
||||
});
|
||||
}
|
||||
|
||||
async deleteSession(sessionId?: string, copilotSessionId?: string): Promise<CopilotSessionInfo[]> {
|
||||
return this.dispatch<CopilotSessionInfo[]>({
|
||||
type: 'delete-session',
|
||||
requestId: `delete-session-${Date.now()}`,
|
||||
sessionId,
|
||||
copilotSessionId,
|
||||
});
|
||||
}
|
||||
|
||||
async disconnectSession(sessionId: string): Promise<void> {
|
||||
return this.dispatch<void>({
|
||||
type: 'disconnect-session',
|
||||
requestId: `disconnect-session-${Date.now()}`,
|
||||
sessionId,
|
||||
});
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -199,6 +283,10 @@ export class SidecarClient {
|
||||
onDelta?: (event: TurnDeltaEvent) => void | Promise<void>,
|
||||
onActivity?: (event: AgentActivityEvent) => void | Promise<void>,
|
||||
onApproval?: (event: ApprovalRequestedEvent) => void | Promise<void>,
|
||||
onUserInput?: (event: UserInputRequestedEvent) => void | Promise<void>,
|
||||
onMcpOAuthRequired?: (event: McpOauthRequiredEvent) => void | Promise<void>,
|
||||
onExitPlanMode?: (event: ExitPlanModeRequestedEvent) => void | Promise<void>,
|
||||
onTurnScopedEvent?: (event: TurnScopedEvent) => void | Promise<void>,
|
||||
): Promise<TResult> {
|
||||
const state = await this.ensureProcess();
|
||||
|
||||
@@ -212,6 +300,10 @@ export class SidecarClient {
|
||||
onDelta: onDelta ?? (() => undefined),
|
||||
onActivity: onActivity ?? (() => undefined),
|
||||
onApproval: onApproval ?? (() => undefined),
|
||||
onUserInput: onUserInput ?? (() => undefined),
|
||||
onMcpOAuthRequired: onMcpOAuthRequired ?? (() => undefined),
|
||||
onExitPlanMode: onExitPlanMode ?? (() => undefined),
|
||||
onTurnScopedEvent: onTurnScopedEvent ?? (() => undefined),
|
||||
errored: false,
|
||||
});
|
||||
} else if (command.type === 'validate-pattern') {
|
||||
@@ -228,6 +320,13 @@ export class SidecarClient {
|
||||
resolve: resolve as () => void,
|
||||
reject,
|
||||
});
|
||||
} else if (command.type === 'resolve-user-input') {
|
||||
this.pending.set(command.requestId, {
|
||||
processId: state.id,
|
||||
kind: 'resolve-user-input',
|
||||
resolve: resolve as () => void,
|
||||
reject,
|
||||
});
|
||||
} else if (command.type === 'cancel-turn') {
|
||||
this.pending.set(command.requestId, {
|
||||
processId: state.id,
|
||||
@@ -235,6 +334,34 @@ export class SidecarClient {
|
||||
resolve: resolve as () => void,
|
||||
reject,
|
||||
});
|
||||
} else if (command.type === 'list-sessions') {
|
||||
this.pending.set(command.requestId, {
|
||||
processId: state.id,
|
||||
kind: 'list-sessions',
|
||||
resolve: resolve as (sessions: CopilotSessionInfo[]) => void,
|
||||
reject,
|
||||
});
|
||||
} else if (command.type === 'delete-session') {
|
||||
this.pending.set(command.requestId, {
|
||||
processId: state.id,
|
||||
kind: 'delete-session',
|
||||
resolve: resolve as (sessions: CopilotSessionInfo[]) => void,
|
||||
reject,
|
||||
});
|
||||
} else if (command.type === 'disconnect-session') {
|
||||
this.pending.set(command.requestId, {
|
||||
processId: state.id,
|
||||
kind: 'disconnect-session',
|
||||
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,
|
||||
@@ -297,6 +424,56 @@ export class SidecarClient {
|
||||
this.invokeRunTurnHandler(event.requestId, pending, () => pending.onApproval(event));
|
||||
}
|
||||
return;
|
||||
case 'user-input-requested':
|
||||
if (pending.kind === 'run-turn' && shouldHandleRunTurnEvent(pending)) {
|
||||
this.invokeRunTurnHandler(event.requestId, pending, () => pending.onUserInput(event));
|
||||
}
|
||||
return;
|
||||
case 'mcp-oauth-required':
|
||||
if (pending.kind === 'run-turn' && shouldHandleRunTurnEvent(pending)) {
|
||||
this.invokeRunTurnHandler(event.requestId, pending, () => pending.onMcpOAuthRequired(event));
|
||||
}
|
||||
return;
|
||||
case 'exit-plan-mode-requested':
|
||||
if (pending.kind === 'run-turn' && shouldHandleRunTurnEvent(pending)) {
|
||||
this.invokeRunTurnHandler(event.requestId, pending, () => pending.onExitPlanMode(event));
|
||||
}
|
||||
return;
|
||||
case 'subagent-event':
|
||||
case 'skill-invoked':
|
||||
case 'hook-lifecycle':
|
||||
case 'session-usage':
|
||||
case 'session-compaction':
|
||||
case 'pending-messages-modified':
|
||||
case 'assistant-usage':
|
||||
if (pending.kind === 'run-turn' && shouldHandleRunTurnEvent(pending)) {
|
||||
this.invokeRunTurnHandler(event.requestId, pending, () => pending.onTurnScopedEvent(event));
|
||||
}
|
||||
return;
|
||||
case 'quota-result':
|
||||
if (pending.kind === 'get-quota') {
|
||||
pending.resolve(event.quotaSnapshots);
|
||||
this.pending.delete(event.requestId);
|
||||
}
|
||||
return;
|
||||
case 'sessions-listed':
|
||||
if (pending.kind === 'list-sessions') {
|
||||
pending.resolve(event.sessions);
|
||||
this.pending.delete(event.requestId);
|
||||
}
|
||||
return;
|
||||
case 'sessions-deleted':
|
||||
if (pending.kind === 'delete-session') {
|
||||
pending.resolve(event.sessions);
|
||||
this.pending.delete(event.requestId);
|
||||
}
|
||||
return;
|
||||
case 'session-disconnected':
|
||||
if (pending.kind === 'disconnect-session') {
|
||||
pending.resolve();
|
||||
this.pending.delete(event.requestId);
|
||||
}
|
||||
return;
|
||||
case 'turn-complete':
|
||||
if (pending.kind === 'run-turn') {
|
||||
if (shouldHandleRunTurnEvent(pending)) {
|
||||
@@ -318,7 +495,7 @@ export class SidecarClient {
|
||||
this.pending.delete(event.requestId);
|
||||
return;
|
||||
case 'command-complete':
|
||||
if (pending.kind === 'resolve-approval' || pending.kind === 'cancel-turn') {
|
||||
if (pending.kind === 'resolve-approval' || pending.kind === 'resolve-user-input' || pending.kind === 'cancel-turn') {
|
||||
pending.resolve();
|
||||
this.pending.delete(event.requestId);
|
||||
} else if (pending.kind !== 'run-turn' || pending.errored) {
|
||||
|
||||
@@ -15,27 +15,56 @@ const api: ElectronApi = {
|
||||
ipcRenderer.invoke(ipcChannels.resolveWorkspaceDiscoveredTooling, input),
|
||||
refreshProjectGitContext: (projectId) => ipcRenderer.invoke(ipcChannels.refreshProjectGitContext, projectId),
|
||||
rescanProjectConfigs: (input) => ipcRenderer.invoke(ipcChannels.rescanProjectConfigs, input),
|
||||
rescanProjectCustomization: (input) =>
|
||||
ipcRenderer.invoke(ipcChannels.rescanProjectCustomization, input),
|
||||
resolveProjectDiscoveredTooling: (input) =>
|
||||
ipcRenderer.invoke(ipcChannels.resolveProjectDiscoveredTooling, input),
|
||||
setProjectAgentProfileEnabled: (input) =>
|
||||
ipcRenderer.invoke(ipcChannels.setProjectAgentProfileEnabled, input),
|
||||
savePattern: (input) => ipcRenderer.invoke(ipcChannels.savePattern, input),
|
||||
deletePattern: (patternId) => ipcRenderer.invoke(ipcChannels.deletePattern, patternId),
|
||||
setPatternFavorite: (input) => ipcRenderer.invoke(ipcChannels.setPatternFavorite, input),
|
||||
setTheme: (theme) => ipcRenderer.invoke(ipcChannels.setTheme, theme),
|
||||
setTerminalHeight: (input) => ipcRenderer.invoke(ipcChannels.setTerminalHeight, input),
|
||||
setNotificationsEnabled: (enabled) => ipcRenderer.invoke(ipcChannels.setNotificationsEnabled, enabled),
|
||||
setMinimizeToTray: (enabled) => ipcRenderer.invoke(ipcChannels.setMinimizeToTray, enabled),
|
||||
checkForUpdates: () => ipcRenderer.invoke(ipcChannels.checkForUpdates),
|
||||
installUpdate: () => ipcRenderer.invoke(ipcChannels.installUpdate),
|
||||
saveMcpServer: (input) => ipcRenderer.invoke(ipcChannels.saveMcpServer, input),
|
||||
deleteMcpServer: (serverId) => ipcRenderer.invoke(ipcChannels.deleteMcpServer, serverId),
|
||||
saveLspProfile: (input) => ipcRenderer.invoke(ipcChannels.saveLspProfile, input),
|
||||
deleteLspProfile: (profileId) => ipcRenderer.invoke(ipcChannels.deleteLspProfile, profileId),
|
||||
describeTerminal: () => ipcRenderer.invoke(ipcChannels.describeTerminal),
|
||||
createTerminal: () => ipcRenderer.invoke(ipcChannels.createTerminal),
|
||||
restartTerminal: () => ipcRenderer.invoke(ipcChannels.restartTerminal),
|
||||
killTerminal: () => ipcRenderer.invoke(ipcChannels.killTerminal),
|
||||
writeTerminal: (data) => {
|
||||
ipcRenderer.send(ipcChannels.writeTerminal, data);
|
||||
},
|
||||
resizeTerminal: (input) => {
|
||||
ipcRenderer.send(ipcChannels.resizeTerminal, input);
|
||||
},
|
||||
updateSessionTooling: (input) => ipcRenderer.invoke(ipcChannels.updateSessionTooling, input),
|
||||
updateSessionApprovalSettings: (input) =>
|
||||
ipcRenderer.invoke(ipcChannels.updateSessionApprovalSettings, input),
|
||||
createSession: (input) => ipcRenderer.invoke(ipcChannels.createSession, input),
|
||||
duplicateSession: (input) => ipcRenderer.invoke(ipcChannels.duplicateSession, input),
|
||||
branchSession: (input) => ipcRenderer.invoke(ipcChannels.branchSession, input),
|
||||
setSessionMessagePinned: (input) => ipcRenderer.invoke(ipcChannels.setSessionMessagePinned, input),
|
||||
renameSession: (input) => ipcRenderer.invoke(ipcChannels.renameSession, input),
|
||||
setSessionPinned: (input) => ipcRenderer.invoke(ipcChannels.setSessionPinned, input),
|
||||
setSessionArchived: (input) => ipcRenderer.invoke(ipcChannels.setSessionArchived, input),
|
||||
deleteSession: (input) => ipcRenderer.invoke(ipcChannels.deleteSession, input),
|
||||
regenerateSessionMessage: (input) => ipcRenderer.invoke(ipcChannels.regenerateSessionMessage, input),
|
||||
editAndResendSessionMessage: (input) => ipcRenderer.invoke(ipcChannels.editAndResendSessionMessage, input),
|
||||
sendSessionMessage: (input) => ipcRenderer.invoke(ipcChannels.sendSessionMessage, input),
|
||||
cancelSessionTurn: (input) => ipcRenderer.invoke(ipcChannels.cancelSessionTurn, input),
|
||||
resolveSessionApproval: (input) => ipcRenderer.invoke(ipcChannels.resolveSessionApproval, input),
|
||||
resolveSessionUserInput: (input) => ipcRenderer.invoke(ipcChannels.resolveSessionUserInput, input),
|
||||
setSessionInteractionMode: (input) => ipcRenderer.invoke(ipcChannels.setSessionInteractionMode, input),
|
||||
dismissSessionPlanReview: (input) => ipcRenderer.invoke(ipcChannels.dismissSessionPlanReview, input),
|
||||
dismissSessionMcpAuth: (input) => ipcRenderer.invoke(ipcChannels.dismissSessionMcpAuth, input),
|
||||
startSessionMcpAuth: (input) => ipcRenderer.invoke(ipcChannels.startSessionMcpAuth, input),
|
||||
updateSessionModelConfig: (input) =>
|
||||
ipcRenderer.invoke(ipcChannels.updateSessionModelConfig, input),
|
||||
querySessions: (input) => ipcRenderer.invoke(ipcChannels.querySessions, input),
|
||||
@@ -44,6 +73,21 @@ const api: ElectronApi = {
|
||||
selectSession: (sessionId) => ipcRenderer.invoke(ipcChannels.selectSession, sessionId),
|
||||
openAppDataFolder: () => ipcRenderer.invoke(ipcChannels.openAppDataFolder),
|
||||
resetLocalWorkspace: () => ipcRenderer.invoke(ipcChannels.resetLocalWorkspace),
|
||||
getQuota: () => ipcRenderer.invoke(ipcChannels.getQuota),
|
||||
onTerminalData: (listener) => {
|
||||
const handler = (_event: Electron.IpcRendererEvent, data: Parameters<typeof listener>[0]) =>
|
||||
listener(data);
|
||||
|
||||
ipcRenderer.on(ipcChannels.terminalData, handler);
|
||||
return () => ipcRenderer.off(ipcChannels.terminalData, handler);
|
||||
},
|
||||
onTerminalExit: (listener) => {
|
||||
const handler = (_event: Electron.IpcRendererEvent, info: Parameters<typeof listener>[0]) =>
|
||||
listener(info);
|
||||
|
||||
ipcRenderer.on(ipcChannels.terminalExit, handler);
|
||||
return () => ipcRenderer.off(ipcChannels.terminalExit, handler);
|
||||
},
|
||||
onWorkspaceUpdated:(listener) => {
|
||||
const handler = (_event: Electron.IpcRendererEvent, workspace: Awaited<ReturnType<ElectronApi['loadWorkspace']>>) =>
|
||||
listener(workspace);
|
||||
@@ -58,6 +102,19 @@ const api: ElectronApi = {
|
||||
ipcRenderer.on(ipcChannels.sessionEvent, handler);
|
||||
return () => ipcRenderer.off(ipcChannels.sessionEvent, handler);
|
||||
},
|
||||
onUpdateStatus: (listener) => {
|
||||
const handler = (_event: Electron.IpcRendererEvent, status: Parameters<typeof listener>[0]) =>
|
||||
listener(status);
|
||||
|
||||
ipcRenderer.on(ipcChannels.updateStatus, handler);
|
||||
return () => ipcRenderer.off(ipcChannels.updateStatus, handler);
|
||||
},
|
||||
onTrayCreateScratchpad: (listener) => {
|
||||
const handler = () => listener();
|
||||
|
||||
ipcRenderer.on(ipcChannels.trayCreateScratchpad, handler);
|
||||
return () => ipcRenderer.off(ipcChannels.trayCreateScratchpad, handler);
|
||||
},
|
||||
};
|
||||
|
||||
contextBridge.exposeInMainWorld('aryxApi', api);
|
||||
|
||||
+425
-11
@@ -1,18 +1,33 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
|
||||
import { AppShell } from '@renderer/components/AppShell';
|
||||
import { ActivityPanel } from '@renderer/components/ActivityPanel';
|
||||
import { ChatPane } from '@renderer/components/ChatPane';
|
||||
import { CommandPalette } from '@renderer/components/CommandPalette';
|
||||
import { DiscoveredToolingModal } from '@renderer/components/DiscoveredToolingModal';
|
||||
import { KeyboardShortcutsPanel } from '@renderer/components/KeyboardShortcutsPanel';
|
||||
import { NewSessionModal } from '@renderer/components/NewSessionModal';
|
||||
import { ProjectSettingsPanel } from '@renderer/components/ProjectSettingsPanel';
|
||||
import { SessionSearchPanel } from '@renderer/components/SessionSearchPanel';
|
||||
import { SettingsPanel } from '@renderer/components/SettingsPanel';
|
||||
import { Sidebar } from '@renderer/components/Sidebar';
|
||||
import { TerminalPanel, DEFAULT_HEIGHT as DEFAULT_TERMINAL_HEIGHT, MIN_HEIGHT as MIN_TERMINAL_HEIGHT } from '@renderer/components/TerminalPanel';
|
||||
import { resolveChatToolingSettings } from '@renderer/lib/chatTooling';
|
||||
import {
|
||||
applySessionEventActivity,
|
||||
applySessionUsageEvent,
|
||||
applyAssistantUsageEvent,
|
||||
applyTurnEventLog,
|
||||
pruneSessionActivities,
|
||||
pruneSessionUsage,
|
||||
pruneSessionRequestUsage,
|
||||
pruneTurnEventLogs,
|
||||
type SessionActivityMap,
|
||||
type SessionUsageMap,
|
||||
type SessionRequestUsageMap,
|
||||
type TurnEventLogMap,
|
||||
} from '@renderer/lib/sessionActivity';
|
||||
import { applySubagentEvent, pruneSubagentMap, type ActiveSubagentMap } from '@renderer/lib/subagentTracker';
|
||||
import { applySessionEventWorkspace } from '@renderer/lib/sessionWorkspace';
|
||||
import { WelcomePane } from '@renderer/components/WelcomePane';
|
||||
import { getElectronApi } from '@renderer/lib/electronApi';
|
||||
@@ -91,10 +106,25 @@ export default function App() {
|
||||
const [error, setError] = useState<string>();
|
||||
const { capabilities: sidecarCapabilities, isRefreshing: isRefreshingCapabilities, refresh: refreshCapabilities } = useSidecarCapabilities(api);
|
||||
const [sessionActivities, setSessionActivities] = useState<SessionActivityMap>({});
|
||||
const [sessionUsage, setSessionUsage] = useState<SessionUsageMap>({});
|
||||
const [sessionRequestUsage, setSessionRequestUsage] = useState<SessionRequestUsageMap>({});
|
||||
const [turnEventLogs, setTurnEventLogs] = useState<TurnEventLogMap>({});
|
||||
const [activeSubagents, setActiveSubagents] = useState<ActiveSubagentMap>({});
|
||||
|
||||
const [showSettings, setShowSettings] = useState(false);
|
||||
const [projectSettingsId, setProjectSettingsId] = useState<string>();
|
||||
const [newSessionProjectId, setNewSessionProjectId] = useState<string>();
|
||||
const [showDiscoveryModal, setShowDiscoveryModal] = useState(false);
|
||||
const [commandPaletteOpen, setCommandPaletteOpen] = useState(false);
|
||||
const [showShortcuts, setShowShortcuts] = useState(false);
|
||||
const [showSearch, setShowSearch] = useState(false);
|
||||
|
||||
// Terminal state
|
||||
const [terminalOpen, setTerminalOpen] = useState(false);
|
||||
const [terminalHeight, setTerminalHeight] = useState(
|
||||
() => workspace?.settings.terminalHeight ?? DEFAULT_TERMINAL_HEIGHT,
|
||||
);
|
||||
const [terminalRunning, setTerminalRunning] = useState(false);
|
||||
|
||||
// Load workspace on mount
|
||||
useEffect(() => {
|
||||
@@ -114,11 +144,39 @@ export default function App() {
|
||||
ws.sessions.map((session) => session.id),
|
||||
),
|
||||
);
|
||||
setSessionUsage((current) =>
|
||||
pruneSessionUsage(
|
||||
current,
|
||||
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 () => {
|
||||
@@ -169,6 +227,22 @@ export default function App() {
|
||||
() => (selectedSession ? sessionActivities[selectedSession.id] : undefined),
|
||||
[selectedSession, sessionActivities],
|
||||
);
|
||||
const usageForSession = useMemo(
|
||||
() => (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],
|
||||
);
|
||||
const hasUserProjects = useMemo(
|
||||
() => (workspace?.projects.some((project) => !isScratchpadProject(project)) ?? false),
|
||||
[workspace?.projects],
|
||||
@@ -196,6 +270,196 @@ export default function App() {
|
||||
if (hasPendingDiscoveries) setShowDiscoveryModal(true);
|
||||
}, [hasPendingDiscoveries]);
|
||||
|
||||
// Keep refs for values the keyboard handler reads — avoids re-registering on every render.
|
||||
const workspaceRef = useRef(workspace);
|
||||
workspaceRef.current = workspace;
|
||||
const showSettingsRef = useRef(showSettings);
|
||||
showSettingsRef.current = showSettings;
|
||||
const showShortcutsRef = useRef(showShortcuts);
|
||||
showShortcutsRef.current = showShortcuts;
|
||||
const commandPaletteOpenRef = useRef(commandPaletteOpen);
|
||||
commandPaletteOpenRef.current = commandPaletteOpen;
|
||||
const projectSettingsIdRef = useRef(projectSettingsId);
|
||||
projectSettingsIdRef.current = projectSettingsId;
|
||||
const newSessionProjectIdRef = useRef(newSessionProjectId);
|
||||
newSessionProjectIdRef.current = newSessionProjectId;
|
||||
|
||||
// ── Global keyboard shortcuts ──
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
const mod = e.ctrlKey || e.metaKey;
|
||||
const ws = workspaceRef.current;
|
||||
|
||||
// Ignore keyboard shortcuts while typing in inputs (except our global combos)
|
||||
const target = e.target as HTMLElement;
|
||||
const isInput = target.tagName === 'INPUT'
|
||||
|| target.tagName === 'TEXTAREA'
|
||||
|| target.isContentEditable;
|
||||
|
||||
// ── Ctrl+` — Toggle terminal ──
|
||||
if (e.ctrlKey && e.key === '`') {
|
||||
e.preventDefault();
|
||||
setTerminalOpen((prev) => !prev);
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Ctrl/Cmd+K — Command palette ──
|
||||
if (mod && e.key === 'k') {
|
||||
e.preventDefault();
|
||||
setCommandPaletteOpen((prev) => !prev);
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Ctrl/Cmd+/ — Keyboard shortcuts cheat sheet ──
|
||||
if (mod && e.key === '/') {
|
||||
e.preventDefault();
|
||||
setShowShortcuts((prev) => !prev);
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Ctrl/Cmd+Shift+F — Search sessions ──
|
||||
if (mod && e.shiftKey && e.key === 'F') {
|
||||
e.preventDefault();
|
||||
setShowSearch((prev) => !prev);
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Ctrl/Cmd+, — Open settings ──
|
||||
if (mod && e.key === ',') {
|
||||
e.preventDefault();
|
||||
setShowSettings(true);
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Escape — Close overlays or cancel running turn ──
|
||||
if (e.key === 'Escape') {
|
||||
// Close overlays in priority order (command palette and shortcuts use their own capture listeners)
|
||||
if (projectSettingsIdRef.current) {
|
||||
e.preventDefault();
|
||||
setProjectSettingsId(undefined);
|
||||
return;
|
||||
}
|
||||
if (showSettingsRef.current) {
|
||||
e.preventDefault();
|
||||
setShowSettings(false);
|
||||
return;
|
||||
}
|
||||
if (newSessionProjectIdRef.current) {
|
||||
e.preventDefault();
|
||||
setNewSessionProjectId(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
// If nothing is open, cancel a running turn on the selected session
|
||||
if (ws) {
|
||||
const session = ws.sessions.find((s) => s.id === ws.selectedSessionId);
|
||||
if (session?.status === 'running' && !isInput) {
|
||||
e.preventDefault();
|
||||
void api.cancelSessionTurn({ sessionId: session.id });
|
||||
return;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip remaining shortcuts when focus is in an input field
|
||||
if (isInput) return;
|
||||
|
||||
// ── Ctrl/Cmd+N — New session ──
|
||||
if (mod && e.key === 'n') {
|
||||
e.preventDefault();
|
||||
if (ws) {
|
||||
const defaultProjectId =
|
||||
ws.selectedProjectId ??
|
||||
ws.projects.find((p) => !isScratchpadProject(p))?.id;
|
||||
if (defaultProjectId) {
|
||||
setNewSessionProjectId(defaultProjectId);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Ctrl/Cmd+W — Archive / close current session ──
|
||||
if (mod && e.key === 'w') {
|
||||
e.preventDefault();
|
||||
if (ws?.selectedSessionId) {
|
||||
void api.setSessionArchived({ sessionId: ws.selectedSessionId, isArchived: true });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Ctrl+Tab / Ctrl+Shift+Tab — Cycle sessions ──
|
||||
if (e.ctrlKey && e.key === 'Tab') {
|
||||
e.preventDefault();
|
||||
if (ws) {
|
||||
const activeSessions = ws.sessions.filter((s) => !s.isArchived);
|
||||
if (activeSessions.length > 1) {
|
||||
const currentIdx = activeSessions.findIndex((s) => s.id === ws.selectedSessionId);
|
||||
const direction = e.shiftKey ? -1 : 1;
|
||||
const nextIdx = (currentIdx + direction + activeSessions.length) % activeSessions.length;
|
||||
void api.selectSession(activeSessions[nextIdx].id);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Ctrl/Cmd+. — Quick approve pending tool call ──
|
||||
if (mod && e.key === '.') {
|
||||
e.preventDefault();
|
||||
if (ws?.selectedSessionId) {
|
||||
const session = ws.sessions.find((s) => s.id === ws.selectedSessionId);
|
||||
if (session?.pendingApproval?.status === 'pending') {
|
||||
void api.resolveSessionApproval({
|
||||
sessionId: session.id,
|
||||
approvalId: session.pendingApproval.id,
|
||||
decision: 'approved',
|
||||
});
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Ctrl/Cmd+L — Focus the composer ──
|
||||
if (mod && e.key === 'l') {
|
||||
e.preventDefault();
|
||||
const editor = document.querySelector<HTMLElement>('.markdown-composer-editable');
|
||||
editor?.focus();
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
|
||||
// Track terminal running state via exit events
|
||||
const offExit = api.onTerminalExit(() => setTerminalRunning(false));
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('keydown', handleKeyDown);
|
||||
offExit();
|
||||
};
|
||||
}, [api]);
|
||||
|
||||
// Sync terminalHeight from workspace settings when workspace loads
|
||||
useEffect(() => {
|
||||
if (workspace?.settings.terminalHeight) {
|
||||
setTerminalHeight(workspace.settings.terminalHeight);
|
||||
}
|
||||
}, [workspace?.settings.terminalHeight]);
|
||||
|
||||
const handleTerminalHeightChange = useCallback((newHeight: number) => {
|
||||
const clamped = Math.max(MIN_TERMINAL_HEIGHT, Math.round(newHeight));
|
||||
setTerminalHeight(clamped);
|
||||
void api.setTerminalHeight({ height: clamped });
|
||||
}, [api]);
|
||||
|
||||
const handleTerminalClose = useCallback(() => {
|
||||
setTerminalOpen(false);
|
||||
}, []);
|
||||
|
||||
const handleTerminalToggle = useCallback(() => {
|
||||
setTerminalOpen((prev) => !prev);
|
||||
}, []);
|
||||
|
||||
const jumpToMessage = useCallback((messageId: string) => {
|
||||
const element = document.querySelector(`[data-message-id="${CSS.escape(messageId)}"]`);
|
||||
if (element) {
|
||||
@@ -221,6 +485,23 @@ export default function App() {
|
||||
}
|
||||
}, [api, workspace]);
|
||||
|
||||
// Listen for tray "Quick Scratchpad" action
|
||||
const scratchpadRef = useRef(handleCreateScratchpad);
|
||||
scratchpadRef.current = handleCreateScratchpad;
|
||||
useEffect(() => {
|
||||
return api.onTrayCreateScratchpad(() => scratchpadRef.current());
|
||||
}, [api]);
|
||||
|
||||
const projectForSettings = useMemo(
|
||||
() => workspace?.projects.find((p) => p.id === projectSettingsId),
|
||||
[workspace?.projects, projectSettingsId],
|
||||
);
|
||||
|
||||
// Close project settings if the project was removed
|
||||
useEffect(() => {
|
||||
if (projectSettingsId && !projectForSettings) setProjectSettingsId(undefined);
|
||||
}, [projectSettingsId, projectForSettings]);
|
||||
|
||||
// Loading state
|
||||
if (!workspace) {
|
||||
return (
|
||||
@@ -245,11 +526,31 @@ export default function App() {
|
||||
} else if (selectedSession && patternForSession && projectForSession) {
|
||||
content = (
|
||||
<ChatPane
|
||||
onSend={(c) => api.sendSessionMessage({ sessionId: selectedSession.id, content: c })}
|
||||
onSend={(c, attachments, messageMode) => api.sendSessionMessage({
|
||||
sessionId: selectedSession.id,
|
||||
content: c,
|
||||
attachments: attachments?.length ? attachments : undefined,
|
||||
messageMode,
|
||||
})}
|
||||
onCancelTurn={() => { void api.cancelSessionTurn({ sessionId: selectedSession.id }); }}
|
||||
onResolveApproval={(approvalId, decision) =>
|
||||
api.resolveSessionApproval({ sessionId: selectedSession.id, approvalId, decision })
|
||||
onResolveApproval={(approvalId, decision, alwaysApprove) =>
|
||||
api.resolveSessionApproval({ sessionId: selectedSession.id, approvalId, decision, alwaysApprove })
|
||||
}
|
||||
onResolveUserInput={(userInputId, answer, wasFreeform) =>
|
||||
api.resolveSessionUserInput({ sessionId: selectedSession.id, userInputId, answer, wasFreeform })
|
||||
}
|
||||
onSetInteractionMode={(mode) => {
|
||||
void api.setSessionInteractionMode({ sessionId: selectedSession.id, mode });
|
||||
}}
|
||||
onDismissPlanReview={() => {
|
||||
void api.dismissSessionPlanReview({ sessionId: selectedSession.id });
|
||||
}}
|
||||
onDismissMcpAuth={() => {
|
||||
void api.dismissSessionMcpAuth({ sessionId: selectedSession.id });
|
||||
}}
|
||||
onAuthenticateMcp={() => {
|
||||
void api.startSessionMcpAuth({ sessionId: selectedSession.id });
|
||||
}}
|
||||
onUpdateSessionModelConfig={(config) =>
|
||||
api.updateSessionModelConfig({
|
||||
sessionId: selectedSession.id,
|
||||
@@ -270,11 +571,34 @@ export default function App() {
|
||||
autoApprovedToolNames: settings.autoApprovedToolNames,
|
||||
});
|
||||
}}
|
||||
onBranchFromMessage={(messageId) => {
|
||||
void api.branchSession({ sessionId: selectedSession.id, messageId });
|
||||
}}
|
||||
onPinMessage={(messageId, isPinned) => {
|
||||
void api.setSessionMessagePinned({ sessionId: selectedSession.id, messageId, isPinned });
|
||||
}}
|
||||
onRegenerateMessage={(messageId) => {
|
||||
void api.regenerateSessionMessage({ sessionId: selectedSession.id, messageId });
|
||||
}}
|
||||
onEditAndResendMessage={(messageId, content) => {
|
||||
void api.editAndResendSessionMessage({ sessionId: selectedSession.id, messageId, content });
|
||||
}}
|
||||
branchOriginLabel={
|
||||
selectedSession.branchOrigin
|
||||
? workspace.sessions.find((s) => s.id === selectedSession.branchOrigin!.sourceSessionId)?.title
|
||||
: undefined
|
||||
}
|
||||
availableModels={availableModels}
|
||||
mcpProbingServerIds={workspace.mcpProbingServerIds}
|
||||
onTerminalToggle={handleTerminalToggle}
|
||||
pattern={patternForSession}
|
||||
project={projectForSession}
|
||||
runtimeTools={sidecarCapabilities?.runtimeTools}
|
||||
session={selectedSession}
|
||||
sessionUsage={usageForSession}
|
||||
activeSubagents={subagentsForSession}
|
||||
terminalOpen={terminalOpen}
|
||||
terminalRunning={terminalRunning}
|
||||
toolingSettings={chatToolingSettings ?? workspace.settings.tooling}
|
||||
/>
|
||||
);
|
||||
@@ -284,12 +608,15 @@ export default function App() {
|
||||
onJumpToMessage={jumpToMessage}
|
||||
pattern={patternForSession}
|
||||
session={selectedSession}
|
||||
sessionRequestUsage={requestUsageForSession}
|
||||
turnEvents={turnEventsForSession}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
content = (
|
||||
<WelcomePane
|
||||
hasProjects={hasUserProjects}
|
||||
connectionStatus={sidecarCapabilities?.connection.status}
|
||||
onAddProject={() => void api.addProject()}
|
||||
onNewScratchpad={() => handleCreateScratchpad()}
|
||||
onOpenSettings={() => setShowSettings(true)}
|
||||
@@ -333,24 +660,26 @@ export default function App() {
|
||||
await api.savePattern({ pattern });
|
||||
}}
|
||||
onSetTheme={(theme) => void api.setTheme(theme)}
|
||||
notificationsEnabled={workspace.settings.notificationsEnabled !== false}
|
||||
onSetNotificationsEnabled={(enabled) => void api.setNotificationsEnabled(enabled)}
|
||||
minimizeToTray={workspace.settings.minimizeToTray === true}
|
||||
onSetMinimizeToTray={(enabled) => void api.setMinimizeToTray(enabled)}
|
||||
onOpenAppDataFolder={() => void api.openAppDataFolder()}
|
||||
onResetLocalWorkspace={async () => {
|
||||
await api.resetLocalWorkspace();
|
||||
const fresh = await api.resetLocalWorkspace();
|
||||
setWorkspace(fresh);
|
||||
setSessionActivities({});
|
||||
setShowSettings(false);
|
||||
}}
|
||||
patterns={workspace.patterns}
|
||||
sidecarCapabilities={sidecarCapabilities}
|
||||
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;
|
||||
|
||||
@@ -360,6 +689,16 @@ export default function App() {
|
||||
content={content}
|
||||
detailPanel={detailPanel}
|
||||
overlay={overlay}
|
||||
terminalPanel={
|
||||
terminalOpen ? (
|
||||
<TerminalPanel
|
||||
height={terminalHeight}
|
||||
onHeightChange={handleTerminalHeightChange}
|
||||
onClose={handleTerminalClose}
|
||||
onMinimize={handleTerminalClose}
|
||||
/>
|
||||
) : undefined
|
||||
}
|
||||
sidebar={
|
||||
<Sidebar
|
||||
onAddProject={() => void api.addProject()}
|
||||
@@ -368,6 +707,7 @@ export default function App() {
|
||||
setNewSessionProjectId(projectId);
|
||||
}}
|
||||
onOpenSettings={() => setShowSettings(true)}
|
||||
onOpenProjectSettings={(projectId) => setProjectSettingsId(projectId)}
|
||||
onProjectSelect={(projectId) => {
|
||||
void api.selectProject(projectId);
|
||||
}}
|
||||
@@ -386,6 +726,9 @@ export default function App() {
|
||||
onSetSessionArchived={(sessionId, isArchived) => {
|
||||
void api.setSessionArchived({ sessionId, isArchived });
|
||||
}}
|
||||
onDeleteSession={(sessionId) => {
|
||||
void api.deleteSession({ sessionId });
|
||||
}}
|
||||
onRefreshGitContext={(projectId) => {
|
||||
void api.refreshProjectGitContext(projectId);
|
||||
}}
|
||||
@@ -426,6 +769,77 @@ export default function App() {
|
||||
userDiscoveredTooling={workspace.settings.discoveredUserTooling}
|
||||
/>
|
||||
)}
|
||||
|
||||
{projectForSettings && (
|
||||
<ProjectSettingsPanel
|
||||
project={projectForSettings}
|
||||
onClose={() => setProjectSettingsId(undefined)}
|
||||
onRescanConfigs={() => {
|
||||
void api.rescanProjectConfigs({ projectId: projectForSettings.id });
|
||||
}}
|
||||
onRescanCustomization={() => {
|
||||
void api.rescanProjectCustomization({ projectId: projectForSettings.id });
|
||||
}}
|
||||
onResolveDiscoveredTooling={(serverIds, resolution) => {
|
||||
void api.resolveProjectDiscoveredTooling({ projectId: projectForSettings.id, serverIds, resolution });
|
||||
}}
|
||||
onSetAgentProfileEnabled={(agentProfileId, enabled) => {
|
||||
void api.setProjectAgentProfileEnabled({ projectId: projectForSettings.id, agentProfileId, enabled });
|
||||
}}
|
||||
onRemoveProject={() => {
|
||||
void api.removeProject(projectForSettings.id);
|
||||
setProjectSettingsId(undefined);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{commandPaletteOpen && workspace && (
|
||||
<CommandPalette
|
||||
workspace={workspace}
|
||||
onClose={() => setCommandPaletteOpen(false)}
|
||||
onSelectSession={(sessionId) => {
|
||||
void api.selectSession(sessionId);
|
||||
}}
|
||||
onSelectProject={(projectId) => {
|
||||
void api.selectProject(projectId);
|
||||
}}
|
||||
onNewSession={(projectId) => {
|
||||
setNewSessionProjectId(projectId);
|
||||
}}
|
||||
onCreateScratchpad={handleCreateScratchpad}
|
||||
onOpenSettings={() => setShowSettings(true)}
|
||||
onOpenProjectSettings={(projectId) => setProjectSettingsId(projectId)}
|
||||
onToggleTerminal={handleTerminalToggle}
|
||||
onSetTheme={(theme) => void api.setTheme(theme)}
|
||||
onDuplicateSession={(sessionId) => {
|
||||
void api.duplicateSession({ sessionId });
|
||||
}}
|
||||
onPinSession={(sessionId, isPinned) => {
|
||||
void api.setSessionPinned({ sessionId, isPinned });
|
||||
}}
|
||||
onArchiveSession={(sessionId, isArchived) => {
|
||||
void api.setSessionArchived({ sessionId, isArchived });
|
||||
}}
|
||||
onAddProject={() => void api.addProject()}
|
||||
onOpenAppDataFolder={() => void api.openAppDataFolder()}
|
||||
onShowShortcuts={() => setShowShortcuts(true)}
|
||||
onShowSearch={() => setShowSearch(true)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{showShortcuts && (
|
||||
<KeyboardShortcutsPanel onClose={() => setShowShortcuts(false)} />
|
||||
)}
|
||||
|
||||
{showSearch && workspace && (
|
||||
<SessionSearchPanel
|
||||
workspace={workspace}
|
||||
onClose={() => setShowSearch(false)}
|
||||
onSelectSession={(sessionId) => {
|
||||
void api.selectSession(sessionId);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
import { useMemo, type ReactNode } from 'react';
|
||||
import { Activity, Clock, ShieldAlert, Sparkles, Users } 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';
|
||||
@@ -18,12 +24,12 @@ import { ProviderIcon } from './ProviderIcons';
|
||||
/* ── Mode accent colours ───────────────────────────────────── */
|
||||
|
||||
const modeAccent: Record<OrchestrationMode, { dot: string; bar: string; label: string }> = {
|
||||
single: { dot: 'bg-indigo-400', bar: 'bg-indigo-500/60', label: 'text-indigo-400' },
|
||||
sequential: { dot: 'bg-amber-400', bar: 'bg-amber-500/60', label: 'text-amber-400' },
|
||||
concurrent: { dot: 'bg-emerald-400', bar: 'bg-emerald-500/60', label: 'text-emerald-400' },
|
||||
handoff: { dot: 'bg-sky-400', bar: 'bg-sky-500/60', label: 'text-sky-400' },
|
||||
'group-chat': { dot: 'bg-violet-400', bar: 'bg-violet-500/60', label: 'text-violet-400' },
|
||||
magentic: { dot: 'bg-zinc-500', bar: 'bg-zinc-600/60', label: 'text-zinc-500' },
|
||||
single: { dot: 'bg-[#245CF9]', bar: 'bg-[#245CF9] opacity-60', label: 'text-[#245CF9]' },
|
||||
sequential: { dot: 'bg-[var(--color-status-warning)]', bar: 'bg-[var(--color-status-warning)] opacity-60', label: 'text-[var(--color-status-warning)]' },
|
||||
concurrent: { dot: 'bg-[var(--color-status-success)]', bar: 'bg-[var(--color-status-success)] opacity-60', label: 'text-[var(--color-status-success)]' },
|
||||
handoff: { dot: 'bg-[var(--color-accent-sky)]', bar: 'bg-[var(--color-accent-sky)] opacity-60', label: 'text-[var(--color-accent-sky)]' },
|
||||
'group-chat': { dot: 'bg-[var(--color-accent-purple)]', bar: 'bg-[var(--color-accent-purple)] opacity-60', label: 'text-[var(--color-accent-purple)]' },
|
||||
magentic: { dot: 'bg-[var(--color-text-muted)]', bar: 'bg-[var(--color-text-muted)] opacity-60', label: 'text-[var(--color-text-muted)]' },
|
||||
};
|
||||
|
||||
/* ── Helpers ───────────────────────────────────────────────── */
|
||||
@@ -56,7 +62,7 @@ const modeLabels: Record<OrchestrationMode, string> = {
|
||||
|
||||
function SectionHeader({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<h3 className="mb-2 flex items-center gap-2 text-[10px] font-semibold uppercase tracking-wider text-zinc-600">
|
||||
<h3 className="font-display mb-2 flex items-center gap-2 text-[10px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
|
||||
{children}
|
||||
</h3>
|
||||
);
|
||||
@@ -69,17 +75,19 @@ function AgentRow({
|
||||
agent,
|
||||
accent,
|
||||
isLast,
|
||||
agentUsage,
|
||||
}: {
|
||||
row: AgentActivityRow;
|
||||
agent?: PatternAgentDefinition;
|
||||
accent: (typeof modeAccent)[OrchestrationMode];
|
||||
isLast: boolean;
|
||||
agentUsage?: AgentUsageAccumulator;
|
||||
}) {
|
||||
const isActive = isAgentActivityActive(row.activity);
|
||||
const isCompleted = isAgentActivityCompleted(row.activity);
|
||||
|
||||
return (
|
||||
<div className={`relative flex gap-2.5 py-2.5 ${isLast ? '' : 'border-b border-zinc-800/50'}`}>
|
||||
<div className={`relative flex gap-2.5 py-2.5 ${isLast ? '' : 'border-b border-[var(--color-border-subtle)]'}`}>
|
||||
{/* Left accent bar — visible only when this agent is actively working */}
|
||||
{isActive && (
|
||||
<div className={`absolute -left-3 bottom-2 top-2 w-[3px] rounded-full ${accent.bar}`} />
|
||||
@@ -88,12 +96,12 @@ function AgentRow({
|
||||
{/* Status dot */}
|
||||
<div className="flex shrink-0 pt-0.5">
|
||||
<span
|
||||
className={`size-2 rounded-full ${
|
||||
className={`size-2 rounded-full transition-all duration-200 ${
|
||||
isActive
|
||||
? `animate-pulse ${accent.dot}`
|
||||
? `animate-pulse ${accent.dot} ring-2 ring-[var(--color-border-glow)]`
|
||||
: isCompleted
|
||||
? 'bg-emerald-400'
|
||||
: 'bg-zinc-700'
|
||||
? 'bg-[var(--color-status-success)]'
|
||||
: 'bg-[var(--color-surface-3)]'
|
||||
}`}
|
||||
/>
|
||||
</div>
|
||||
@@ -101,13 +109,13 @@ function AgentRow({
|
||||
{/* Content */}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="truncate text-[12px] font-medium text-zinc-200">{row.agentName}</span>
|
||||
<span className="truncate text-[12px] font-medium text-[var(--color-text-primary)]">{row.agentName}</span>
|
||||
</div>
|
||||
|
||||
{/* Model + effort inline */}
|
||||
{agent && (
|
||||
<div className="mt-1 flex flex-wrap items-center gap-1">
|
||||
<span className="inline-flex items-center gap-1 text-[10px] text-zinc-500">
|
||||
<span className="inline-flex items-center gap-1 text-[10px] text-[var(--color-text-muted)]">
|
||||
{(() => {
|
||||
const prov = inferProvider(agent.model);
|
||||
return prov ? <ProviderIcon provider={prov} className="size-2.5" /> : null;
|
||||
@@ -116,8 +124,8 @@ function AgentRow({
|
||||
</span>
|
||||
{agent.reasoningEffort && (
|
||||
<>
|
||||
<span className="text-[10px] text-zinc-700">·</span>
|
||||
<span className="inline-flex items-center gap-0.5 text-[10px] text-zinc-500">
|
||||
<span className="text-[10px] text-[var(--color-text-muted)]">·</span>
|
||||
<span className="inline-flex items-center gap-0.5 text-[10px] text-[var(--color-text-muted)]">
|
||||
<Sparkles className="size-2" />
|
||||
{formatEffort(agent.reasoningEffort)}
|
||||
</span>
|
||||
@@ -133,18 +141,68 @@ 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>
|
||||
);
|
||||
}
|
||||
|
||||
/* ── Turn event helpers ─────────────────────────────────────── */
|
||||
|
||||
import type { SessionEventKind } from '@shared/domain/event';
|
||||
|
||||
function TurnEventIcon({ kind, phase, success }: { kind: SessionEventKind; phase?: string; success?: boolean }) {
|
||||
const base = 'size-3';
|
||||
switch (kind) {
|
||||
case 'subagent':
|
||||
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-[var(--color-status-warning)]' : success === false ? 'text-[var(--color-status-error)]' : 'text-[var(--color-status-success)]'}`} />;
|
||||
case 'skill-invoked':
|
||||
return <Sparkles className={`${base} text-[var(--color-accent-purple)]`} />;
|
||||
case 'session-compaction':
|
||||
return <CheckCircle2 className={`${base} ${phase === 'start' ? 'animate-pulse text-[var(--color-status-warning)]' : 'text-[var(--color-status-success)]'}`} />;
|
||||
default:
|
||||
return <Zap className={`${base} text-[var(--color-text-muted)]`} />;
|
||||
}
|
||||
}
|
||||
|
||||
function formatTurnEventTimestamp(iso: string): string {
|
||||
try {
|
||||
const d = new Date(iso);
|
||||
return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/* ── ActivityPanel ─────────────────────────────────────────── */
|
||||
|
||||
interface ActivityPanelProps {
|
||||
@@ -152,6 +210,8 @@ interface ActivityPanelProps {
|
||||
onJumpToMessage?: (messageId: string) => void;
|
||||
pattern: PatternDefinition;
|
||||
session: SessionRecord;
|
||||
sessionRequestUsage?: SessionRequestUsageState;
|
||||
turnEvents?: TurnEventLog;
|
||||
}
|
||||
|
||||
export function ActivityPanel({
|
||||
@@ -159,6 +219,8 @@ export function ActivityPanel({
|
||||
onJumpToMessage,
|
||||
pattern,
|
||||
session,
|
||||
sessionRequestUsage,
|
||||
turnEvents,
|
||||
}: ActivityPanelProps) {
|
||||
const activityRows = useMemo(
|
||||
() => buildAgentActivityRows(activity, pattern.agents),
|
||||
@@ -176,19 +238,19 @@ export function ActivityPanel({
|
||||
{/* Header — top padding clears the title bar overlay zone */}
|
||||
<div className="drag-region border-b border-[var(--color-border)] px-4 pb-3 pt-3">
|
||||
<div className="flex min-h-8 items-center gap-2">
|
||||
<Activity className="size-4 text-zinc-500" />
|
||||
<span className="text-[12px] font-semibold uppercase tracking-[0.12em] text-zinc-400">
|
||||
<Activity className="size-4 text-[var(--color-text-muted)]" />
|
||||
<span className="font-display text-[12px] font-semibold uppercase tracking-[0.12em] text-[var(--color-text-secondary)]">
|
||||
Activity
|
||||
</span>
|
||||
{hasPendingApproval ? (
|
||||
<span className="flex items-center gap-1">
|
||||
<ShieldAlert className="size-3 text-amber-400" />
|
||||
<span className="text-[9px] font-semibold uppercase tracking-wider text-amber-400">
|
||||
<ShieldAlert className="size-3 text-[var(--color-status-warning)]" />
|
||||
<span className="text-[9px] font-semibold uppercase tracking-wider text-[var(--color-status-warning)]">
|
||||
Approval{totalApprovalCount > 1 ? `s (${totalApprovalCount})` : ''}
|
||||
</span>
|
||||
</span>
|
||||
) : isBusy ? (
|
||||
<span className="size-1.5 animate-pulse rounded-full bg-blue-400" />
|
||||
<span className="size-1.5 animate-pulse rounded-full bg-[var(--color-status-info)]" />
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
@@ -199,7 +261,7 @@ export function ActivityPanel({
|
||||
<SectionHeader>
|
||||
<Users className="size-3" />
|
||||
<span>Agents</span>
|
||||
<span className="rounded-full bg-zinc-800 px-1.5 py-0.5 text-[9px] tabular-nums text-zinc-500">
|
||||
<span className="font-mono rounded-full bg-[var(--color-surface-2)] px-1.5 py-0.5 text-[9px] tabular-nums text-[var(--color-text-muted)]">
|
||||
{activityRows.length}
|
||||
</span>
|
||||
<span className={`ml-auto text-[9px] font-medium normal-case tracking-normal ${accent.label}`}>
|
||||
@@ -208,29 +270,76 @@ export function ActivityPanel({
|
||||
</SectionHeader>
|
||||
|
||||
{activityRows.length > 0 ? (
|
||||
<div className="rounded-lg border border-zinc-800 bg-zinc-900/40 px-3">
|
||||
{activityRows.map((row, index) => (
|
||||
<AgentRow
|
||||
accent={accent}
|
||||
agent={pattern.agents[index]}
|
||||
isLast={index === activityRows.length - 1}
|
||||
key={row.key}
|
||||
row={row}
|
||||
/>
|
||||
))}
|
||||
<div className="glass-surface rounded-lg px-3">
|
||||
{activityRows.map((row, index) => {
|
||||
const agentKey = row.activity?.agentId ?? row.key;
|
||||
const agentUsage = sessionRequestUsage?.perAgent[agentKey]
|
||||
?? sessionRequestUsage?.perAgent[row.agentName];
|
||||
return (
|
||||
<AgentRow
|
||||
accent={accent}
|
||||
agent={pattern.agents[index]}
|
||||
agentUsage={agentUsage}
|
||||
isLast={index === activityRows.length - 1}
|
||||
key={row.key}
|
||||
row={row}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<p className="py-4 text-center text-[11px] text-zinc-600">No agents configured</p>
|
||||
<p className="py-4 text-center text-[11px] text-[var(--color-text-muted)]">No agents configured</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ── Session usage section ──────────────────────────── */}
|
||||
{sessionRequestUsage && sessionRequestUsage.requestCount > 0 && (
|
||||
<div className="mb-4">
|
||||
<SectionHeader>
|
||||
<BarChart3 className="size-3" />
|
||||
<span>Session Usage</span>
|
||||
</SectionHeader>
|
||||
|
||||
<div className="glass-surface rounded-lg px-3 py-2.5">
|
||||
<div className="flex flex-wrap items-center gap-1.5 text-[11px] text-[var(--color-text-secondary)]">
|
||||
<span className="font-mono font-medium tabular-nums">
|
||||
{sessionRequestUsage.requestCount} premium request{sessionRequestUsage.requestCount === 1 ? '' : 's'}
|
||||
</span>
|
||||
{sessionRequestUsage.totalNanoAiu > 0 && (
|
||||
<>
|
||||
<span className="text-[var(--color-text-muted)]">·</span>
|
||||
<span className="font-mono tabular-nums">{formatNanoAiu(sessionRequestUsage.totalNanoAiu)} AIU</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-1 flex flex-wrap items-center gap-1.5 text-[10px] text-[var(--color-text-muted)]">
|
||||
<span className="font-mono tabular-nums">{formatTokenCount(sessionRequestUsage.totalInputTokens)} in</span>
|
||||
<span className="text-[var(--color-text-muted)]">·</span>
|
||||
<span className="font-mono tabular-nums">{formatTokenCount(sessionRequestUsage.totalOutputTokens)} out</span>
|
||||
{sessionRequestUsage.totalCost > 0 && (
|
||||
<>
|
||||
<span className="text-[var(--color-text-muted)]">·</span>
|
||||
<span className="font-mono tabular-nums">{sessionRequestUsage.totalCost.toFixed(2)} cost</span>
|
||||
</>
|
||||
)}
|
||||
{sessionRequestUsage.totalDurationMs > 0 && (
|
||||
<>
|
||||
<span className="text-[var(--color-text-muted)]">·</span>
|
||||
<span className="font-mono tabular-nums">{formatDuration(sessionRequestUsage.totalDurationMs)} total</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Run timeline section ─────────────────────────── */}
|
||||
<div className="mb-4">
|
||||
<SectionHeader>
|
||||
<Clock className="size-3" />
|
||||
<span>Timeline</span>
|
||||
{session.runs.length > 0 && (
|
||||
<span className="rounded-full bg-zinc-800 px-1.5 py-0.5 text-[9px] tabular-nums text-zinc-500">
|
||||
<span className="font-mono rounded-full bg-[var(--color-surface-2)] px-1.5 py-0.5 text-[9px] tabular-nums text-[var(--color-text-muted)]">
|
||||
{session.runs.length}
|
||||
</span>
|
||||
)}
|
||||
@@ -239,6 +348,39 @@ export function ActivityPanel({
|
||||
<RunTimeline onJumpToMessage={onJumpToMessage} runs={session.runs} />
|
||||
</div>
|
||||
|
||||
{/* ── Turn events section ─────────────────────────── */}
|
||||
{turnEvents && turnEvents.length > 0 && (
|
||||
<div className="mb-4">
|
||||
<SectionHeader>
|
||||
<Zap className="size-3" />
|
||||
<span>Events</span>
|
||||
<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="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">
|
||||
<TurnEventIcon kind={entry.kind} phase={entry.phase} success={entry.success} />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<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-[var(--color-text-muted)]">{entry.detail}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
|
||||
@@ -4,24 +4,39 @@ interface AppShellProps {
|
||||
sidebar: ReactNode;
|
||||
content: ReactNode;
|
||||
detailPanel?: ReactNode;
|
||||
terminalPanel?: ReactNode;
|
||||
overlay?: ReactNode;
|
||||
}
|
||||
|
||||
export function AppShell({ sidebar, content, detailPanel, overlay }: AppShellProps) {
|
||||
export function AppShell({ sidebar, content, detailPanel, terminalPanel, overlay }: AppShellProps) {
|
||||
return (
|
||||
<div className="relative flex h-screen bg-[var(--color-surface-0)] text-zinc-100">
|
||||
<div className="relative flex h-screen bg-[var(--color-surface-0)] text-[var(--color-text-primary)]">
|
||||
{/* Full-width drag region matching the title bar overlay height */}
|
||||
<div className="drag-region absolute inset-x-0 top-0 z-10 h-3" />
|
||||
|
||||
<aside className="flex w-72 shrink-0 flex-col border-r border-[var(--color-border)] bg-[var(--color-surface-1)]">
|
||||
{/* Sidebar */}
|
||||
<aside className="flex w-72 shrink-0 flex-col border-r border-[var(--color-border-subtle)] bg-[var(--color-surface-1)]">
|
||||
{sidebar}
|
||||
</aside>
|
||||
<main className="relative min-w-0 flex-1">{content}</main>
|
||||
|
||||
{/* Main content + terminal */}
|
||||
<main className="relative flex min-w-0 flex-1 flex-col">
|
||||
{/* Ambient glow behind active content area */}
|
||||
<div
|
||||
className="pointer-events-none absolute inset-0 opacity-30"
|
||||
style={{ background: 'var(--gradient-glow)' }}
|
||||
/>
|
||||
<div className="relative min-h-0 flex-1">{content}</div>
|
||||
{terminalPanel}
|
||||
</main>
|
||||
|
||||
{/* Detail panel */}
|
||||
{detailPanel && (
|
||||
<aside className="flex w-64 shrink-0 flex-col border-l border-[var(--color-border)] bg-[var(--color-surface-1)]">
|
||||
<aside className="flex w-64 shrink-0 flex-col border-l border-[var(--color-border-subtle)] bg-[var(--color-surface-1)]">
|
||||
{detailPanel}
|
||||
</aside>
|
||||
)}
|
||||
|
||||
{overlay}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,13 +1,25 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { AlertCircle, ArrowUp, Bot, Circle, GitBranch, Loader2, ShieldAlert, Square, User } 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 { InlineApprovalPill, InlineModelPill, InlineThinkingPill, InlineToolsPill } from '@renderer/components/chat/InlinePills';
|
||||
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, InlineTerminalPill, InlineThinkingPill, InlineToolsPill } from '@renderer/components/chat/InlinePills';
|
||||
import { InlinePromptPill } from '@renderer/components/chat/InlinePromptPill';
|
||||
import { ThinkingDots } from '@renderer/components/chat/ThinkingDots';
|
||||
import { SubagentActivityList } from '@renderer/components/chat/SubagentActivityCard';
|
||||
import { getAssistantMessagePhase } from '@renderer/lib/messagePhase';
|
||||
import type { ApprovalDecision } from '@shared/domain/approval';
|
||||
import type { InteractionMode, MessageMode } from '@shared/contracts/sidecar';
|
||||
import type { ChatMessageAttachment } from '@shared/domain/attachment';
|
||||
import { getAttachmentDisplayName, isImageAttachment } from '@shared/domain/attachment';
|
||||
import type { SessionUsageState } from '@renderer/lib/sessionActivity';
|
||||
import type { ActiveSubagent } from '@renderer/lib/subagentTracker';
|
||||
import {
|
||||
findModel,
|
||||
getSupportedReasoningEfforts,
|
||||
@@ -16,8 +28,9 @@ import {
|
||||
} from '@shared/domain/models';
|
||||
import { type PatternDefinition, type ReasoningEffort } from '@shared/domain/pattern';
|
||||
import { isScratchpadProject, type ProjectRecord } from '@shared/domain/project';
|
||||
import { resolveSessionToolingSelection, type SessionRecord } from '@shared/domain/session';
|
||||
import { resolveSessionToolingSelection, type SessionBranchOriginAction, type SessionRecord } from '@shared/domain/session';
|
||||
import {
|
||||
groupApprovalToolsByProvider,
|
||||
listApprovalToolDefinitions,
|
||||
type RuntimeToolDefinition,
|
||||
type SessionToolingSelection,
|
||||
@@ -32,16 +45,32 @@ interface ChatPaneProps {
|
||||
session: SessionRecord;
|
||||
availableModels: ReadonlyArray<ModelDefinition>;
|
||||
toolingSettings: WorkspaceToolingSettings;
|
||||
mcpProbingServerIds?: string[];
|
||||
runtimeTools?: ReadonlyArray<RuntimeToolDefinition>;
|
||||
onSend: (content: string) => Promise<void>;
|
||||
sessionUsage?: SessionUsageState;
|
||||
activeSubagents?: ReadonlyArray<ActiveSubagent>;
|
||||
terminalOpen?: boolean;
|
||||
terminalRunning?: boolean;
|
||||
onSend: (content: string, attachments?: ChatMessageAttachment[], messageMode?: MessageMode) => Promise<void>;
|
||||
onCancelTurn?: () => void;
|
||||
onResolveApproval?: (approvalId: string, decision: ApprovalDecision) => Promise<unknown>;
|
||||
onResolveApproval?: (approvalId: string, decision: ApprovalDecision, alwaysApprove?: boolean) => Promise<unknown>;
|
||||
onResolveUserInput?: (userInputId: string, answer: string, wasFreeform: boolean) => Promise<unknown>;
|
||||
onSetInteractionMode?: (mode: InteractionMode) => void;
|
||||
onDismissPlanReview?: () => void;
|
||||
onDismissMcpAuth?: () => void;
|
||||
onAuthenticateMcp?: () => void;
|
||||
onTerminalToggle?: () => void;
|
||||
onUpdateSessionModelConfig?: (config: {
|
||||
model: string;
|
||||
reasoningEffort?: ReasoningEffort;
|
||||
}) => Promise<unknown>;
|
||||
onUpdateSessionTooling?: (selection: SessionToolingSelection) => void;
|
||||
onUpdateSessionApprovalSettings?: (settings: { autoApprovedToolNames?: string[] }) => void;
|
||||
onBranchFromMessage?: (messageId: string) => void;
|
||||
onPinMessage?: (messageId: string, isPinned: boolean) => void;
|
||||
onRegenerateMessage?: (messageId: string) => void;
|
||||
onEditAndResendMessage?: (messageId: string, content: string) => void;
|
||||
branchOriginLabel?: string;
|
||||
}
|
||||
|
||||
export function ChatPane({
|
||||
@@ -50,34 +79,68 @@ export function ChatPane({
|
||||
session,
|
||||
availableModels,
|
||||
toolingSettings,
|
||||
mcpProbingServerIds,
|
||||
runtimeTools,
|
||||
sessionUsage,
|
||||
activeSubagents,
|
||||
terminalOpen,
|
||||
terminalRunning,
|
||||
onSend,
|
||||
onCancelTurn,
|
||||
onResolveApproval,
|
||||
onResolveUserInput,
|
||||
onSetInteractionMode,
|
||||
onDismissPlanReview,
|
||||
onDismissMcpAuth,
|
||||
onAuthenticateMcp,
|
||||
onTerminalToggle,
|
||||
onUpdateSessionModelConfig,
|
||||
onUpdateSessionTooling,
|
||||
onUpdateSessionApprovalSettings,
|
||||
onBranchFromMessage,
|
||||
onPinMessage,
|
||||
onRegenerateMessage,
|
||||
onEditAndResendMessage,
|
||||
branchOriginLabel,
|
||||
}: ChatPaneProps) {
|
||||
const [hasComposerContent, setHasComposerContent] = useState(false);
|
||||
const [configError, setConfigError] = useState<string>();
|
||||
const [approvalError, setApprovalError] = useState<string>();
|
||||
const [isResolvingApproval, setIsResolvingApproval] = useState(false);
|
||||
const [isSubmittingUserInput, setIsSubmittingUserInput] = useState(false);
|
||||
const [isUpdatingSessionModelConfig, setIsUpdatingSessionModelConfig] = useState(false);
|
||||
const [editingMessageId, setEditingMessageId] = useState<string>();
|
||||
const transcriptRef = useRef<HTMLDivElement>(null);
|
||||
const composerRef = useRef<MarkdownComposerHandle>(null);
|
||||
|
||||
const isSessionBusy = session.status === 'running';
|
||||
const lastAssistantIndex = useMemo(() => {
|
||||
for (let i = session.messages.length - 1; i >= 0; i--) {
|
||||
if (session.messages[i].role === 'assistant') return i;
|
||||
}
|
||||
return -1;
|
||||
}, [session.messages]);
|
||||
const pendingApproval = session.pendingApproval?.status === 'pending' ? session.pendingApproval : undefined;
|
||||
const queuedApprovals = (session.pendingApprovalQueue ?? []).filter((a) => a.status === 'pending');
|
||||
const totalPendingCount = (pendingApproval ? 1 : 0) + queuedApprovals.length;
|
||||
const pendingUserInput = session.pendingUserInput?.status === 'pending' ? session.pendingUserInput : undefined;
|
||||
const pendingPlanReview = session.pendingPlanReview?.status === 'pending' ? session.pendingPlanReview : undefined;
|
||||
const pendingMcpAuth = session.pendingMcpAuth?.status === 'pending' || session.pendingMcpAuth?.status === 'authenticating'
|
||||
|| session.pendingMcpAuth?.status === 'failed'
|
||||
? session.pendingMcpAuth
|
||||
: undefined;
|
||||
const interactionMode: InteractionMode = session.interactionMode ?? 'interactive';
|
||||
const isPlanMode = interactionMode === 'plan';
|
||||
const isScratchpad = isScratchpadProject(project);
|
||||
const isSingleAgent = pattern.agents.length === 1;
|
||||
const primaryAgent = pattern.agents[0];
|
||||
const selectedModel = primaryAgent ? findModel(primaryAgent.model, availableModels) : undefined;
|
||||
const supportedEfforts = getSupportedReasoningEfforts(selectedModel);
|
||||
const sessionReasoningEffort = resolveReasoningEffort(selectedModel, primaryAgent?.reasoningEffort);
|
||||
const isComposerDisabled = isSessionBusy || isUpdatingSessionModelConfig;
|
||||
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;
|
||||
@@ -97,6 +160,22 @@ export function ChatPane({
|
||||
),
|
||||
[isApprovalOverridden, session.approvalSettings, pattern.approvalPolicy],
|
||||
);
|
||||
const effectiveAutoApprovedCount = useMemo(() => {
|
||||
const groups = groupApprovalToolsByProvider(approvalTools, toolingSettings);
|
||||
const counted = new Set<string>();
|
||||
for (const group of groups) {
|
||||
if (group.serverApprovalKey && effectiveAutoApproved.has(group.serverApprovalKey)) {
|
||||
for (const tool of group.tools) counted.add(tool.id);
|
||||
} else {
|
||||
for (const tool of group.tools) {
|
||||
if (effectiveAutoApproved.has(tool.id)) counted.add(tool.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
return counted.size;
|
||||
}, [approvalTools, effectiveAutoApproved, toolingSettings]);
|
||||
const isProbingMcp = (mcpProbingServerIds?.length ?? 0) > 0;
|
||||
const hasApprovalContent = approvalTools.length > 0 || isProbingMcp;
|
||||
|
||||
useEffect(() => {
|
||||
transcriptRef.current?.scrollTo({
|
||||
@@ -110,10 +189,38 @@ export function ChatPane({
|
||||
setApprovalError(undefined);
|
||||
setIsResolvingApproval(false);
|
||||
setIsUpdatingSessionModelConfig(false);
|
||||
setEditingMessageId(undefined);
|
||||
}, [session.id]);
|
||||
|
||||
function handleComposerSubmit(content: string) {
|
||||
void onSend(content);
|
||||
const attachments = pendingAttachments.length > 0 ? [...pendingAttachments] : undefined;
|
||||
const messageMode: MessageMode | undefined = isSessionBusy ? 'immediate' : undefined;
|
||||
setPendingAttachments([]);
|
||||
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?.();
|
||||
}
|
||||
|
||||
function handleDismissMcpAuth() {
|
||||
onDismissMcpAuth?.();
|
||||
}
|
||||
|
||||
function handleAuthenticateMcp() {
|
||||
onAuthenticateMcp?.();
|
||||
}
|
||||
|
||||
async function handleSessionModelConfigChange(config: {
|
||||
@@ -143,14 +250,14 @@ export function ChatPane({
|
||||
}
|
||||
}
|
||||
|
||||
async function handleResolveApproval(decision: ApprovalDecision) {
|
||||
async function handleResolveApproval(decision: ApprovalDecision, alwaysApprove?: boolean) {
|
||||
if (!pendingApproval || !onResolveApproval || isResolvingApproval) return;
|
||||
|
||||
setApprovalError(undefined);
|
||||
setIsResolvingApproval(true);
|
||||
|
||||
try {
|
||||
await onResolveApproval(pendingApproval.id, decision);
|
||||
await onResolveApproval(pendingApproval.id, decision, alwaysApprove);
|
||||
} catch (error) {
|
||||
setApprovalError(error instanceof Error ? error.message : String(error));
|
||||
} finally {
|
||||
@@ -158,19 +265,33 @@ export function ChatPane({
|
||||
}
|
||||
}
|
||||
|
||||
async function handleResolveUserInput(answer: string, wasFreeform: boolean) {
|
||||
if (!pendingUserInput || !onResolveUserInput || isSubmittingUserInput) return;
|
||||
|
||||
setIsSubmittingUserInput(true);
|
||||
|
||||
try {
|
||||
await onResolveUserInput(pendingUserInput.id, answer, wasFreeform);
|
||||
} catch {
|
||||
// User input errors are non-critical; the turn will fail and show the error status
|
||||
} finally {
|
||||
setIsSubmittingUserInput(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
{/* Header — extra top padding clears the title bar overlay zone */}
|
||||
<header className="drag-region border-b border-[var(--color-border)] px-6 pb-3 pt-3">
|
||||
<header className="drag-region border-b border-[var(--color-border-subtle)] px-6 pb-3 pt-3">
|
||||
<div className="flex min-h-8 items-center justify-between">
|
||||
<div className="min-w-0">
|
||||
<h2 className="truncate text-[13px] font-semibold leading-tight text-zinc-100">{session.title}</h2>
|
||||
<p className="truncate text-[11px] leading-tight text-zinc-500">
|
||||
<h2 className="font-display truncate text-[13px] font-semibold leading-tight text-[var(--color-text-primary)]">{session.title}</h2>
|
||||
<p className="truncate text-[11px] leading-tight text-[var(--color-text-muted)]">
|
||||
{isScratchpad
|
||||
? `Scratchpad · ${pattern.name}`
|
||||
: `${project.name} · ${pattern.name} · ${pattern.mode}`}
|
||||
{!isScratchpad && project.git?.status === 'ready' && (
|
||||
<span className="ml-2 inline-flex items-center gap-1 text-zinc-600">
|
||||
<span className="ml-2 inline-flex items-center gap-1 text-[var(--color-text-muted)]">
|
||||
<GitBranch className="inline size-2.5" />
|
||||
{project.git.branch ?? project.git.head?.shortHash ?? 'HEAD'}
|
||||
{project.git.isDirty && (
|
||||
@@ -184,25 +305,31 @@ export function ChatPane({
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{pendingApproval && (
|
||||
<div className="flex items-center gap-1.5 text-[12px] font-medium text-amber-400">
|
||||
<div className="flex items-center gap-1.5 text-[12px] font-medium text-[var(--color-status-warning)]">
|
||||
<ShieldAlert className="size-3.5" />
|
||||
Awaiting approval
|
||||
{queuedApprovals.length > 0 && (
|
||||
<span className="rounded-full bg-amber-500/15 px-1.5 py-0.5 text-[10px] tabular-nums">
|
||||
<span className="rounded-full bg-[var(--color-status-warning)]/15 px-1.5 py-0.5 text-[10px] tabular-nums">
|
||||
+{queuedApprovals.length} queued
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{isSessionBusy && !pendingApproval && <span className="size-2 animate-pulse rounded-full bg-blue-400" />}
|
||||
{pendingUserInput && !pendingApproval && (
|
||||
<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-[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 && session.messages.length > 0 && (
|
||||
<span className="text-[12px] text-zinc-600">
|
||||
{session.status === 'idle' && !pendingApproval && !pendingUserInput && session.messages.length > 0 && (
|
||||
<span className="text-[12px] text-[var(--color-text-muted)]">
|
||||
{session.messages.length} message{session.messages.length === 1 ? '' : 's'}
|
||||
</span>
|
||||
)}
|
||||
@@ -214,54 +341,67 @@ export function ChatPane({
|
||||
<div className="flex-1 overflow-y-auto" ref={transcriptRef}>
|
||||
{session.messages.length === 0 ? (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-2 px-6 text-center">
|
||||
<Bot className="size-10 text-zinc-800" />
|
||||
<p className="text-[13px] text-zinc-500">Send a message to start the conversation</p>
|
||||
<p className="text-[12px] text-zinc-700">
|
||||
<Bot className="size-10 text-[var(--color-surface-3)]" />
|
||||
<p className="text-[13px] text-[var(--color-text-muted)]">Send a message to start the conversation</p>
|
||||
<p className="text-[12px] text-[var(--color-text-muted)]">
|
||||
{isScratchpad ? (
|
||||
<>
|
||||
Scratchpad is ready for ad-hoc questions using{' '}
|
||||
<span className="text-zinc-500">{pattern.name}</span>
|
||||
<span className="text-[var(--color-text-secondary)]">{pattern.name}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
Using <span className="text-zinc-500">{pattern.name}</span> in{' '}
|
||||
<span className="text-zinc-500">{project.name}</span>
|
||||
Using <span className="text-[var(--color-text-secondary)]">{pattern.name}</span> in{' '}
|
||||
<span className="text-[var(--color-text-secondary)]">{project.name}</span>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="mx-auto max-w-3xl px-6 py-4">
|
||||
{/* Branch origin banner */}
|
||||
{session.branchOrigin && (
|
||||
<BranchOriginBanner
|
||||
action={session.branchOrigin.action}
|
||||
label={branchOriginLabel}
|
||||
/>
|
||||
)}
|
||||
<div className="space-y-1">
|
||||
{session.messages.map((message, index) => {
|
||||
const isUser = message.role === 'user';
|
||||
const isEditing = editingMessageId === message.id;
|
||||
const isLastAssistant = index === lastAssistantIndex;
|
||||
const phase = getAssistantMessagePhase(session, message, index);
|
||||
const assistantContainerClass =
|
||||
phase === 'thinking'
|
||||
? 'border-sky-500/20 bg-sky-500/5'
|
||||
? 'border-[var(--color-accent-sky)]/20 bg-[var(--color-accent-sky)]/5'
|
||||
: phase === 'final'
|
||||
? 'border-emerald-500/20 bg-emerald-500/5'
|
||||
: 'border-zinc-800 bg-zinc-900/40';
|
||||
? 'border-[var(--color-status-success)]/20 bg-[var(--color-status-success)]/5'
|
||||
: 'border-[var(--color-border)] bg-[var(--color-surface-1)]/40';
|
||||
const assistantBadgeClass =
|
||||
phase === 'thinking'
|
||||
? 'border-sky-400/20 bg-sky-400/10 text-sky-300'
|
||||
: 'border-emerald-400/20 bg-emerald-400/10 text-emerald-300';
|
||||
? 'border-[var(--color-accent-sky)]/20 bg-[var(--color-accent-sky)]/10 text-[var(--color-accent-sky)]'
|
||||
: 'border-[var(--color-status-success)]/20 bg-[var(--color-status-success)]/10 text-[var(--color-status-success)]';
|
||||
const phaseLabel =
|
||||
phase === 'thinking' ? 'Thinking' : phase === 'final' ? 'Final' : undefined;
|
||||
const showActions = !isSessionBusy && !message.pending;
|
||||
|
||||
return (
|
||||
<div className="group py-3" data-message-id={message.id} key={message.id}>
|
||||
<div className="message-enter group py-3" data-message-id={message.id} key={message.id}>
|
||||
<div className="flex gap-3">
|
||||
<div
|
||||
className={`mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-full ${
|
||||
isUser ? 'bg-indigo-600 text-white' : 'bg-zinc-800 text-zinc-400'
|
||||
isUser ? 'brand-gradient-bg text-white' : 'bg-[var(--color-surface-2)] text-[var(--color-text-secondary)]'
|
||||
}`}
|
||||
>
|
||||
{isUser ? <User className="size-3.5" /> : <Bot className="size-3.5" />}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="mb-1 flex items-center gap-2 text-[12px] font-medium text-zinc-400">
|
||||
<div className="mb-1 flex items-center gap-2 text-[12px] font-medium text-[var(--color-text-secondary)]">
|
||||
<span>{message.authorName}</span>
|
||||
{message.isPinned && (
|
||||
<Bookmark className="size-3 fill-[var(--color-accent-sky)] text-[var(--color-accent-sky)]" />
|
||||
)}
|
||||
{!isUser && phaseLabel && (
|
||||
<span
|
||||
className={`inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.08em] ${assistantBadgeClass}`}
|
||||
@@ -269,25 +409,71 @@ export function ChatPane({
|
||||
{phaseLabel}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className={
|
||||
isUser
|
||||
? 'text-[14px] leading-relaxed text-zinc-200'
|
||||
: `rounded-xl border px-4 py-3 text-[14px] leading-relaxed text-zinc-200 ${assistantContainerClass}`
|
||||
}
|
||||
>
|
||||
{!isUser && message.pending ? (
|
||||
<div className="whitespace-pre-wrap break-words text-[14px] leading-relaxed text-zinc-200">
|
||||
{message.content}
|
||||
{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>
|
||||
) : (
|
||||
<MarkdownContent content={message.content} />
|
||||
)}
|
||||
{message.pending && message.content && (
|
||||
<span className="mt-1 inline-block h-4 w-[2px] animate-pulse rounded-sm bg-zinc-400" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Edit mode */}
|
||||
{isEditing ? (
|
||||
<MessageEditComposer
|
||||
initialContent={message.content}
|
||||
onSave={(content) => handleEditSave(message.id, content)}
|
||||
onCancel={() => setEditingMessageId(undefined)}
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
className={
|
||||
isUser
|
||||
? 'text-[14px] leading-relaxed text-[var(--color-text-primary)]'
|
||||
: `rounded-xl border px-4 py-3 text-[14px] leading-relaxed text-[var(--color-text-primary)] ${assistantContainerClass}`
|
||||
}
|
||||
>
|
||||
{/* Attachment thumbnails */}
|
||||
{isUser && message.attachments && message.attachments.length > 0 && (
|
||||
<div className="mb-2 flex flex-wrap gap-2">
|
||||
{message.attachments.map((att, attIdx) =>
|
||||
isImageAttachment(att) ? (
|
||||
<img
|
||||
key={attIdx}
|
||||
alt={getAttachmentDisplayName(att)}
|
||||
className="max-h-48 max-w-xs rounded-lg border border-[var(--color-border)] object-cover"
|
||||
src={`data:${att.mimeType};base64,${att.data}`}
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
key={attIdx}
|
||||
className="flex items-center gap-1.5 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-2)] px-2 py-1 text-[11px] text-[var(--color-text-secondary)]"
|
||||
>
|
||||
<Paperclip className="size-3" />
|
||||
{getAttachmentDisplayName(att)}
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!isUser && message.pending ? (
|
||||
<div className="whitespace-pre-wrap break-words text-[14px] leading-relaxed text-[var(--color-text-primary)]">
|
||||
{message.content}
|
||||
</div>
|
||||
) : (
|
||||
<MarkdownContent content={message.content} />
|
||||
)}
|
||||
{message.pending && message.content && (
|
||||
<span className="mt-1 inline-block h-4 w-[2px] animate-pulse rounded-sm bg-[var(--color-accent)]" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{message.pending && !message.content && <ThinkingDots />}
|
||||
</div>
|
||||
</div>
|
||||
@@ -295,29 +481,34 @@ export function ChatPane({
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{activeSubagents && activeSubagents.length > 0 && (
|
||||
<div className="px-6 py-1">
|
||||
<SubagentActivityList subagents={activeSubagents} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Input area */}
|
||||
<div className="border-t border-[var(--color-border)] px-6 py-4">
|
||||
<div className="border-t border-[var(--color-border-subtle)] px-6 py-4">
|
||||
{session.lastError && (
|
||||
<div className="mb-3 flex items-start gap-2 rounded-lg bg-red-500/10 px-3 py-2 text-[13px] text-red-300">
|
||||
<AlertCircle className="mt-0.5 size-4 shrink-0 text-red-400" />
|
||||
<div className="mb-3 flex items-start gap-2 rounded-lg bg-[var(--color-status-error)]/10 px-3 py-2 text-[13px] text-[var(--color-status-error)]">
|
||||
<AlertCircle className="mt-0.5 size-4 shrink-0 text-[var(--color-status-error)]" />
|
||||
<span>{session.lastError}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{configError && (
|
||||
<div className="mb-3 flex items-start gap-2 rounded-lg bg-red-500/10 px-3 py-2 text-[13px] text-red-300">
|
||||
<AlertCircle className="mt-0.5 size-4 shrink-0 text-red-400" />
|
||||
<div className="mb-3 flex items-start gap-2 rounded-lg bg-[var(--color-status-error)]/10 px-3 py-2 text-[13px] text-[var(--color-status-error)]">
|
||||
<AlertCircle className="mt-0.5 size-4 shrink-0 text-[var(--color-status-error)]" />
|
||||
<span>{configError}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{approvalError && (
|
||||
<div className="mb-3 flex items-start gap-2 rounded-lg bg-red-500/10 px-3 py-2 text-[13px] text-red-300">
|
||||
<AlertCircle className="mt-0.5 size-4 shrink-0 text-red-400" />
|
||||
<div className="mb-3 flex items-start gap-2 rounded-lg bg-[var(--color-status-error)]/10 px-3 py-2 text-[13px] text-[var(--color-status-error)]">
|
||||
<AlertCircle className="mt-0.5 size-4 shrink-0 text-[var(--color-status-error)]" />
|
||||
<span>{approvalError}</span>
|
||||
</div>
|
||||
)}
|
||||
@@ -325,11 +516,11 @@ 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}
|
||||
onResolve={(decision) => void handleResolveApproval(decision)}
|
||||
onResolve={(decision, alwaysApprove) => void handleResolveApproval(decision, alwaysApprove)}
|
||||
position={totalPendingCount > 1 ? 1 : undefined}
|
||||
total={totalPendingCount > 1 ? totalPendingCount : undefined}
|
||||
/>
|
||||
@@ -339,6 +530,38 @@ export function ChatPane({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Pending user input banner */}
|
||||
{pendingUserInput && (
|
||||
<div className="mb-3">
|
||||
<UserInputBanner
|
||||
isSubmitting={isSubmittingUserInput}
|
||||
onSubmit={(answer, wasFreeform) => void handleResolveUserInput(answer, wasFreeform)}
|
||||
userInput={pendingUserInput}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Plan review banner */}
|
||||
{pendingPlanReview && (
|
||||
<div className="mb-3">
|
||||
<PlanReviewBanner
|
||||
onDismiss={handleDismissPlan}
|
||||
planReview={pendingPlanReview}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* MCP auth required banner */}
|
||||
{pendingMcpAuth && (
|
||||
<div className="mb-3">
|
||||
<McpAuthBanner
|
||||
mcpAuth={pendingMcpAuth}
|
||||
onAuthenticate={handleAuthenticateMcp}
|
||||
onDismiss={handleDismissMcpAuth}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Session config pills — tools/approval left, model/reasoning right */}
|
||||
{isSingleAgent && (
|
||||
<div className="mb-2 flex items-center gap-2">
|
||||
@@ -351,13 +574,16 @@ export function ChatPane({
|
||||
selection={toolSelection}
|
||||
/>
|
||||
)}
|
||||
{hasToolCallApproval && onUpdateSessionApprovalSettings && approvalTools.length > 0 && (
|
||||
{hasToolCallApproval && onUpdateSessionApprovalSettings && hasApprovalContent && (
|
||||
<InlineApprovalPill
|
||||
approvalTools={approvalTools}
|
||||
disabled={isComposerDisabled}
|
||||
effectiveAutoApproved={effectiveAutoApproved}
|
||||
effectiveAutoApprovedCount={effectiveAutoApprovedCount}
|
||||
isOverridden={isApprovalOverridden}
|
||||
mcpProbingServerIds={mcpProbingServerIds}
|
||||
onUpdate={onUpdateSessionApprovalSettings}
|
||||
toolingSettings={toolingSettings}
|
||||
/>
|
||||
)}
|
||||
{primaryAgent && (
|
||||
@@ -386,7 +612,7 @@ export function ChatPane({
|
||||
value={sessionReasoningEffort}
|
||||
/>
|
||||
{isUpdatingSessionModelConfig && (
|
||||
<Loader2 className="size-3 animate-spin text-zinc-500" />
|
||||
<Loader2 className="size-3 animate-spin text-[var(--color-text-muted)]" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
@@ -405,19 +631,45 @@ 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>
|
||||
)}
|
||||
|
||||
<div className="rounded-xl border border-zinc-700 bg-zinc-900 transition-colors focus-within:border-indigo-500/50">
|
||||
{/* Attachment preview */}
|
||||
{pendingAttachments.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2 px-1 pb-2">
|
||||
{pendingAttachments.map((attachment, index) => (
|
||||
<div
|
||||
key={index}
|
||||
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-[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-[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"
|
||||
>
|
||||
<X className="size-3" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<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}
|
||||
@@ -426,42 +678,205 @@ export function ChatPane({
|
||||
placeholder={
|
||||
pendingApproval
|
||||
? 'Awaiting approval...'
|
||||
: isSessionBusy
|
||||
? 'Waiting for response...'
|
||||
: isUpdatingSessionModelConfig
|
||||
? 'Saving model settings...'
|
||||
: 'Message...'
|
||||
: pendingUserInput
|
||||
? 'Awaiting your input above...'
|
||||
: pendingPlanReview
|
||||
? 'Review the plan above...'
|
||||
: pendingMcpAuth
|
||||
? 'MCP server requires authentication...'
|
||||
: isSessionBusy
|
||||
? 'Steer the agent (sends immediately)...'
|
||||
: isUpdatingSessionModelConfig
|
||||
? 'Saving model settings...'
|
||||
: isPlanMode
|
||||
? 'Describe what to plan...'
|
||||
: 'Message...'
|
||||
}
|
||||
>
|
||||
<button
|
||||
className={`absolute bottom-2 right-2 flex size-8 items-center justify-center rounded-lg transition ${
|
||||
isSessionBusy
|
||||
? 'bg-red-600/80 text-white hover:bg-red-500'
|
||||
: canSubmitInput
|
||||
? 'bg-indigo-600 text-white hover:bg-indigo-500'
|
||||
: 'bg-zinc-800 text-zinc-600'
|
||||
}`}
|
||||
disabled={!canSubmitInput && !isSessionBusy}
|
||||
onClick={() => {
|
||||
if (isSessionBusy) {
|
||||
onCancelTurn?.();
|
||||
} else {
|
||||
composerRef.current?.submit();
|
||||
}
|
||||
}}
|
||||
type="button"
|
||||
aria-label={isSessionBusy ? 'Stop generating' : 'Send message'}
|
||||
>
|
||||
{isSessionBusy ? (
|
||||
<Square className="size-3.5" fill="currentColor" />
|
||||
) : (
|
||||
<ArrowUp className="size-4" />
|
||||
{/* Bottom action bar: left = shortcuts, right = buttons */}
|
||||
<div className="flex items-center justify-between px-2 pb-2">
|
||||
{/* Left: quick actions */}
|
||||
<div className="flex items-center gap-1.5">
|
||||
{onTerminalToggle && (
|
||||
<InlineTerminalPill
|
||||
disabled={false}
|
||||
isOpen={!!terminalOpen}
|
||||
isRunning={!!terminalRunning}
|
||||
onToggle={onTerminalToggle}
|
||||
/>
|
||||
)}
|
||||
{!isScratchpad && promptFiles.length > 0 && (
|
||||
<InlinePromptPill
|
||||
disabled={isComposerDisabled}
|
||||
onSubmit={(content) => void onSend(content)}
|
||||
promptFiles={promptFiles}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Right: attach, plan mode, send */}
|
||||
<div className="flex items-center gap-1">
|
||||
{/* Attachment picker */}
|
||||
<button
|
||||
aria-label="Attach image"
|
||||
className="flex size-8 items-center justify-center rounded-lg text-[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');
|
||||
input.type = 'file';
|
||||
input.accept = 'image/jpeg,image/png,image/gif,image/webp';
|
||||
input.multiple = true;
|
||||
input.onchange = () => {
|
||||
if (!input.files) return;
|
||||
const newAttachments: ChatMessageAttachment[] = [];
|
||||
for (const file of input.files) {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
const base64 = (reader.result as string).split(',')[1];
|
||||
setPendingAttachments((prev) => [
|
||||
...prev,
|
||||
{ type: 'blob', data: base64, mimeType: file.type, displayName: file.name },
|
||||
]);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
};
|
||||
input.click();
|
||||
}}
|
||||
type="button"
|
||||
>
|
||||
<Paperclip className="size-3.5" />
|
||||
</button>
|
||||
|
||||
{/* Plan mode toggle */}
|
||||
{onSetInteractionMode && !isSessionBusy && (
|
||||
<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-all duration-150 ${
|
||||
isPlanMode
|
||||
? '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')}
|
||||
type="button"
|
||||
>
|
||||
<ClipboardList className="size-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Send / Stop / Steer button */}
|
||||
<button
|
||||
className={`flex size-8 items-center justify-center rounded-lg transition-all duration-150 ${
|
||||
isSessionBusy && !hasComposerContent && pendingAttachments.length === 0
|
||||
? 'bg-[var(--color-status-error)]/80 text-white hover:bg-[var(--color-status-error)]'
|
||||
: canSubmitInput || pendingAttachments.length > 0
|
||||
? isSessionBusy
|
||||
? 'bg-[var(--color-status-warning)] text-white hover:brightness-110'
|
||||
: isPlanMode
|
||||
? '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={() => {
|
||||
if (isSessionBusy && !hasComposerContent && pendingAttachments.length === 0) {
|
||||
onCancelTurn?.();
|
||||
} else {
|
||||
composerRef.current?.submit();
|
||||
}
|
||||
}}
|
||||
type="button"
|
||||
aria-label={
|
||||
isSessionBusy && !hasComposerContent && pendingAttachments.length === 0
|
||||
? 'Stop generating'
|
||||
: isSessionBusy
|
||||
? 'Steer agent'
|
||||
: isPlanMode
|
||||
? 'Send as plan request'
|
||||
: 'Send message'
|
||||
}
|
||||
>
|
||||
{isSessionBusy && !hasComposerContent && pendingAttachments.length === 0 ? (
|
||||
<Square className="size-3.5" fill="currentColor" />
|
||||
) : (
|
||||
<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-[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-[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>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Session usage bar */}
|
||||
{sessionUsage && sessionUsage.tokenLimit > 0 && (
|
||||
<div className="px-1 pt-1.5">
|
||||
<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-[var(--color-status-error)]'
|
||||
: sessionUsage.currentTokens / sessionUsage.tokenLimit > 0.7
|
||||
? 'bg-[var(--color-status-warning)]'
|
||||
: 'bg-[var(--color-accent)]/60'
|
||||
}`}
|
||||
style={{ width: `${Math.min(100, (sessionUsage.currentTokens / sessionUsage.tokenLimit) * 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="tabular-nums">
|
||||
{Math.round((sessionUsage.currentTokens / sessionUsage.tokenLimit) * 100)}% context
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,497 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
Archive,
|
||||
Copy,
|
||||
FolderOpen,
|
||||
FolderPlus,
|
||||
Keyboard,
|
||||
MessageSquare,
|
||||
Monitor,
|
||||
Moon,
|
||||
Pin,
|
||||
PinOff,
|
||||
Plus,
|
||||
Search,
|
||||
Settings,
|
||||
Sparkles,
|
||||
Sun,
|
||||
Terminal,
|
||||
} from 'lucide-react';
|
||||
|
||||
import type { AppearanceTheme } from '@shared/domain/tooling';
|
||||
import { isScratchpadProject } from '@shared/domain/project';
|
||||
import type { WorkspaceState } from '@shared/domain/workspace';
|
||||
import { shortcutKeys } from '@renderer/lib/keyboardShortcuts';
|
||||
|
||||
interface PaletteCommand {
|
||||
id: string;
|
||||
label: string;
|
||||
category: string;
|
||||
keywords?: string;
|
||||
shortcut?: string;
|
||||
icon: React.ReactNode;
|
||||
action: () => void;
|
||||
}
|
||||
|
||||
export interface CommandPaletteProps {
|
||||
workspace: WorkspaceState;
|
||||
onClose: () => void;
|
||||
onSelectSession: (sessionId: string) => void;
|
||||
onSelectProject: (projectId: string) => void;
|
||||
onNewSession: (projectId: string) => void;
|
||||
onCreateScratchpad: () => void;
|
||||
onOpenSettings: () => void;
|
||||
onOpenProjectSettings: (projectId: string) => void;
|
||||
onToggleTerminal: () => void;
|
||||
onSetTheme: (theme: AppearanceTheme) => void;
|
||||
onDuplicateSession: (sessionId: string) => void;
|
||||
onPinSession: (sessionId: string, isPinned: boolean) => void;
|
||||
onArchiveSession: (sessionId: string, isArchived: boolean) => void;
|
||||
onAddProject: () => void;
|
||||
onOpenAppDataFolder: () => void;
|
||||
onShowShortcuts: () => void;
|
||||
onShowSearch: () => void;
|
||||
}
|
||||
|
||||
/** Score how well `query` matches `text` (and optional `keywords`). 0 = no match. */
|
||||
function matchScore(query: string, text: string, keywords?: string): number {
|
||||
if (!query) return 1;
|
||||
const q = query.toLowerCase();
|
||||
const t = text.toLowerCase();
|
||||
|
||||
if (t.startsWith(q)) return 4;
|
||||
if (t.split(/\s+/).some((w) => w.startsWith(q))) return 3;
|
||||
if (t.includes(q)) return 2;
|
||||
if (keywords?.toLowerCase().includes(q)) return 1.5;
|
||||
|
||||
const tokens = q.split(/\s+/).filter(Boolean);
|
||||
if (tokens.length > 1) {
|
||||
const combined = `${t} ${keywords?.toLowerCase() ?? ''}`;
|
||||
if (tokens.every((tok) => combined.includes(tok))) return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
const ICON = 'size-4';
|
||||
|
||||
export function CommandPalette({
|
||||
workspace,
|
||||
onClose,
|
||||
onSelectSession,
|
||||
onSelectProject,
|
||||
onNewSession,
|
||||
onCreateScratchpad,
|
||||
onOpenSettings,
|
||||
onOpenProjectSettings,
|
||||
onToggleTerminal,
|
||||
onSetTheme,
|
||||
onDuplicateSession,
|
||||
onPinSession,
|
||||
onArchiveSession,
|
||||
onAddProject,
|
||||
onOpenAppDataFolder,
|
||||
onShowShortcuts,
|
||||
onShowSearch,
|
||||
}: CommandPaletteProps) {
|
||||
const [query, setQuery] = useState('');
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
inputRef.current?.focus();
|
||||
}, []);
|
||||
|
||||
// Intercept Escape in capture phase so it doesn't leak to other overlays
|
||||
useEffect(() => {
|
||||
const handleEscape = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
e.stopImmediatePropagation();
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', handleEscape, true);
|
||||
return () => document.removeEventListener('keydown', handleEscape, true);
|
||||
}, [onClose]);
|
||||
|
||||
const selectedSession = useMemo(() => {
|
||||
const id = workspace.selectedSessionId;
|
||||
return id ? workspace.sessions.find((s) => s.id === id) : undefined;
|
||||
}, [workspace.sessions, workspace.selectedSessionId]);
|
||||
|
||||
const selectedProject = useMemo(() => {
|
||||
const id = workspace.selectedProjectId;
|
||||
return id ? workspace.projects.find((p) => p.id === id) : undefined;
|
||||
}, [workspace.projects, workspace.selectedProjectId]);
|
||||
|
||||
const commands = useMemo<PaletteCommand[]>(() => {
|
||||
const cmds: PaletteCommand[] = [];
|
||||
|
||||
// ── Sessions ──
|
||||
const sessions = workspace.sessions
|
||||
.filter((s) => !s.isArchived)
|
||||
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
||||
|
||||
for (const s of sessions) {
|
||||
const project = workspace.projects.find((p) => p.id === s.projectId);
|
||||
const isCurrent = s.id === workspace.selectedSessionId;
|
||||
cmds.push({
|
||||
id: `session-${s.id}`,
|
||||
label: `${s.title}${isCurrent ? ' (current)' : ''}`,
|
||||
category: 'Sessions',
|
||||
keywords: `switch ${project?.name ?? ''} ${s.status}`,
|
||||
icon: <MessageSquare className={ICON} />,
|
||||
action: () => onSelectSession(s.id),
|
||||
});
|
||||
}
|
||||
|
||||
// ── Actions ──
|
||||
const defaultProjectId =
|
||||
workspace.selectedProjectId ??
|
||||
workspace.projects.find((p) => !isScratchpadProject(p))?.id;
|
||||
|
||||
if (defaultProjectId) {
|
||||
cmds.push({
|
||||
id: 'new-session',
|
||||
label: 'New Session',
|
||||
category: 'Actions',
|
||||
keywords: 'create start',
|
||||
shortcut: shortcutKeys('new-session'),
|
||||
icon: <Plus className={ICON} />,
|
||||
action: () => onNewSession(defaultProjectId),
|
||||
});
|
||||
}
|
||||
|
||||
cmds.push({
|
||||
id: 'new-scratchpad',
|
||||
label: 'Quick Scratchpad',
|
||||
category: 'Actions',
|
||||
keywords: 'create new scratch quick note',
|
||||
icon: <Sparkles className={ICON} />,
|
||||
action: onCreateScratchpad,
|
||||
});
|
||||
|
||||
// ── Current session ──
|
||||
if (selectedSession) {
|
||||
cmds.push({
|
||||
id: 'duplicate-session',
|
||||
label: 'Duplicate Session',
|
||||
category: 'Session',
|
||||
keywords: 'copy clone',
|
||||
icon: <Copy className={ICON} />,
|
||||
action: () => onDuplicateSession(selectedSession.id),
|
||||
});
|
||||
cmds.push({
|
||||
id: 'pin-session',
|
||||
label: selectedSession.isPinned ? 'Unpin Session' : 'Pin Session',
|
||||
category: 'Session',
|
||||
keywords: 'pin unpin sticky',
|
||||
icon: selectedSession.isPinned ? <PinOff className={ICON} /> : <Pin className={ICON} />,
|
||||
action: () => onPinSession(selectedSession.id, !selectedSession.isPinned),
|
||||
});
|
||||
cmds.push({
|
||||
id: 'archive-session',
|
||||
label: 'Archive Session',
|
||||
category: 'Session',
|
||||
keywords: 'archive hide remove close',
|
||||
shortcut: shortcutKeys('close-session'),
|
||||
icon: <Archive className={ICON} />,
|
||||
action: () => onArchiveSession(selectedSession.id, true),
|
||||
});
|
||||
}
|
||||
|
||||
// ── Projects ──
|
||||
const userProjects = workspace.projects.filter((p) => !isScratchpadProject(p));
|
||||
for (const p of userProjects) {
|
||||
const isCurrent = p.id === workspace.selectedProjectId;
|
||||
cmds.push({
|
||||
id: `project-${p.id}`,
|
||||
label: `${p.name}${isCurrent ? ' (current)' : ''}`,
|
||||
category: 'Projects',
|
||||
keywords: `switch folder ${p.path}`,
|
||||
icon: <FolderOpen className={ICON} />,
|
||||
action: () => onSelectProject(p.id),
|
||||
});
|
||||
}
|
||||
cmds.push({
|
||||
id: 'add-project',
|
||||
label: 'Add Project',
|
||||
category: 'Projects',
|
||||
keywords: 'folder new open browse',
|
||||
icon: <FolderPlus className={ICON} />,
|
||||
action: onAddProject,
|
||||
});
|
||||
|
||||
// ── General ──
|
||||
cmds.push({
|
||||
id: 'search-sessions',
|
||||
label: 'Search Sessions',
|
||||
category: 'General',
|
||||
keywords: 'find search messages content text',
|
||||
shortcut: shortcutKeys('search-sessions'),
|
||||
icon: <Search className={ICON} />,
|
||||
action: onShowSearch,
|
||||
});
|
||||
|
||||
cmds.push({
|
||||
id: 'settings',
|
||||
label: 'Open Settings',
|
||||
category: 'General',
|
||||
keywords: 'preferences config options',
|
||||
shortcut: shortcutKeys('settings'),
|
||||
icon: <Settings className={ICON} />,
|
||||
action: onOpenSettings,
|
||||
});
|
||||
|
||||
if (selectedProject && !isScratchpadProject(selectedProject)) {
|
||||
cmds.push({
|
||||
id: 'project-settings',
|
||||
label: `Project Settings — ${selectedProject.name}`,
|
||||
category: 'General',
|
||||
keywords: 'project config options customization',
|
||||
icon: <Settings className={ICON} />,
|
||||
action: () => onOpenProjectSettings(selectedProject.id),
|
||||
});
|
||||
}
|
||||
|
||||
cmds.push({
|
||||
id: 'toggle-terminal',
|
||||
label: 'Toggle Terminal',
|
||||
category: 'General',
|
||||
keywords: 'terminal console shell command',
|
||||
shortcut: shortcutKeys('toggle-terminal'),
|
||||
icon: <Terminal className={ICON} />,
|
||||
action: onToggleTerminal,
|
||||
});
|
||||
|
||||
cmds.push({
|
||||
id: 'app-data',
|
||||
label: 'Open App Data Folder',
|
||||
category: 'General',
|
||||
keywords: 'data storage files folder workspace',
|
||||
icon: <FolderOpen className={ICON} />,
|
||||
action: onOpenAppDataFolder,
|
||||
});
|
||||
|
||||
cmds.push({
|
||||
id: 'keyboard-shortcuts',
|
||||
label: 'Keyboard Shortcuts',
|
||||
category: 'General',
|
||||
keywords: 'keys keybindings hotkeys help cheatsheet',
|
||||
shortcut: shortcutKeys('shortcut-help'),
|
||||
icon: <Keyboard className={ICON} />,
|
||||
action: onShowShortcuts,
|
||||
});
|
||||
|
||||
// ── Theme ──
|
||||
cmds.push({
|
||||
id: 'theme-dark',
|
||||
label: 'Dark Theme',
|
||||
category: 'Theme',
|
||||
keywords: 'appearance dark mode night',
|
||||
icon: <Moon className={ICON} />,
|
||||
action: () => onSetTheme('dark'),
|
||||
});
|
||||
cmds.push({
|
||||
id: 'theme-light',
|
||||
label: 'Light Theme',
|
||||
category: 'Theme',
|
||||
keywords: 'appearance light mode day',
|
||||
icon: <Sun className={ICON} />,
|
||||
action: () => onSetTheme('light'),
|
||||
});
|
||||
cmds.push({
|
||||
id: 'theme-system',
|
||||
label: 'System Theme',
|
||||
category: 'Theme',
|
||||
keywords: 'appearance auto system follow',
|
||||
icon: <Monitor className={ICON} />,
|
||||
action: () => onSetTheme('system'),
|
||||
});
|
||||
|
||||
return cmds;
|
||||
}, [
|
||||
workspace, selectedSession, selectedProject,
|
||||
onSelectSession, onSelectProject, onNewSession, onCreateScratchpad,
|
||||
onOpenSettings, onOpenProjectSettings, onToggleTerminal, onSetTheme,
|
||||
onDuplicateSession, onPinSession, onArchiveSession, onAddProject,
|
||||
onOpenAppDataFolder, onShowShortcuts, onShowSearch,
|
||||
]);
|
||||
|
||||
const filteredCommands = useMemo(() => {
|
||||
if (!query.trim()) return commands;
|
||||
return commands
|
||||
.map((cmd) => ({ cmd, score: matchScore(query, cmd.label, cmd.keywords) }))
|
||||
.filter(({ score }) => score > 0)
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.map(({ cmd }) => cmd);
|
||||
}, [commands, query]);
|
||||
|
||||
const groupedCommands = useMemo(() => {
|
||||
const groups: { category: string; commands: PaletteCommand[] }[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const cmd of filteredCommands) {
|
||||
if (!seen.has(cmd.category)) {
|
||||
seen.add(cmd.category);
|
||||
groups.push({ category: cmd.category, commands: [] });
|
||||
}
|
||||
groups.find((g) => g.category === cmd.category)!.commands.push(cmd);
|
||||
}
|
||||
return groups;
|
||||
}, [filteredCommands]);
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedIndex(0);
|
||||
}, [query]);
|
||||
|
||||
const executeCommand = useCallback(
|
||||
(cmd: PaletteCommand) => {
|
||||
onClose();
|
||||
cmd.action();
|
||||
},
|
||||
[onClose],
|
||||
);
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(e: React.KeyboardEvent) => {
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
if (filteredCommands.length > 0) {
|
||||
setSelectedIndex((i) => Math.min(i + 1, filteredCommands.length - 1));
|
||||
}
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
setSelectedIndex((i) => Math.max(i - 1, 0));
|
||||
} else if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
const cmd = filteredCommands[selectedIndex];
|
||||
if (cmd) executeCommand(cmd);
|
||||
}
|
||||
},
|
||||
[filteredCommands, selectedIndex, executeCommand],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const item = listRef.current?.querySelector(`[data-palette-index="${selectedIndex}"]`);
|
||||
item?.scrollIntoView({ block: 'nearest' });
|
||||
}, [selectedIndex]);
|
||||
|
||||
let flatIndex = 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="palette-backdrop-enter fixed inset-0 z-[60] flex justify-center bg-[#07080e]/80 pt-[18vh] backdrop-blur-sm"
|
||||
onClick={onClose}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Command palette"
|
||||
>
|
||||
<div
|
||||
className="palette-enter glow-border flex h-fit max-h-[min(420px,60vh)] w-full max-w-xl flex-col overflow-hidden rounded-xl bg-[var(--color-surface-1)] shadow-[0_16px_64px_rgba(0,0,0,0.5)]"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onKeyDown={handleKeyDown}
|
||||
>
|
||||
{/* Search input */}
|
||||
<div className="flex items-center gap-3 border-b border-[var(--color-border)] px-4">
|
||||
<Search className="size-4 shrink-0 text-[var(--color-text-muted)]" />
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
className="flex-1 bg-transparent py-3.5 text-[14px] text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-muted)]"
|
||||
placeholder="Type a command…"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
aria-label="Search commands"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
/>
|
||||
{query && (
|
||||
<button
|
||||
className="shrink-0 rounded px-1.5 py-0.5 text-[11px] text-[var(--color-text-muted)] transition hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]"
|
||||
onClick={() => setQuery('')}
|
||||
type="button"
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Results */}
|
||||
<div ref={listRef} className="flex-1 overflow-y-auto py-1.5" role="listbox">
|
||||
{groupedCommands.length === 0 ? (
|
||||
<div className="px-4 py-8 text-center text-[13px] text-[var(--color-text-muted)]">
|
||||
No matching commands
|
||||
</div>
|
||||
) : (
|
||||
groupedCommands.map((group) => (
|
||||
<div key={group.category}>
|
||||
<div className="px-4 pb-1 pt-2.5 text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-muted)]">
|
||||
{group.category}
|
||||
</div>
|
||||
{group.commands.map((cmd) => {
|
||||
const index = flatIndex++;
|
||||
const isSelected = index === selectedIndex;
|
||||
return (
|
||||
<button
|
||||
key={cmd.id}
|
||||
data-palette-index={index}
|
||||
className={`flex w-full items-center gap-3 px-4 py-2 text-left text-[13px] transition-colors ${
|
||||
isSelected
|
||||
? 'bg-[var(--color-accent-muted)] text-[var(--color-text-primary)]'
|
||||
: 'text-[var(--color-text-secondary)] hover:bg-[var(--color-glass-hover)] hover:text-[var(--color-text-primary)]'
|
||||
}`}
|
||||
onClick={() => executeCommand(cmd)}
|
||||
onMouseEnter={() => setSelectedIndex(index)}
|
||||
role="option"
|
||||
aria-selected={isSelected}
|
||||
type="button"
|
||||
>
|
||||
<span
|
||||
className={
|
||||
isSelected
|
||||
? 'text-[var(--color-text-accent)]'
|
||||
: 'text-[var(--color-text-muted)]'
|
||||
}
|
||||
>
|
||||
{cmd.icon}
|
||||
</span>
|
||||
<span className="flex-1 truncate">{cmd.label}</span>
|
||||
{cmd.shortcut && (
|
||||
<kbd className="rounded border border-[var(--color-border)] bg-[var(--color-surface-0)] px-1.5 py-0.5 font-mono text-[10px] text-[var(--color-text-muted)]">
|
||||
{cmd.shortcut}
|
||||
</kbd>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Footer hints */}
|
||||
<div className="flex items-center gap-4 border-t border-[var(--color-border)] px-4 py-2 text-[11px] text-[var(--color-text-muted)]">
|
||||
<span className="flex items-center gap-1">
|
||||
<kbd className="rounded border border-[var(--color-border-subtle)] px-1 font-mono text-[10px]">
|
||||
↑↓
|
||||
</kbd>
|
||||
navigate
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<kbd className="rounded border border-[var(--color-border-subtle)] px-1 font-mono text-[10px]">
|
||||
↵
|
||||
</kbd>
|
||||
select
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<kbd className="rounded border border-[var(--color-border-subtle)] px-1 font-mono text-[10px]">
|
||||
esc
|
||||
</kbd>
|
||||
close
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import {
|
||||
CheckCircle2,
|
||||
XCircle,
|
||||
@@ -12,12 +12,15 @@ import {
|
||||
ArrowUpCircle,
|
||||
User,
|
||||
Building2,
|
||||
BarChart3,
|
||||
Loader2,
|
||||
} from 'lucide-react';
|
||||
|
||||
import type {
|
||||
SidecarConnectionDiagnostics,
|
||||
SidecarConnectionStatus,
|
||||
SidecarCopilotCliVersionStatus,
|
||||
QuotaSnapshot,
|
||||
} from '@shared/contracts/sidecar';
|
||||
|
||||
interface CopilotStatusCardProps {
|
||||
@@ -25,6 +28,7 @@ interface CopilotStatusCardProps {
|
||||
modelCount: number;
|
||||
isRefreshing: boolean;
|
||||
onRefresh: () => void;
|
||||
onGetQuota?: () => Promise<Record<string, QuotaSnapshot>>;
|
||||
}
|
||||
|
||||
interface StatusConfig {
|
||||
@@ -40,35 +44,35 @@ function getStatusConfig(status: SidecarConnectionStatus): StatusConfig {
|
||||
switch (status) {
|
||||
case 'ready':
|
||||
return {
|
||||
icon: <CheckCircle2 className="size-4 text-emerald-400" />,
|
||||
icon: <CheckCircle2 className="size-4 text-[var(--color-status-success)]" />,
|
||||
label: 'Connected to GitHub Copilot',
|
||||
accentClasses: 'text-emerald-400',
|
||||
dotClasses: 'bg-emerald-400',
|
||||
accentClasses: 'text-[var(--color-status-success)]',
|
||||
dotClasses: 'bg-[var(--color-status-success)]',
|
||||
};
|
||||
case 'copilot-cli-missing':
|
||||
return {
|
||||
icon: <Download className="size-4 text-amber-400" />,
|
||||
icon: <Download className="size-4 text-[var(--color-status-warning)]" />,
|
||||
label: 'Copilot CLI not found',
|
||||
accentClasses: 'text-amber-400',
|
||||
dotClasses: 'bg-amber-400',
|
||||
accentClasses: 'text-[var(--color-status-warning)]',
|
||||
dotClasses: 'bg-[var(--color-status-warning)]',
|
||||
actionIcon: <Terminal className="size-3" />,
|
||||
actionLabel: 'Install the copilot CLI and ensure it is on your PATH',
|
||||
};
|
||||
case 'copilot-auth-required':
|
||||
return {
|
||||
icon: <LogIn className="size-4 text-blue-400" />,
|
||||
icon: <LogIn className="size-4 text-[var(--color-status-info)]" />,
|
||||
label: 'Sign-in required',
|
||||
accentClasses: 'text-blue-400',
|
||||
dotClasses: 'bg-blue-400',
|
||||
accentClasses: 'text-[var(--color-status-info)]',
|
||||
dotClasses: 'bg-[var(--color-status-info)]',
|
||||
actionIcon: <Terminal className="size-3" />,
|
||||
actionLabel: 'Run copilot auth login in your terminal, then refresh',
|
||||
};
|
||||
case 'copilot-error':
|
||||
return {
|
||||
icon: <XCircle className="size-4 text-red-400" />,
|
||||
icon: <XCircle className="size-4 text-[var(--color-status-error)]" />,
|
||||
label: 'Connection error',
|
||||
accentClasses: 'text-red-400',
|
||||
dotClasses: 'bg-red-400',
|
||||
accentClasses: 'text-[var(--color-status-error)]',
|
||||
dotClasses: 'bg-[var(--color-status-error)]',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -104,27 +108,158 @@ function VersionBadge({ status, installedVersion }: { status: SidecarCopilotCliV
|
||||
switch (status) {
|
||||
case 'latest':
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2 py-0.5 text-[10px] font-medium text-emerald-400">
|
||||
<span className="inline-flex items-center gap-1 rounded-full bg-[var(--color-status-success)]/10 px-2 py-0.5 text-[10px] font-medium text-[var(--color-status-success)]">
|
||||
<CheckCircle2 className="size-2.5" />
|
||||
{versionLabel ?? 'Up to date'}
|
||||
</span>
|
||||
);
|
||||
case 'outdated':
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 rounded-full bg-amber-500/10 px-2 py-0.5 text-[10px] font-medium text-amber-400">
|
||||
<span className="inline-flex items-center gap-1 rounded-full bg-[var(--color-status-warning)]/10 px-2 py-0.5 text-[10px] font-medium text-[var(--color-status-warning)]">
|
||||
<ArrowUpCircle className="size-2.5" />
|
||||
Update available
|
||||
</span>
|
||||
);
|
||||
case 'unknown':
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 rounded-full bg-zinc-800 px-2 py-0.5 text-[10px] font-medium text-zinc-500">
|
||||
<span className="inline-flex items-center gap-1 rounded-full bg-[var(--color-surface-3)] px-2 py-0.5 text-[10px] font-medium text-[var(--color-text-muted)]">
|
||||
{versionLabel ?? 'Version unknown'}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const quotaTypeLabels: Record<string, string> = {
|
||||
premium_interactions: 'Premium Requests',
|
||||
chat: 'Chat',
|
||||
completions: 'Completions',
|
||||
};
|
||||
|
||||
function formatQuotaTypeLabel(key: string): string {
|
||||
return quotaTypeLabels[key] ?? key.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
|
||||
}
|
||||
|
||||
function formatResetDate(iso: string): string {
|
||||
try {
|
||||
const date = new Date(iso);
|
||||
const now = new Date();
|
||||
const diffMs = date.getTime() - now.getTime();
|
||||
const diffDays = Math.ceil(diffMs / 86_400_000);
|
||||
|
||||
if (diffDays <= 0) return 'Today';
|
||||
if (diffDays === 1) return 'Tomorrow';
|
||||
if (diffDays <= 30) return `In ${diffDays} day${diffDays === 1 ? '' : 's'}`;
|
||||
|
||||
return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
|
||||
} catch {
|
||||
return iso;
|
||||
}
|
||||
}
|
||||
|
||||
function QuotaSection({
|
||||
onGetQuota,
|
||||
}: {
|
||||
onGetQuota: () => Promise<Record<string, QuotaSnapshot>>;
|
||||
}) {
|
||||
const [quotaData, setQuotaData] = useState<Record<string, QuotaSnapshot>>();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
setError(undefined);
|
||||
|
||||
void onGetQuota()
|
||||
.then((data) => { if (!cancelled) setQuotaData(data); })
|
||||
.catch((err: unknown) => {
|
||||
if (!cancelled) setError(err instanceof Error ? err.message : String(err));
|
||||
})
|
||||
.finally(() => { if (!cancelled) setLoading(false); });
|
||||
|
||||
return () => { cancelled = true; };
|
||||
}, [onGetQuota]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 py-2">
|
||||
<Loader2 className="size-3.5 animate-spin text-[var(--color-text-muted)]" />
|
||||
<span className="text-[12px] text-[var(--color-text-muted)]">Loading quota…</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 py-2">
|
||||
<XCircle className="size-3.5 text-[var(--color-status-error)]" />
|
||||
<span className="text-[12px] text-[var(--color-text-muted)]">Could not load quota</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!quotaData || Object.keys(quotaData).length === 0) {
|
||||
return (
|
||||
<div className="py-2">
|
||||
<span className="text-[12px] text-[var(--color-text-muted)]">No quota data available</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{Object.entries(quotaData).map(([key, snapshot]) => {
|
||||
const usedPct = snapshot.entitlementRequests > 0
|
||||
? (snapshot.usedRequests / snapshot.entitlementRequests) * 100
|
||||
: 0;
|
||||
const barColor = usedPct > 90
|
||||
? 'bg-[var(--color-status-error)]'
|
||||
: usedPct > 70
|
||||
? 'bg-[var(--color-status-warning)]'
|
||||
: 'bg-[var(--color-accent)]/60';
|
||||
|
||||
return (
|
||||
<div key={key} className="space-y-1.5">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-[12px] font-medium text-[var(--color-text-secondary)]">
|
||||
{formatQuotaTypeLabel(key)}
|
||||
</span>
|
||||
<span className="text-[11px] tabular-nums text-[var(--color-text-muted)]">
|
||||
{Math.round(snapshot.remainingPercentage)}% remaining
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-1.5 overflow-hidden rounded-full bg-[var(--color-surface-3)]">
|
||||
<div
|
||||
className={`h-full rounded-full transition-all ${barColor}`}
|
||||
style={{ width: `${Math.min(100, usedPct)}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5 text-[10px] text-[var(--color-text-muted)]">
|
||||
<span className="tabular-nums">
|
||||
{Math.round(snapshot.usedRequests)} of {Math.round(snapshot.entitlementRequests)} used
|
||||
</span>
|
||||
{snapshot.overage > 0 && (
|
||||
<>
|
||||
<span className="text-[var(--color-text-muted)]">·</span>
|
||||
<span className="tabular-nums text-[var(--color-status-warning)]">
|
||||
{Math.round(snapshot.overage)} overage
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
{snapshot.resetDate && (
|
||||
<>
|
||||
<span className="text-[var(--color-text-muted)]">·</span>
|
||||
<span>Resets {formatResetDate(snapshot.resetDate)}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AccountSection({ connection }: { connection: SidecarConnectionDiagnostics }) {
|
||||
const { account } = connection;
|
||||
if (!account) return null;
|
||||
@@ -141,34 +276,34 @@ function AccountSection({ connection }: { connection: SidecarConnectionDiagnosti
|
||||
<div className="space-y-2.5">
|
||||
{/* Identity row */}
|
||||
<div className="flex items-center gap-2">
|
||||
<User className="size-3.5 text-zinc-500" />
|
||||
<User className="size-3.5 text-[var(--color-text-muted)]" />
|
||||
{hasLogin ? (
|
||||
<div className="flex items-center gap-1.5 text-[12px]">
|
||||
<span className="font-medium text-zinc-200">{account.login}</span>
|
||||
<span className="font-medium text-[var(--color-text-primary)]">{account.login}</span>
|
||||
{account.host && (
|
||||
<span className="text-zinc-500">· {account.host}</span>
|
||||
<span className="text-[var(--color-text-muted)]">· {account.host}</span>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-[12px] text-zinc-500">{account.statusMessage}</span>
|
||||
<span className="text-[12px] text-[var(--color-text-muted)]">{account.statusMessage}</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Organizations */}
|
||||
{hasOrgs && (
|
||||
<div className="flex items-start gap-2">
|
||||
<Building2 className="mt-0.5 size-3.5 shrink-0 text-zinc-500" />
|
||||
<Building2 className="mt-0.5 size-3.5 shrink-0 text-[var(--color-text-muted)]" />
|
||||
<div className="flex flex-wrap items-center gap-1">
|
||||
{visibleOrgs.map((org) => (
|
||||
<span
|
||||
className="rounded-md bg-zinc-800 px-1.5 py-0.5 text-[10px] font-medium text-zinc-400"
|
||||
className="rounded-md bg-[var(--color-surface-3)] px-1.5 py-0.5 text-[10px] font-medium text-[var(--color-text-secondary)]"
|
||||
key={org}
|
||||
>
|
||||
{org}
|
||||
</span>
|
||||
))}
|
||||
{remainingOrgs > 0 && (
|
||||
<span className="text-[10px] text-zinc-600">+{remainingOrgs} more</span>
|
||||
<span className="text-[10px] text-[var(--color-text-muted)]">+{remainingOrgs} more</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -182,15 +317,16 @@ export function CopilotStatusCard({
|
||||
modelCount,
|
||||
isRefreshing,
|
||||
onRefresh,
|
||||
onGetQuota,
|
||||
}: CopilotStatusCardProps) {
|
||||
const [showDetails, setShowDetails] = useState(false);
|
||||
|
||||
if (!connection) {
|
||||
return (
|
||||
<div className="flex items-center gap-3 rounded-xl border border-[var(--color-border)] bg-zinc-900/40 px-4 py-3">
|
||||
<Cpu className="size-4 text-zinc-600" />
|
||||
<span className="text-[13px] text-zinc-500">Checking connection…</span>
|
||||
<RefreshCw className="ml-auto size-3.5 animate-spin text-zinc-600" />
|
||||
<div className="flex items-center gap-3 rounded-xl border border-[var(--color-border)] bg-[var(--color-glass)] px-4 py-3">
|
||||
<Cpu className="size-4 text-[var(--color-text-muted)]" />
|
||||
<span className="text-[13px] text-[var(--color-text-muted)]">Checking connection…</span>
|
||||
<RefreshCw className="ml-auto size-3.5 animate-spin text-[var(--color-text-muted)]" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -211,7 +347,7 @@ export function CopilotStatusCard({
|
||||
{config.label}
|
||||
</span>
|
||||
{isHealthy && (
|
||||
<span className="text-[12px] text-zinc-500">
|
||||
<span className="text-[12px] text-[var(--color-text-muted)]">
|
||||
· {modelCount} model{modelCount === 1 ? '' : 's'} available
|
||||
</span>
|
||||
)}
|
||||
@@ -223,10 +359,10 @@ export function CopilotStatusCard({
|
||||
/>
|
||||
)}
|
||||
{checkedLabel && (
|
||||
<span className="text-[11px] text-zinc-600">{checkedLabel}</span>
|
||||
<span className="text-[11px] text-[var(--color-text-muted)]">{checkedLabel}</span>
|
||||
)}
|
||||
<button
|
||||
className="flex size-6 items-center justify-center rounded-md text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300 disabled:opacity-50"
|
||||
className="flex size-6 items-center justify-center rounded-md text-[var(--color-text-muted)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)] disabled:opacity-50"
|
||||
disabled={isRefreshing}
|
||||
onClick={onRefresh}
|
||||
title="Refresh connection status"
|
||||
@@ -242,11 +378,24 @@ export function CopilotStatusCard({
|
||||
<AccountSection connection={connection} />
|
||||
)}
|
||||
|
||||
{/* Usage & Quota (when healthy and callback provided) */}
|
||||
{isHealthy && onGetQuota && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-1.5 text-[11px] font-medium text-[var(--color-text-secondary)]">
|
||||
<BarChart3 className="size-3" />
|
||||
<span>Usage & Quota</span>
|
||||
</div>
|
||||
<div className="rounded-lg border border-[var(--color-border-subtle)] bg-[var(--color-glass)] px-3 py-2.5">
|
||||
<QuotaSection onGetQuota={onGetQuota} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Action hint for non-ready states */}
|
||||
{!isHealthy && config.actionLabel && (
|
||||
<div className="flex items-start gap-2 rounded-lg border border-zinc-800 bg-zinc-900/60 px-3 py-2.5">
|
||||
<div className="flex items-start gap-2 rounded-lg border border-[var(--color-border)] bg-[var(--color-glass)] px-3 py-2.5">
|
||||
<div className="mt-0.5 shrink-0">{config.actionIcon}</div>
|
||||
<p className="text-[12px] leading-relaxed text-zinc-400">{config.actionLabel}</p>
|
||||
<p className="text-[12px] leading-relaxed text-[var(--color-text-secondary)]">{config.actionLabel}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -254,7 +403,7 @@ export function CopilotStatusCard({
|
||||
{isHealthy && hasDetail && (
|
||||
<div className="space-y-2">
|
||||
<button
|
||||
className="flex w-full items-center gap-1.5 text-[11px] text-zinc-600 transition hover:text-zinc-400"
|
||||
className="flex w-full items-center gap-1.5 text-[11px] text-[var(--color-text-muted)] transition-all duration-200 hover:text-[var(--color-text-secondary)]"
|
||||
onClick={() => setShowDetails((prev) => !prev)}
|
||||
type="button"
|
||||
>
|
||||
@@ -263,26 +412,26 @@ export function CopilotStatusCard({
|
||||
</button>
|
||||
|
||||
{showDetails && (
|
||||
<div className="overflow-hidden rounded-lg border border-zinc-800/60 bg-zinc-900/40">
|
||||
<div className="overflow-hidden rounded-lg border border-[var(--color-border-subtle)] bg-[var(--color-glass)]">
|
||||
{connection.copilotCliPath && (
|
||||
<div className="border-b border-zinc-800/40 px-3 py-2">
|
||||
<span className="text-[10px] font-medium uppercase tracking-wider text-zinc-600">CLI path</span>
|
||||
<p className="mt-0.5 break-all font-mono text-[11px] text-zinc-400" title={connection.copilotCliPath}>
|
||||
<div className="border-b border-[var(--color-border-subtle)] px-3 py-2">
|
||||
<span className="text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-muted)]">CLI path</span>
|
||||
<p className="mt-0.5 break-all font-mono text-[11px] text-[var(--color-text-secondary)]" title={connection.copilotCliPath}>
|
||||
{connection.copilotCliPath}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{hasVersionInfo && connection.copilotCliVersion!.status === 'outdated' && connection.copilotCliVersion!.latestVersion && (
|
||||
<div className="border-b border-zinc-800/40 px-3 py-2">
|
||||
<span className="text-[10px] font-medium uppercase tracking-wider text-zinc-600">Latest version</span>
|
||||
<p className="mt-0.5 font-mono text-[11px] text-zinc-400">
|
||||
<div className="border-b border-[var(--color-border-subtle)] px-3 py-2">
|
||||
<span className="text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-muted)]">Latest version</span>
|
||||
<p className="mt-0.5 font-mono text-[11px] text-[var(--color-text-secondary)]">
|
||||
{connection.copilotCliVersion!.latestVersion}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<div className="px-3 py-2">
|
||||
<span className="text-[10px] font-medium uppercase tracking-wider text-zinc-600">Last checked</span>
|
||||
<p className="mt-0.5 text-[11px] text-zinc-400">
|
||||
<span className="text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-muted)]">Last checked</span>
|
||||
<p className="mt-0.5 text-[11px] text-[var(--color-text-secondary)]">
|
||||
{new Date(connection.checkedAt).toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
@@ -293,17 +442,17 @@ export function CopilotStatusCard({
|
||||
|
||||
{/* Error detail for non-ready states */}
|
||||
{!isHealthy && hasDetail && (
|
||||
<div className="overflow-hidden rounded-lg border border-zinc-800/60 bg-zinc-900/40">
|
||||
<div className="border-b border-zinc-800/40 px-3 py-2">
|
||||
<span className="text-[10px] font-medium uppercase tracking-wider text-zinc-600">CLI path</span>
|
||||
<p className="mt-0.5 break-all font-mono text-[11px] text-zinc-400" title={connection.copilotCliPath}>
|
||||
<div className="overflow-hidden rounded-lg border border-[var(--color-border-subtle)] bg-[var(--color-glass)]">
|
||||
<div className="border-b border-[var(--color-border-subtle)] px-3 py-2">
|
||||
<span className="text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-muted)]">CLI path</span>
|
||||
<p className="mt-0.5 break-all font-mono text-[11px] text-[var(--color-text-secondary)]" title={connection.copilotCliPath}>
|
||||
{shortenPath(connection.copilotCliPath!)}
|
||||
</p>
|
||||
</div>
|
||||
{connection.detail && (
|
||||
<div className="px-3 py-2">
|
||||
<span className="text-[10px] font-medium uppercase tracking-wider text-zinc-600">Error detail</span>
|
||||
<p className="mt-0.5 break-words text-[11px] text-zinc-400">{connection.detail}</p>
|
||||
<span className="text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-muted)]">Error detail</span>
|
||||
<p className="mt-0.5 break-words text-[11px] text-[var(--color-text-secondary)]">{connection.detail}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -81,20 +81,20 @@ export function DiscoveredToolingModal({
|
||||
<div
|
||||
aria-labelledby="discovered-tooling-title"
|
||||
aria-modal="true"
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm"
|
||||
className="overlay-backdrop-enter fixed inset-0 z-50 flex items-center justify-center bg-[#07080e]/90 backdrop-blur-sm"
|
||||
role="dialog"
|
||||
>
|
||||
<div className="flex max-h-[80vh] w-full max-w-lg flex-col rounded-xl border border-zinc-800 bg-zinc-900 shadow-2xl">
|
||||
<div className="overlay-panel-enter flex max-h-[80vh] w-full max-w-lg flex-col rounded-xl border border-[var(--color-border)] bg-[var(--color-surface-1)] shadow-[0_16px_64px_rgba(0,0,0,0.5)]">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between border-b border-zinc-800 px-5 py-4">
|
||||
<div className="flex items-center justify-between border-b border-[var(--color-border)] px-5 py-4">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<FileSearch className="size-4 text-indigo-400" />
|
||||
<h2 id="discovered-tooling-title" className="text-[13px] font-semibold text-zinc-100">
|
||||
<FileSearch className="size-4 text-[var(--color-text-accent)]" />
|
||||
<h2 id="discovered-tooling-title" className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">
|
||||
MCP servers found in config files
|
||||
</h2>
|
||||
</div>
|
||||
<button
|
||||
className="flex size-7 items-center justify-center rounded-lg text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300"
|
||||
className="flex size-7 items-center justify-center rounded-lg text-[var(--color-text-muted)] transition hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]"
|
||||
onClick={onClose}
|
||||
type="button"
|
||||
>
|
||||
@@ -104,7 +104,7 @@ export function DiscoveredToolingModal({
|
||||
|
||||
{/* Body */}
|
||||
<div className="flex-1 overflow-y-auto px-5 py-4">
|
||||
<p className="mb-4 text-[12px] leading-relaxed text-zinc-500">
|
||||
<p className="mb-4 text-[12px] leading-relaxed text-[var(--color-text-muted)]">
|
||||
The following MCP servers were found in your config files. Accept the ones you want to
|
||||
use, or dismiss those you don't need. Accepted servers become available for session tooling.
|
||||
</p>
|
||||
@@ -127,20 +127,20 @@ export function DiscoveredToolingModal({
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="flex items-center justify-between border-t border-zinc-800 px-5 py-3">
|
||||
<span className="text-[12px] text-zinc-600">
|
||||
<div className="flex items-center justify-between border-t border-[var(--color-border)] px-5 py-3">
|
||||
<span className="text-[12px] text-[var(--color-text-muted)]">
|
||||
{totalPending} server{totalPending === 1 ? '' : 's'} pending review
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
className="rounded-lg px-3 py-1.5 text-[13px] text-zinc-400 transition hover:bg-zinc-800 hover:text-zinc-200"
|
||||
className="rounded-lg px-3 py-1.5 text-[13px] text-[var(--color-text-secondary)] transition hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]"
|
||||
onClick={handleDismissAll}
|
||||
type="button"
|
||||
>
|
||||
Dismiss All
|
||||
</button>
|
||||
<button
|
||||
className="rounded-lg bg-indigo-600 px-3 py-1.5 text-[13px] font-medium text-white transition hover:bg-indigo-500"
|
||||
className="rounded-lg bg-[var(--color-accent)] px-3 py-1.5 text-[13px] font-medium text-white transition hover:bg-[var(--color-accent-sky)]"
|
||||
onClick={handleAcceptAll}
|
||||
type="button"
|
||||
>
|
||||
@@ -166,15 +166,15 @@ function DiscoveredGroup({
|
||||
}) {
|
||||
return (
|
||||
<div className="mb-4">
|
||||
<div className="mb-2 text-[10px] font-semibold uppercase tracking-wider text-zinc-600">
|
||||
<div className="mb-2 text-[10px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
|
||||
{scopeLabel}
|
||||
</div>
|
||||
{groups.map((group) => (
|
||||
<div className="mb-3" key={group.sourceLabel}>
|
||||
<div className="mb-1.5 flex items-center gap-1.5 text-[11px] text-zinc-500">
|
||||
<div className="mb-1.5 flex items-center gap-1.5 text-[11px] text-[var(--color-text-muted)]">
|
||||
<span className="truncate font-medium">{group.sourceLabel}</span>
|
||||
<span className="text-zinc-700">·</span>
|
||||
<span className="text-zinc-600">
|
||||
<span className="text-[var(--color-text-muted)]">·</span>
|
||||
<span className="text-[var(--color-text-muted)]">
|
||||
{group.servers.length} server{group.servers.length === 1 ? '' : 's'}
|
||||
</span>
|
||||
</div>
|
||||
@@ -211,22 +211,22 @@ function ServerRow({
|
||||
: server.url || 'No URL';
|
||||
|
||||
return (
|
||||
<div className="group flex items-center gap-3 rounded-lg border border-zinc-800/60 bg-zinc-800/20 px-3 py-2.5">
|
||||
<Server className="size-3.5 shrink-0 text-zinc-600" />
|
||||
<div className="group flex items-center gap-3 rounded-lg border border-[var(--color-border-subtle)] bg-[var(--color-glass)] px-3 py-2.5">
|
||||
<Server className="size-3.5 shrink-0 text-[var(--color-text-muted)]" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="truncate text-[13px] font-medium text-zinc-200">
|
||||
<span className="truncate text-[13px] font-medium text-[var(--color-text-primary)]">
|
||||
{server.name}
|
||||
</span>
|
||||
<span className="rounded-full bg-zinc-800 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-zinc-500">
|
||||
<span className="rounded-full bg-[var(--color-surface-3)] px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-[var(--color-text-muted)]">
|
||||
{server.transport}
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-0.5 truncate text-[12px] text-zinc-500">{detail}</p>
|
||||
<p className="mt-0.5 truncate text-[12px] text-[var(--color-text-muted)]">{detail}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
className="flex size-7 items-center justify-center rounded-md text-zinc-600 transition hover:bg-red-500/10 hover:text-red-400"
|
||||
className="flex size-7 items-center justify-center rounded-md text-[var(--color-text-muted)] transition hover:bg-[var(--color-status-error)]/10 hover:text-[var(--color-status-error)]"
|
||||
onClick={onDismiss}
|
||||
title="Dismiss"
|
||||
type="button"
|
||||
@@ -234,7 +234,7 @@ function ServerRow({
|
||||
<XCircle className="size-3.5" />
|
||||
</button>
|
||||
<button
|
||||
className="flex size-7 items-center justify-center rounded-md text-zinc-600 transition hover:bg-emerald-500/10 hover:text-emerald-400"
|
||||
className="flex size-7 items-center justify-center rounded-md text-[var(--color-text-muted)] transition hover:bg-[var(--color-status-success)]/10 hover:text-[var(--color-status-success)]"
|
||||
onClick={onAccept}
|
||||
title="Accept"
|
||||
type="button"
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import { useEffect } from 'react';
|
||||
import { Keyboard } from 'lucide-react';
|
||||
|
||||
import { shortcuts, type ShortcutDefinition } from '@renderer/lib/keyboardShortcuts';
|
||||
|
||||
interface KeyboardShortcutsPanelProps {
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const categoryOrder = ['Navigation', 'Sessions', 'Workspace', 'General'] as const;
|
||||
|
||||
function groupByCategory(defs: ShortcutDefinition[]): Map<string, ShortcutDefinition[]> {
|
||||
const groups = new Map<string, ShortcutDefinition[]>();
|
||||
for (const def of defs) {
|
||||
const list = groups.get(def.category) ?? [];
|
||||
list.push(def);
|
||||
groups.set(def.category, list);
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
export function KeyboardShortcutsPanel({ onClose }: KeyboardShortcutsPanelProps) {
|
||||
// Escape to close — capture phase so it doesn't propagate
|
||||
useEffect(() => {
|
||||
const handleEscape = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
e.stopImmediatePropagation();
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', handleEscape, true);
|
||||
return () => document.removeEventListener('keydown', handleEscape, true);
|
||||
}, [onClose]);
|
||||
|
||||
const grouped = groupByCategory(shortcuts);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="palette-backdrop-enter fixed inset-0 z-[70] flex items-center justify-center bg-[#07080e]/80 backdrop-blur-sm"
|
||||
onClick={onClose}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="shortcuts-title"
|
||||
>
|
||||
<div
|
||||
className="palette-enter w-full max-w-lg overflow-hidden rounded-xl border border-[var(--color-border)] bg-[var(--color-surface-1)] shadow-[0_24px_80px_rgba(0,0,0,0.55)]"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-3 border-b border-[var(--color-border)] px-5 py-3.5">
|
||||
<Keyboard className="size-4 text-[var(--color-text-accent)]" />
|
||||
<h2
|
||||
id="shortcuts-title"
|
||||
className="font-display text-[14px] font-semibold text-[var(--color-text-primary)]"
|
||||
>
|
||||
Keyboard Shortcuts
|
||||
</h2>
|
||||
<span className="ml-auto text-[11px] text-[var(--color-text-muted)]">
|
||||
Press <Kbd>Esc</Kbd> to close
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Body — two-column grid of categories */}
|
||||
<div className="grid grid-cols-2 gap-x-6 gap-y-5 px-5 py-4">
|
||||
{categoryOrder.map((cat) => {
|
||||
const items = grouped.get(cat);
|
||||
if (!items?.length) return null;
|
||||
return (
|
||||
<div key={cat}>
|
||||
<h3 className="mb-2 text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-muted)]">
|
||||
{cat}
|
||||
</h3>
|
||||
<ul className="space-y-1.5">
|
||||
{items.map((item) => (
|
||||
<li
|
||||
key={item.id}
|
||||
className="flex items-center justify-between gap-3 text-[12.5px]"
|
||||
>
|
||||
<span className="truncate text-[var(--color-text-secondary)]">
|
||||
{item.label}
|
||||
</span>
|
||||
<ShortcutBadge keys={item.keys} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="border-t border-[var(--color-border)] px-5 py-2.5 text-[11px] text-[var(--color-text-muted)]">
|
||||
Tip: Use the command palette for even more actions
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Inline keyboard key cap. */
|
||||
function Kbd({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<kbd className="rounded border border-[var(--color-border)] bg-[var(--color-surface-0)] px-1.5 py-0.5 font-mono text-[10px] text-[var(--color-text-muted)]">
|
||||
{children}
|
||||
</kbd>
|
||||
);
|
||||
}
|
||||
|
||||
/** Renders a compound shortcut like "Ctrl+Shift+Tab" as joined key caps. */
|
||||
function ShortcutBadge({ keys }: { keys: string }) {
|
||||
const parts = keys.split('+');
|
||||
return (
|
||||
<span className="flex shrink-0 items-center gap-0.5">
|
||||
{parts.map((part, i) => (
|
||||
<Kbd key={i}>{part}</Kbd>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -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}
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -18,6 +18,8 @@ import {
|
||||
import type { ApprovalCheckpointKind, ApprovalPolicy } from '@shared/domain/approval';
|
||||
import type { ModelDefinition } from '@shared/domain/models';
|
||||
import {
|
||||
addAgentToGraph,
|
||||
removeAgentFromGraph,
|
||||
resolvePatternGraph,
|
||||
syncPatternGraph,
|
||||
validatePatternDefinition,
|
||||
@@ -35,7 +37,6 @@ import {
|
||||
} from '@shared/domain/tooling';
|
||||
|
||||
import { ToggleSwitch } from '@renderer/components/ui';
|
||||
import { addAgentNodeToGraph } from '@renderer/lib/patternGraph';
|
||||
import { PatternGraphCanvas } from './pattern-graph/PatternGraphCanvas';
|
||||
import { PatternGraphInspector } from './pattern-graph/PatternGraphInspector';
|
||||
|
||||
@@ -104,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`}
|
||||
@@ -143,6 +144,10 @@ export function PatternEditor({
|
||||
const graph = resolvePatternGraph(pattern);
|
||||
|
||||
function emitChange(nextPattern: PatternDefinition) {
|
||||
onChange({ ...nextPattern, graph: resolvePatternGraph(nextPattern) });
|
||||
}
|
||||
|
||||
function emitModeChange(nextPattern: PatternDefinition) {
|
||||
onChange(syncPatternGraph(nextPattern));
|
||||
}
|
||||
|
||||
@@ -159,7 +164,7 @@ export function PatternEditor({
|
||||
model: 'gpt-5.4',
|
||||
reasoningEffort: 'high',
|
||||
};
|
||||
const updatedGraph = addAgentNodeToGraph(graph, newAgent);
|
||||
const updatedGraph = addAgentToGraph(graph, pattern.mode, newAgent);
|
||||
onChange({ ...pattern, agents: [...pattern.agents, newAgent], graph: updatedGraph });
|
||||
}
|
||||
|
||||
@@ -175,9 +180,11 @@ export function PatternEditor({
|
||||
return;
|
||||
}
|
||||
|
||||
emitChange({
|
||||
const updatedGraph = removeAgentFromGraph(graph, pattern.mode, agentId);
|
||||
onChange({
|
||||
...pattern,
|
||||
agents: pattern.agents.filter((a) => a.id !== agentId),
|
||||
graph: updatedGraph,
|
||||
});
|
||||
setSelectedNodeId(null);
|
||||
}
|
||||
@@ -235,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>
|
||||
@@ -253,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"
|
||||
>
|
||||
@@ -262,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"
|
||||
>
|
||||
@@ -283,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}`}
|
||||
>
|
||||
@@ -294,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>
|
||||
@@ -303,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"
|
||||
>
|
||||
@@ -328,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">
|
||||
@@ -353,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">
|
||||
@@ -365,31 +372,31 @@ 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}
|
||||
onClick={() => emitChange({ ...pattern, mode })}
|
||||
onClick={() => emitModeChange({ ...pattern, mode })}
|
||||
type="button"
|
||||
>
|
||||
<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>
|
||||
@@ -400,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">
|
||||
@@ -419,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>
|
||||
) : (
|
||||
@@ -455,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>
|
||||
@@ -511,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"
|
||||
@@ -538,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"
|
||||
@@ -556,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)}
|
||||
@@ -576,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>
|
||||
)}
|
||||
@@ -613,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>
|
||||
)}
|
||||
@@ -643,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>
|
||||
);
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -26,25 +26,26 @@ import {
|
||||
} from '@renderer/lib/runTimelineFormatting';
|
||||
import type { OrchestrationMode } from '@shared/domain/pattern';
|
||||
import type { RunTimelineEventRecord, SessionRunRecord } from '@shared/domain/runTimeline';
|
||||
import { FileChangePreview } from '@renderer/components/chat/FileChangePreview';
|
||||
|
||||
/* ── Mode accent colours (shared with ActivityPanel) ───────── */
|
||||
|
||||
const modeAccent: Record<OrchestrationMode, { dot: string; ring: string; text: string }> = {
|
||||
single: { dot: 'bg-indigo-400', ring: 'ring-indigo-500/30', text: 'text-indigo-400' },
|
||||
sequential: { dot: 'bg-amber-400', ring: 'ring-amber-500/30', text: 'text-amber-400' },
|
||||
concurrent: { dot: 'bg-emerald-400', ring: 'ring-emerald-500/30', text: 'text-emerald-400' },
|
||||
handoff: { dot: 'bg-sky-400', ring: 'ring-sky-500/30', text: 'text-sky-400' },
|
||||
'group-chat': { dot: 'bg-violet-400', ring: 'ring-violet-500/30', text: 'text-violet-400' },
|
||||
magentic: { dot: 'bg-zinc-500', ring: 'ring-zinc-600/30', text: 'text-zinc-500' },
|
||||
single: { dot: 'bg-[#245CF9]', ring: 'ring-[#245CF9]/30', text: 'text-[#245CF9]' },
|
||||
sequential: { dot: 'bg-[var(--color-status-warning)]', ring: 'ring-[var(--color-status-warning)]/30', text: 'text-[var(--color-status-warning)]' },
|
||||
concurrent: { dot: 'bg-[var(--color-status-success)]', ring: 'ring-[var(--color-status-success)]/30', text: 'text-[var(--color-status-success)]' },
|
||||
handoff: { dot: 'bg-[var(--color-accent-sky)]', ring: 'ring-[var(--color-accent-sky)]/30', text: 'text-[var(--color-accent-sky)]' },
|
||||
'group-chat': { dot: 'bg-[var(--color-accent-purple)]', ring: 'ring-[var(--color-accent-purple)]/30', text: 'text-[var(--color-accent-purple)]' },
|
||||
magentic: { dot: 'bg-[var(--color-text-muted)]', ring: 'ring-[var(--color-text-muted)]/30', text: 'text-[var(--color-text-muted)]' },
|
||||
};
|
||||
|
||||
/* ── Status badges ─────────────────────────────────────────── */
|
||||
|
||||
const runStatusStyles: Record<SessionRunRecord['status'], { icon: ReactNode; className: string }> = {
|
||||
running: { icon: <CircleDot className="size-3" />, className: 'text-blue-400' },
|
||||
completed: { icon: <CheckCircle2 className="size-3" />, className: 'text-emerald-400' },
|
||||
cancelled: { icon: <XCircle className="size-3" />, className: 'text-zinc-400' },
|
||||
error: { icon: <XCircle className="size-3" />, className: 'text-red-400' },
|
||||
running: { icon: <CircleDot className="size-3" />, className: 'text-[var(--color-status-info)]' },
|
||||
completed: { icon: <CheckCircle2 className="size-3" />, className: 'text-[var(--color-status-success)]' },
|
||||
cancelled: { icon: <XCircle className="size-3" />, className: 'text-[var(--color-text-muted)]' },
|
||||
error: { icon: <XCircle className="size-3" />, className: 'text-[var(--color-status-error)]' },
|
||||
};
|
||||
|
||||
/* ── Event node icon ───────────────────────────────────────── */
|
||||
@@ -53,23 +54,23 @@ function EventIcon({ kind, status }: { kind: RunTimelineEventRecord['kind']; sta
|
||||
const base = 'size-3.5';
|
||||
switch (kind) {
|
||||
case 'run-started':
|
||||
return <Play className={`${base} text-zinc-500`} />;
|
||||
return <Play className={`${base} text-[var(--color-text-muted)]`} />;
|
||||
case 'thinking':
|
||||
return <Brain className={`${base} ${status === 'running' ? 'text-sky-400 animate-pulse' : 'text-zinc-500'}`} />;
|
||||
return <Brain className={`${base} ${status === 'running' ? 'text-[var(--color-accent-sky)] animate-pulse' : 'text-[var(--color-text-muted)]'}`} />;
|
||||
case 'handoff':
|
||||
return <ArrowRight className={`${base} text-amber-400`} />;
|
||||
return <ArrowRight className={`${base} text-[var(--color-status-warning)]`} />;
|
||||
case 'tool-call':
|
||||
return <Wrench className={`${base} text-violet-400`} />;
|
||||
return <Wrench className={`${base} text-[var(--color-accent-purple)]`} />;
|
||||
case 'approval':
|
||||
return <AlertTriangle className={`${base} ${status === 'running' ? 'text-amber-400 animate-pulse' : status === 'error' ? 'text-red-400' : 'text-emerald-400'}`} />;
|
||||
return <AlertTriangle className={`${base} ${status === 'running' ? 'text-[var(--color-status-warning)] animate-pulse' : status === 'error' ? 'text-[var(--color-status-error)]' : 'text-[var(--color-status-success)]'}`} />;
|
||||
case 'message':
|
||||
return <MessageSquare className={`${base} ${status === 'running' ? 'text-blue-400 animate-pulse' : status === 'error' ? 'text-red-400' : 'text-emerald-400'}`} />;
|
||||
return <MessageSquare className={`${base} ${status === 'running' ? 'text-[var(--color-status-info)] animate-pulse' : status === 'error' ? 'text-[var(--color-status-error)]' : 'text-[var(--color-status-success)]'}`} />;
|
||||
case 'run-completed':
|
||||
return <CheckCircle2 className={`${base} text-emerald-400`} />;
|
||||
return <CheckCircle2 className={`${base} text-[var(--color-status-success)]`} />;
|
||||
case 'run-cancelled':
|
||||
return <XCircle className={`${base} text-zinc-400`} />;
|
||||
return <XCircle className={`${base} text-[var(--color-text-muted)]`} />;
|
||||
case 'run-failed':
|
||||
return <AlertTriangle className={`${base} text-red-400`} />;
|
||||
return <AlertTriangle className={`${base} text-[var(--color-status-error)]`} />;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,67 +92,76 @@ function TimelineEventRow({
|
||||
const terminal = isTerminalEvent(event.kind);
|
||||
|
||||
return (
|
||||
<button
|
||||
className={`group relative flex w-full gap-2.5 text-left ${terminal ? 'py-1' : 'py-1.5'} ${isClickable ? 'cursor-pointer' : 'cursor-default'}`}
|
||||
disabled={!isClickable}
|
||||
onClick={isClickable ? () => onJumpToMessage(event.messageId!) : undefined}
|
||||
type="button"
|
||||
>
|
||||
<div className="relative">
|
||||
{/* Vertical connector line */}
|
||||
{!isLast && (
|
||||
<div className="absolute left-[7px] top-[22px] bottom-0 w-px bg-zinc-800" />
|
||||
<div className="absolute left-[7px] top-[22px] bottom-0 w-px bg-[var(--color-border)]" />
|
||||
)}
|
||||
|
||||
{/* Node */}
|
||||
<div className="relative z-10 flex shrink-0 items-start pt-0.5">
|
||||
<div className="flex size-[15px] items-center justify-center rounded-full bg-[var(--color-surface-1)]">
|
||||
<EventIcon kind={event.kind} status={event.status} />
|
||||
<button
|
||||
className={`group flex w-full gap-2.5 text-left transition-all duration-200 ${terminal ? 'py-1' : 'py-1.5'} ${isClickable ? 'cursor-pointer' : 'cursor-default'}`}
|
||||
disabled={!isClickable}
|
||||
onClick={isClickable ? () => onJumpToMessage(event.messageId!) : undefined}
|
||||
type="button"
|
||||
>
|
||||
{/* Node */}
|
||||
<div className="relative z-10 flex shrink-0 items-start pt-0.5">
|
||||
<div className={`flex size-[15px] items-center justify-center rounded-full ${event.status === 'running' ? 'brand-gradient-bg' : 'bg-[var(--color-surface-2)]'}`}>
|
||||
<EventIcon kind={event.kind} status={event.status} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className={`text-[11px] font-medium ${terminal ? 'text-zinc-600' : 'text-zinc-300'} ${isClickable ? 'group-hover:text-indigo-300' : ''}`}>
|
||||
{label}
|
||||
</span>
|
||||
{/* Approval kind badge */}
|
||||
{event.kind === 'approval' && event.approvalKind && (
|
||||
<span className={`rounded-full px-1.5 py-0.5 text-[8px] font-semibold uppercase tracking-wider ${
|
||||
event.status === 'running'
|
||||
? 'bg-amber-500/15 text-amber-400'
|
||||
: event.status === 'completed'
|
||||
? 'bg-emerald-500/15 text-emerald-400'
|
||||
: 'bg-red-500/15 text-red-400'
|
||||
}`}>
|
||||
{event.approvalKind === 'final-response' ? 'response' : 'tool'}
|
||||
{/* Content */}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className={`text-[11px] font-medium ${terminal ? 'text-[var(--color-text-muted)]' : 'text-[var(--color-text-secondary)]'} ${isClickable ? 'group-hover:text-[var(--color-text-accent)]' : ''}`}>
|
||||
{label}
|
||||
</span>
|
||||
{/* Approval kind badge */}
|
||||
{event.kind === 'approval' && event.approvalKind && (
|
||||
<span className={`rounded-full px-1.5 py-0.5 text-[8px] font-semibold uppercase tracking-wider ${
|
||||
event.status === 'running'
|
||||
? 'bg-[var(--color-status-warning)]/15 text-[var(--color-status-warning)]'
|
||||
: event.status === 'completed'
|
||||
? 'bg-[var(--color-status-success)]/15 text-[var(--color-status-success)]'
|
||||
: 'bg-[var(--color-status-error)]/15 text-[var(--color-status-error)]'
|
||||
}`}>
|
||||
{event.approvalKind === 'final-response' ? 'response' : 'tool'}
|
||||
</span>
|
||||
)}
|
||||
<span className="font-mono ml-auto shrink-0 text-[9px] tabular-nums text-[var(--color-text-muted)]">{timestamp}</span>
|
||||
</div>
|
||||
|
||||
{/* Content preview for message events */}
|
||||
{preview && (
|
||||
<p className={`mt-0.5 text-[10px] leading-snug text-[var(--color-text-muted)] ${isClickable ? 'group-hover:text-[var(--color-text-secondary)]' : ''}`}>
|
||||
{preview}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Approval detail */}
|
||||
{event.kind === 'approval' && event.approvalDetail && (
|
||||
<p className="mt-0.5 text-[10px] leading-snug text-[var(--color-text-muted)]">
|
||||
{truncateContent(event.approvalDetail, 120)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Error detail */}
|
||||
{event.error && (
|
||||
<p className="mt-0.5 text-[10px] leading-snug text-[var(--color-status-error)]/80">
|
||||
{truncateContent(event.error, 120)}
|
||||
</p>
|
||||
)}
|
||||
<span className="ml-auto shrink-0 text-[9px] tabular-nums text-zinc-700">{timestamp}</span>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{/* Content preview for message events */}
|
||||
{preview && (
|
||||
<p className={`mt-0.5 text-[10px] leading-snug text-zinc-600 ${isClickable ? 'group-hover:text-zinc-500' : ''}`}>
|
||||
{preview}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Approval detail */}
|
||||
{event.kind === 'approval' && event.approvalDetail && (
|
||||
<p className="mt-0.5 text-[10px] leading-snug text-zinc-500">
|
||||
{truncateContent(event.approvalDetail, 120)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Error detail */}
|
||||
{event.error && (
|
||||
<p className="mt-0.5 text-[10px] leading-snug text-red-500/80">
|
||||
{truncateContent(event.error, 120)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
{/* File change preview for tool-call events */}
|
||||
{event.kind === 'tool-call' && event.fileChanges && event.fileChanges.length > 0 && (
|
||||
<div className="relative z-10 ml-[25px] pb-1">
|
||||
<FileChangePreview fileChanges={event.fileChanges} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -169,15 +179,15 @@ function ThinkingGroupRow({
|
||||
return (
|
||||
<div className="group relative flex w-full gap-2.5 py-1">
|
||||
{!isLast && (
|
||||
<div className="absolute left-[7px] top-[22px] bottom-0 w-px bg-zinc-800" />
|
||||
<div className="absolute left-[7px] top-[22px] bottom-0 w-px bg-[var(--color-border)]" />
|
||||
)}
|
||||
<div className="relative z-10 flex shrink-0 items-start pt-0.5">
|
||||
<div className="flex size-[15px] items-center justify-center rounded-full bg-[var(--color-surface-1)]">
|
||||
<Brain className="size-3.5 text-zinc-500" />
|
||||
<div className="flex size-[15px] items-center justify-center rounded-full bg-[var(--color-surface-2)]">
|
||||
<Brain className="size-3.5 text-[var(--color-text-muted)]" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<span className="text-[11px] text-zinc-600">
|
||||
<span className="text-[11px] text-[var(--color-text-muted)]">
|
||||
{agentName ? `${agentName} thinking` : 'Thinking'} ×{events.length}
|
||||
</span>
|
||||
</div>
|
||||
@@ -225,26 +235,26 @@ function RunCard({
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-zinc-800 bg-zinc-900/40">
|
||||
<div className="glass-surface rounded-lg">
|
||||
{/* Run header */}
|
||||
<button
|
||||
className="flex w-full items-center gap-2 px-3 py-2 text-left transition hover:bg-zinc-800/30"
|
||||
className="flex w-full items-center gap-2 px-3 py-2 text-left transition-all duration-200 hover:bg-[var(--color-surface-3)]"
|
||||
onClick={onToggle}
|
||||
type="button"
|
||||
>
|
||||
{expanded
|
||||
? <ChevronDown className="size-3 shrink-0 text-zinc-600" />
|
||||
: <ChevronRight className="size-3 shrink-0 text-zinc-600" />}
|
||||
? <ChevronDown className="size-3 shrink-0 text-[var(--color-text-muted)]" />
|
||||
: <ChevronRight className="size-3 shrink-0 text-[var(--color-text-muted)]" />}
|
||||
|
||||
<Bot className={`size-3 shrink-0 ${accent.text}`} />
|
||||
|
||||
<span className="min-w-0 flex-1 truncate text-[11px] font-medium text-zinc-300">
|
||||
<span className="min-w-0 flex-1 truncate text-[11px] font-medium text-[var(--color-text-secondary)]">
|
||||
{run.patternName}
|
||||
</span>
|
||||
|
||||
{/* Status */}
|
||||
<span className={`flex items-center gap-1 shrink-0 ${statusStyle.className}`}>
|
||||
{run.status === 'running' && <span className="size-1.5 animate-pulse rounded-full bg-blue-400" />}
|
||||
{run.status === 'running' && <span className="size-1.5 animate-pulse rounded-full bg-[var(--color-status-info)]" />}
|
||||
{run.status !== 'running' && statusStyle.icon}
|
||||
<span className="text-[9px] font-medium">{formatRunStatusLabel(run.status)}</span>
|
||||
</span>
|
||||
@@ -252,13 +262,13 @@ function RunCard({
|
||||
|
||||
{/* Expanded timeline */}
|
||||
{expanded && (
|
||||
<div className="border-t border-zinc-800/60 px-3 pb-2 pt-1.5">
|
||||
<div className="border-t border-[var(--color-border-subtle)] px-3 pb-2 pt-1.5">
|
||||
{/* Agent badges */}
|
||||
{run.agents.length > 1 && (
|
||||
<div className="mb-2 flex flex-wrap gap-1">
|
||||
{run.agents.map((agent) => (
|
||||
<span
|
||||
className="rounded-full bg-zinc-800/80 px-2 py-0.5 text-[9px] font-medium text-zinc-500"
|
||||
className="rounded-full bg-[var(--color-surface-2)] px-2 py-0.5 text-[9px] font-medium text-[var(--color-text-muted)]"
|
||||
key={agent.agentId}
|
||||
>
|
||||
{agent.agentName}
|
||||
@@ -281,7 +291,7 @@ function RunCard({
|
||||
|
||||
{/* Duration footer */}
|
||||
{duration && (
|
||||
<div className="mt-1 border-t border-zinc-800/40 pt-1.5 text-[9px] tabular-nums text-zinc-700">
|
||||
<div className="font-mono mt-1 border-t border-[var(--color-border-subtle)] pt-1.5 text-[9px] tabular-nums text-[var(--color-text-muted)]">
|
||||
Duration: {duration}
|
||||
</div>
|
||||
)}
|
||||
@@ -295,7 +305,7 @@ function RunCard({
|
||||
|
||||
function EmptyTimeline() {
|
||||
return (
|
||||
<p className="py-4 text-center text-[11px] text-zinc-600">
|
||||
<p className="py-4 text-center text-[11px] text-[var(--color-text-muted)]">
|
||||
Send a message to see the run timeline
|
||||
</p>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Search, MessageSquare, ArrowRight } from 'lucide-react';
|
||||
|
||||
import type { WorkspaceState } from '@shared/domain/workspace';
|
||||
import type { ChatMessageRecord, SessionRecord } from '@shared/domain/session';
|
||||
import { isScratchpadProject } from '@shared/domain/project';
|
||||
|
||||
export interface SessionSearchPanelProps {
|
||||
workspace: WorkspaceState;
|
||||
onClose: () => void;
|
||||
onSelectSession: (sessionId: string) => void;
|
||||
}
|
||||
|
||||
interface SearchHit {
|
||||
session: SessionRecord;
|
||||
projectName: string;
|
||||
message: ChatMessageRecord;
|
||||
/** The matching substring context around the first token hit. */
|
||||
snippet: string;
|
||||
/** Character offset of the match within the snippet for highlighting. */
|
||||
matchStart: number;
|
||||
matchLength: number;
|
||||
}
|
||||
|
||||
function extractSnippet(content: string, query: string): { snippet: string; matchStart: number; matchLength: number } | undefined {
|
||||
const lower = content.toLowerCase();
|
||||
const qLower = query.toLowerCase().trim();
|
||||
if (!qLower) return undefined;
|
||||
|
||||
// Find first occurrence of query in content
|
||||
const idx = lower.indexOf(qLower);
|
||||
if (idx === -1) {
|
||||
// Try individual tokens
|
||||
const tokens = qLower.split(/\s+/).filter(Boolean);
|
||||
for (const token of tokens) {
|
||||
const tidx = lower.indexOf(token);
|
||||
if (tidx !== -1) {
|
||||
const start = Math.max(0, tidx - 40);
|
||||
const end = Math.min(content.length, tidx + token.length + 80);
|
||||
const snippet = (start > 0 ? '…' : '') + content.slice(start, end).replace(/\n/g, ' ') + (end < content.length ? '…' : '');
|
||||
const adjustedStart = (start > 0 ? 1 : 0) + (tidx - start);
|
||||
return { snippet, matchStart: adjustedStart, matchLength: token.length };
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const start = Math.max(0, idx - 40);
|
||||
const end = Math.min(content.length, idx + qLower.length + 80);
|
||||
const snippet = (start > 0 ? '…' : '') + content.slice(start, end).replace(/\n/g, ' ') + (end < content.length ? '…' : '');
|
||||
const adjustedStart = (start > 0 ? 1 : 0) + (idx - start);
|
||||
return { snippet, matchStart: adjustedStart, matchLength: qLower.length };
|
||||
}
|
||||
|
||||
export function SessionSearchPanel({ workspace, onClose, onSelectSession }: SessionSearchPanelProps) {
|
||||
const [query, setQuery] = useState('');
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => { inputRef.current?.focus(); }, []);
|
||||
|
||||
// Escape to close in capture phase
|
||||
useEffect(() => {
|
||||
const handleEscape = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
e.stopImmediatePropagation();
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', handleEscape, true);
|
||||
return () => document.removeEventListener('keydown', handleEscape, true);
|
||||
}, [onClose]);
|
||||
|
||||
// Build project name lookup
|
||||
const projectNames = useMemo(() => {
|
||||
const map = new Map<string, string>();
|
||||
for (const p of workspace.projects) {
|
||||
map.set(p.id, isScratchpadProject(p) ? 'Scratchpad' : p.name);
|
||||
}
|
||||
return map;
|
||||
}, [workspace.projects]);
|
||||
|
||||
// Search across all sessions and messages
|
||||
const hits = useMemo<SearchHit[]>(() => {
|
||||
const q = query.trim();
|
||||
if (!q) return [];
|
||||
|
||||
const results: SearchHit[] = [];
|
||||
const activeSessions = workspace.sessions.filter((s) => !s.isArchived);
|
||||
|
||||
for (const session of activeSessions) {
|
||||
for (const message of session.messages) {
|
||||
if (!message.content) continue;
|
||||
const extracted = extractSnippet(message.content, q);
|
||||
if (extracted) {
|
||||
results.push({
|
||||
session,
|
||||
projectName: projectNames.get(session.projectId) ?? 'Unknown',
|
||||
message,
|
||||
...extracted,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Limit results for performance and sort by session recency
|
||||
return results.slice(0, 50);
|
||||
}, [query, workspace.sessions, projectNames]);
|
||||
|
||||
useEffect(() => { setSelectedIndex(0); }, [query]);
|
||||
|
||||
const handleSelect = useCallback((hit: SearchHit) => {
|
||||
onClose();
|
||||
onSelectSession(hit.session.id);
|
||||
// After navigation, scroll to the matching message
|
||||
requestAnimationFrame(() => {
|
||||
setTimeout(() => {
|
||||
const el = document.querySelector(`[data-message-id="${CSS.escape(hit.message.id)}"]`);
|
||||
if (el) {
|
||||
el.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
el.classList.add('ring-1', 'ring-[var(--color-accent)]/40', 'rounded-lg');
|
||||
setTimeout(() => el.classList.remove('ring-1', 'ring-[var(--color-accent)]/40', 'rounded-lg'), 2000);
|
||||
}
|
||||
}, 100);
|
||||
});
|
||||
}, [onClose, onSelectSession]);
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(e: React.KeyboardEvent) => {
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
if (hits.length > 0) setSelectedIndex((i) => Math.min(i + 1, hits.length - 1));
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
setSelectedIndex((i) => Math.max(i - 1, 0));
|
||||
} else if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
const hit = hits[selectedIndex];
|
||||
if (hit) handleSelect(hit);
|
||||
}
|
||||
},
|
||||
[hits, selectedIndex, handleSelect],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const item = listRef.current?.querySelector(`[data-search-index="${selectedIndex}"]`);
|
||||
item?.scrollIntoView({ block: 'nearest' });
|
||||
}, [selectedIndex]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="palette-backdrop-enter fixed inset-0 z-[60] flex justify-center bg-[#07080e]/80 pt-[15vh] backdrop-blur-sm"
|
||||
onClick={onClose}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Search sessions"
|
||||
>
|
||||
<div
|
||||
className="palette-enter glow-border flex h-fit max-h-[min(520px,65vh)] w-full max-w-2xl flex-col overflow-hidden rounded-xl bg-[var(--color-surface-1)] shadow-[0_16px_64px_rgba(0,0,0,0.5)]"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onKeyDown={handleKeyDown}
|
||||
>
|
||||
{/* Search input */}
|
||||
<div className="flex items-center gap-3 border-b border-[var(--color-border)] px-4">
|
||||
<Search className="size-4 shrink-0 text-[var(--color-text-muted)]" />
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
className="flex-1 bg-transparent py-3.5 text-[14px] text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-muted)]"
|
||||
placeholder="Search across all sessions…"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
aria-label="Search session content"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
/>
|
||||
{query && (
|
||||
<span className="shrink-0 text-[11px] text-[var(--color-text-muted)]">
|
||||
{hits.length} result{hits.length !== 1 ? 's' : ''}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Results */}
|
||||
<div ref={listRef} className="flex-1 overflow-y-auto py-1.5" role="listbox">
|
||||
{query && hits.length === 0 ? (
|
||||
<div className="px-4 py-10 text-center text-[13px] text-[var(--color-text-muted)]">
|
||||
No matches found
|
||||
</div>
|
||||
) : !query ? (
|
||||
<div className="px-4 py-10 text-center text-[13px] text-[var(--color-text-muted)]">
|
||||
Type to search across all session messages
|
||||
</div>
|
||||
) : (
|
||||
hits.map((hit, index) => {
|
||||
const isSelected = index === selectedIndex;
|
||||
return (
|
||||
<button
|
||||
key={`${hit.session.id}-${hit.message.id}`}
|
||||
data-search-index={index}
|
||||
className={`flex w-full flex-col gap-1 px-4 py-2.5 text-left transition-colors ${
|
||||
isSelected
|
||||
? 'bg-[var(--color-accent-muted)] text-[var(--color-text-primary)]'
|
||||
: 'text-[var(--color-text-secondary)] hover:bg-[var(--color-glass-hover)] hover:text-[var(--color-text-primary)]'
|
||||
}`}
|
||||
onClick={() => handleSelect(hit)}
|
||||
onMouseEnter={() => setSelectedIndex(index)}
|
||||
role="option"
|
||||
aria-selected={isSelected}
|
||||
type="button"
|
||||
>
|
||||
{/* Session title row */}
|
||||
<div className="flex items-center gap-2">
|
||||
<MessageSquare className={`size-3.5 shrink-0 ${isSelected ? 'text-[var(--color-text-accent)]' : 'text-[var(--color-text-muted)]'}`} />
|
||||
<span className="truncate text-[12px] font-medium">{hit.session.title}</span>
|
||||
<span className="text-[10px] text-[var(--color-text-muted)]">·</span>
|
||||
<span className="truncate text-[10px] text-[var(--color-text-muted)]">{hit.projectName}</span>
|
||||
<ArrowRight className="ml-auto size-3 shrink-0 text-[var(--color-text-muted)]" />
|
||||
</div>
|
||||
{/* Message snippet with highlighted match */}
|
||||
<div className="pl-5.5 text-[12px] leading-relaxed text-[var(--color-text-muted)]">
|
||||
<span className="line-clamp-2">
|
||||
{hit.snippet.slice(0, hit.matchStart)}
|
||||
<mark className="rounded-sm bg-[var(--color-accent)]/20 px-0.5 text-[var(--color-text-accent)]">
|
||||
{hit.snippet.slice(hit.matchStart, hit.matchStart + hit.matchLength)}
|
||||
</mark>
|
||||
{hit.snippet.slice(hit.matchStart + hit.matchLength)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="pl-5.5 text-[10px] text-[var(--color-text-muted)]">
|
||||
{hit.message.role === 'user' ? 'You' : hit.message.authorName}
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Footer hints */}
|
||||
<div className="flex items-center gap-4 border-t border-[var(--color-border)] px-4 py-2 text-[11px] text-[var(--color-text-muted)]">
|
||||
<span className="flex items-center gap-1">
|
||||
<kbd className="rounded border border-[var(--color-border-subtle)] px-1 font-mono text-[10px]">↑↓</kbd>
|
||||
navigate
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<kbd className="rounded border border-[var(--color-border-subtle)] px-1 font-mono text-[10px]">↵</kbd>
|
||||
jump to message
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<kbd className="rounded border border-[var(--color-border-subtle)] px-1 font-mono text-[10px]">esc</kbd>
|
||||
close
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import { ChevronLeft, ChevronRight, Code, Cpu, FolderOpen, Palette, Plus, RefreshCw, Server, TriangleAlert, Workflow, Wrench } from 'lucide-react';
|
||||
import { ChevronLeft, ChevronRight, Code, Cpu, FolderOpen, Palette, Plus, Server, TriangleAlert, Workflow, Wrench } from 'lucide-react';
|
||||
|
||||
import { CopilotStatusCard } from '@renderer/components/CopilotStatusCard';
|
||||
import { PatternEditor } from '@renderer/components/PatternEditor';
|
||||
import { ToggleSwitch } from '@renderer/components/ui';
|
||||
import { LspProfileEditor } from '@renderer/components/settings/LspProfileEditor';
|
||||
import { McpServerEditor } from '@renderer/components/settings/McpServerEditor';
|
||||
import type { SidecarCapabilities } from '@shared/contracts/sidecar';
|
||||
import type { DiscoveredMcpServer, DiscoveredToolingState, ProjectDiscoveredTooling } from '@shared/domain/discoveredTooling';
|
||||
import type { SidecarCapabilities, QuotaSnapshot } from '@shared/contracts/sidecar';
|
||||
import type { DiscoveredMcpServer, DiscoveredToolingState } from '@shared/domain/discoveredTooling';
|
||||
import { listAcceptedDiscoveredMcpServers, listPendingDiscoveredMcpServers } from '@shared/domain/discoveredTooling';
|
||||
import type { ModelDefinition } from '@shared/domain/models';
|
||||
import type { PatternDefinition } from '@shared/domain/pattern';
|
||||
@@ -26,8 +27,6 @@ interface SettingsPanelProps {
|
||||
theme: AppearanceTheme;
|
||||
toolingSettings: WorkspaceToolingSettings;
|
||||
discoveredUserTooling: DiscoveredToolingState;
|
||||
discoveredProjectTooling?: ProjectDiscoveredTooling;
|
||||
selectedProjectName?: string;
|
||||
isRefreshingCapabilities: boolean;
|
||||
onRefreshCapabilities: () => void;
|
||||
onClose: () => void;
|
||||
@@ -41,11 +40,14 @@ interface SettingsPanelProps {
|
||||
onDeleteLspProfile: (profileId: string) => Promise<void>;
|
||||
onNewLspProfile: () => LspProfileDefinition;
|
||||
onSetTheme: (theme: AppearanceTheme) => void;
|
||||
notificationsEnabled: boolean;
|
||||
onSetNotificationsEnabled: (enabled: boolean) => void;
|
||||
minimizeToTray: boolean;
|
||||
onSetMinimizeToTray: (enabled: boolean) => void;
|
||||
onOpenAppDataFolder: () => void;
|
||||
onResetLocalWorkspace: () => Promise<void>;
|
||||
onRescanProjectConfigs?: () => void;
|
||||
onResolveUserDiscoveredTooling?: (serverIds: string[], resolution: 'accept' | 'dismiss') => void;
|
||||
onResolveProjectDiscoveredTooling?: (serverIds: string[], resolution: 'accept' | 'dismiss') => void;
|
||||
onGetQuota?: () => Promise<Record<string, QuotaSnapshot>>;
|
||||
}
|
||||
|
||||
type SettingsSection = 'appearance' | 'connection' | 'patterns' | 'mcp-servers' | 'lsp-profiles' | 'troubleshooting';
|
||||
@@ -96,8 +98,8 @@ const navGroups: NavGroup[] = [
|
||||
];
|
||||
|
||||
function modeBadgeClasses(pattern: PatternDefinition) {
|
||||
if (pattern.availability === 'unavailable') return 'bg-amber-500/10 text-amber-400';
|
||||
return 'bg-zinc-800 text-zinc-400';
|
||||
if (pattern.availability === 'unavailable') return 'bg-[var(--color-status-warning)]/10 text-[var(--color-status-warning)]';
|
||||
return 'bg-[var(--color-surface-3)] text-[var(--color-text-secondary)]';
|
||||
}
|
||||
|
||||
export function SettingsPanel({
|
||||
@@ -107,8 +109,6 @@ export function SettingsPanel({
|
||||
theme,
|
||||
toolingSettings,
|
||||
discoveredUserTooling,
|
||||
discoveredProjectTooling,
|
||||
selectedProjectName,
|
||||
isRefreshingCapabilities,
|
||||
onRefreshCapabilities,
|
||||
onClose,
|
||||
@@ -122,11 +122,14 @@ export function SettingsPanel({
|
||||
onDeleteLspProfile,
|
||||
onNewLspProfile,
|
||||
onSetTheme,
|
||||
notificationsEnabled,
|
||||
onSetNotificationsEnabled,
|
||||
minimizeToTray,
|
||||
onSetMinimizeToTray,
|
||||
onOpenAppDataFolder,
|
||||
onResetLocalWorkspace,
|
||||
onRescanProjectConfigs,
|
||||
onResolveUserDiscoveredTooling,
|
||||
onResolveProjectDiscoveredTooling,
|
||||
onGetQuota,
|
||||
}: SettingsPanelProps) {
|
||||
const [activeSection, setActiveSection] = useState<SettingsSection>('appearance');
|
||||
const [editingPattern, setEditingPattern] = useState<PatternDefinition | null>(null);
|
||||
@@ -213,16 +216,16 @@ export function SettingsPanel({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex flex-col bg-[var(--color-surface-0)]">
|
||||
<div className="overlay-slide-enter fixed inset-0 z-50 flex flex-col bg-[var(--color-surface-0)]">
|
||||
<div className="drag-region flex items-center gap-3 border-b border-[var(--color-border)] px-5 pb-3 pt-3">
|
||||
<button
|
||||
className="no-drag flex size-8 items-center justify-center rounded-lg text-zinc-400 transition hover:bg-zinc-800 hover:text-zinc-200"
|
||||
className="no-drag flex size-8 items-center justify-center rounded-lg text-[var(--color-text-secondary)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]"
|
||||
onClick={onClose}
|
||||
type="button"
|
||||
>
|
||||
<ChevronLeft className="size-4" />
|
||||
</button>
|
||||
<h2 className="text-[13px] font-semibold text-zinc-100">Settings</h2>
|
||||
<h2 className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">Settings</h2>
|
||||
</div>
|
||||
|
||||
<div className="flex min-h-0 flex-1">
|
||||
@@ -230,7 +233,7 @@ export function SettingsPanel({
|
||||
<div className="space-y-4">
|
||||
{navGroups.map((group) => (
|
||||
<div key={group.label}>
|
||||
<span className="mb-1 block px-3 text-[10px] font-semibold uppercase tracking-wider text-zinc-600">
|
||||
<span className="mb-1 block px-3 text-[10px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
|
||||
{group.label}
|
||||
</span>
|
||||
<div className="space-y-0.5">
|
||||
@@ -238,16 +241,16 @@ export function SettingsPanel({
|
||||
const isActive = item.id === activeSection;
|
||||
return (
|
||||
<button
|
||||
className={`flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-left text-[13px] transition ${
|
||||
className={`flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-left text-[13px] transition-all duration-200 ${
|
||||
isActive
|
||||
? 'bg-zinc-800 font-medium text-zinc-100'
|
||||
: 'text-zinc-400 hover:bg-zinc-800/50 hover:text-zinc-300'
|
||||
? 'bg-[var(--color-surface-3)] font-medium text-[var(--color-text-primary)]'
|
||||
: 'text-[var(--color-text-secondary)] hover:bg-[var(--color-surface-3)]/50 hover:text-[var(--color-text-secondary)]'
|
||||
}`}
|
||||
key={item.id}
|
||||
onClick={() => setActiveSection(item.id)}
|
||||
type="button"
|
||||
>
|
||||
<span className={isActive ? 'text-zinc-300' : 'text-zinc-500'}>{item.icon}</span>
|
||||
<span className={isActive ? 'text-[var(--color-text-secondary)]' : 'text-[var(--color-text-muted)]'}>{item.icon}</span>
|
||||
{item.label}
|
||||
</button>
|
||||
);
|
||||
@@ -261,7 +264,14 @@ export function SettingsPanel({
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<div className="mx-auto max-w-2xl px-8 py-6">
|
||||
{activeSection === 'appearance' && (
|
||||
<AppearanceSection theme={theme} onSetTheme={onSetTheme} />
|
||||
<AppearanceSection
|
||||
theme={theme}
|
||||
onSetTheme={onSetTheme}
|
||||
notificationsEnabled={notificationsEnabled}
|
||||
onSetNotificationsEnabled={onSetNotificationsEnabled}
|
||||
minimizeToTray={minimizeToTray}
|
||||
onSetMinimizeToTray={onSetMinimizeToTray}
|
||||
/>
|
||||
)}
|
||||
{activeSection === 'connection' && (
|
||||
<ConnectionSection
|
||||
@@ -269,6 +279,7 @@ export function SettingsPanel({
|
||||
isRefreshing={isRefreshingCapabilities}
|
||||
modelCount={sidecarCapabilities?.models.length ?? 0}
|
||||
onRefresh={onRefreshCapabilities}
|
||||
onGetQuota={onGetQuota}
|
||||
/>
|
||||
)}
|
||||
{activeSection === 'patterns' && (
|
||||
@@ -287,12 +298,8 @@ export function SettingsPanel({
|
||||
)}
|
||||
{activeSection === 'mcp-servers' && (
|
||||
<DiscoveredMcpSection
|
||||
discoveredProjectTooling={discoveredProjectTooling}
|
||||
discoveredUserTooling={discoveredUserTooling}
|
||||
onRescanProjectConfigs={onRescanProjectConfigs}
|
||||
onResolveProjectDiscoveredTooling={onResolveProjectDiscoveredTooling}
|
||||
onResolveUserDiscoveredTooling={onResolveUserDiscoveredTooling}
|
||||
selectedProjectName={selectedProjectName}
|
||||
/>
|
||||
)}
|
||||
{activeSection === 'lsp-profiles' && (
|
||||
@@ -324,15 +331,23 @@ const themeOptions: { value: AppearanceTheme; label: string; description: string
|
||||
function AppearanceSection({
|
||||
theme,
|
||||
onSetTheme,
|
||||
notificationsEnabled,
|
||||
onSetNotificationsEnabled,
|
||||
minimizeToTray,
|
||||
onSetMinimizeToTray,
|
||||
}: {
|
||||
theme: AppearanceTheme;
|
||||
onSetTheme: (theme: AppearanceTheme) => void;
|
||||
}) {
|
||||
notificationsEnabled: boolean;
|
||||
onSetNotificationsEnabled: (enabled: boolean) => void;
|
||||
minimizeToTray: boolean;
|
||||
onSetMinimizeToTray: (enabled: boolean) => void;
|
||||
}){
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-1">
|
||||
<h3 className="text-[13px] font-semibold text-zinc-200">Appearance</h3>
|
||||
<p className="mt-0.5 text-[12px] text-zinc-500">
|
||||
<h3 className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">Appearance</h3>
|
||||
<p className="mt-0.5 text-[12px] text-[var(--color-text-muted)]">
|
||||
Choose how Aryx looks on your device
|
||||
</p>
|
||||
</div>
|
||||
@@ -342,32 +357,80 @@ function AppearanceSection({
|
||||
const isSelected = option.value === theme;
|
||||
return (
|
||||
<button
|
||||
className={`flex w-full items-center gap-3 rounded-lg border px-4 py-3 text-left transition ${
|
||||
className={`flex w-full items-center gap-3 rounded-lg border px-4 py-3 text-left transition-all duration-200 ${
|
||||
isSelected
|
||||
? 'border-indigo-500/50 bg-indigo-500/10'
|
||||
: 'border-[var(--color-border)] hover:border-zinc-600 hover:bg-zinc-800/40'
|
||||
? 'border-[var(--color-border-glow)] bg-[var(--color-accent-muted)]'
|
||||
: 'border-[var(--color-border)] hover:border-[var(--color-border)] hover:bg-[var(--color-surface-3)]/40'
|
||||
}`}
|
||||
key={option.value}
|
||||
onClick={() => onSetTheme(option.value)}
|
||||
type="button"
|
||||
>
|
||||
<div
|
||||
className={`flex size-4 shrink-0 items-center justify-center rounded-full border-2 transition ${
|
||||
isSelected ? 'border-indigo-500' : 'border-zinc-600'
|
||||
className={`flex size-4 shrink-0 items-center justify-center rounded-full border-2 transition-all duration-200 ${
|
||||
isSelected ? 'border-[var(--color-accent)]' : 'border-[var(--color-border)]'
|
||||
}`}
|
||||
>
|
||||
{isSelected && <div className="size-2 rounded-full bg-indigo-500" />}
|
||||
{isSelected && <div className="size-2 rounded-full bg-[var(--color-accent)]" />}
|
||||
</div>
|
||||
<div>
|
||||
<span className={`text-[13px] font-medium ${isSelected ? 'text-zinc-100' : 'text-zinc-300'}`}>
|
||||
<span className={`text-[13px] font-medium ${isSelected ? 'text-[var(--color-text-primary)]' : 'text-[var(--color-text-secondary)]'}`}>
|
||||
{option.label}
|
||||
</span>
|
||||
<p className="text-[12px] text-zinc-500">{option.description}</p>
|
||||
<p className="text-[12px] text-[var(--color-text-muted)]">{option.description}</p>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Notifications */}
|
||||
<div className="mt-8 mb-1">
|
||||
<h3 className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">Notifications</h3>
|
||||
<p className="mt-0.5 text-[12px] text-[var(--color-text-muted)]">
|
||||
Control when Aryx sends desktop notifications
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<button
|
||||
className="mt-4 flex w-full items-center justify-between rounded-lg border border-[var(--color-border)] px-4 py-3 text-left transition hover:bg-[var(--color-surface-3)]/40"
|
||||
onClick={() => onSetNotificationsEnabled(!notificationsEnabled)}
|
||||
type="button"
|
||||
>
|
||||
<div>
|
||||
<span className="text-[13px] font-medium text-[var(--color-text-primary)]">
|
||||
Run completion alerts
|
||||
</span>
|
||||
<p className="text-[12px] text-[var(--color-text-muted)]">
|
||||
Notify when a session run completes, fails, or needs approval while the app is unfocused
|
||||
</p>
|
||||
</div>
|
||||
<ToggleSwitch enabled={notificationsEnabled} />
|
||||
</button>
|
||||
|
||||
{/* System Tray */}
|
||||
<div className="mt-8 mb-1">
|
||||
<h3 className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">System Tray</h3>
|
||||
<p className="mt-0.5 text-[12px] text-[var(--color-text-muted)]">
|
||||
Control how Aryx behaves when you close the window
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<button
|
||||
className="mt-4 flex w-full items-center justify-between rounded-lg border border-[var(--color-border)] px-4 py-3 text-left transition hover:bg-[var(--color-surface-3)]/40"
|
||||
onClick={() => onSetMinimizeToTray(!minimizeToTray)}
|
||||
type="button"
|
||||
>
|
||||
<div>
|
||||
<span className="text-[13px] font-medium text-[var(--color-text-primary)]">
|
||||
Minimize to tray on close
|
||||
</span>
|
||||
<p className="text-[12px] text-[var(--color-text-muted)]">
|
||||
Keep Aryx running in the system tray when you close the window instead of quitting
|
||||
</p>
|
||||
</div>
|
||||
<ToggleSwitch enabled={minimizeToTray} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -377,25 +440,28 @@ function ConnectionSection({
|
||||
modelCount,
|
||||
isRefreshing,
|
||||
onRefresh,
|
||||
onGetQuota,
|
||||
}: {
|
||||
connection?: SidecarCapabilities['connection'];
|
||||
modelCount: number;
|
||||
isRefreshing: boolean;
|
||||
onRefresh: () => void;
|
||||
onGetQuota?: () => Promise<Record<string, QuotaSnapshot>>;
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-1">
|
||||
<h3 className="text-[13px] font-semibold text-zinc-200">GitHub Copilot</h3>
|
||||
<p className="mt-0.5 text-[12px] text-zinc-500">
|
||||
<h3 className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">GitHub Copilot</h3>
|
||||
<p className="mt-0.5 text-[12px] text-[var(--color-text-muted)]">
|
||||
Aryx uses your installed GitHub Copilot CLI for AI capabilities
|
||||
</p>
|
||||
</div>
|
||||
<div className="mt-4 rounded-xl border border-[var(--color-border)] bg-zinc-900/30 p-4">
|
||||
<div className="mt-4 rounded-xl border border-[var(--color-border)] bg-[var(--color-glass)] p-4">
|
||||
<CopilotStatusCard
|
||||
connection={connection}
|
||||
isRefreshing={isRefreshing}
|
||||
modelCount={modelCount}
|
||||
onGetQuota={onGetQuota}
|
||||
onRefresh={onRefresh}
|
||||
/>
|
||||
</div>
|
||||
@@ -424,25 +490,25 @@ function PatternsSection({
|
||||
<div className="space-y-1">
|
||||
{patterns.map((pattern) => (
|
||||
<button
|
||||
className="group flex w-full items-center gap-3 rounded-xl border border-transparent px-4 py-3 text-left transition hover:border-zinc-800 hover:bg-zinc-900"
|
||||
className="group flex w-full items-center gap-3 rounded-xl border border-transparent px-4 py-3 text-left transition-all duration-200 hover:border-[var(--color-border)] hover:bg-[var(--color-surface-1)]"
|
||||
key={pattern.id}
|
||||
onClick={() => onEditPattern(pattern)}
|
||||
type="button"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-[13px] font-medium text-zinc-200">{pattern.name}</span>
|
||||
<span className="text-[13px] font-medium text-[var(--color-text-primary)]">{pattern.name}</span>
|
||||
<span className={`rounded-full px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide ${modeBadgeClasses(pattern)}`}>
|
||||
{pattern.mode}
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-0.5 truncate text-[12px] text-zinc-500">{pattern.description}</p>
|
||||
<p className="mt-0.5 truncate text-[12px] text-[var(--color-text-muted)]">{pattern.description}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-[12px] text-zinc-600">
|
||||
<span className="text-[12px] text-[var(--color-text-muted)]">
|
||||
{pattern.agents.length} agent{pattern.agents.length === 1 ? '' : 's'}
|
||||
</span>
|
||||
<ChevronRight className="size-4 text-zinc-700 transition group-hover:text-zinc-500" />
|
||||
<ChevronRight className="size-4 text-[var(--color-text-muted)] transition-all duration-200 group-hover:text-[var(--color-text-muted)]" />
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
@@ -543,8 +609,8 @@ function SectionHeader({
|
||||
return (
|
||||
<div className="mb-4 flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<h3 className="text-[13px] font-semibold text-zinc-200">{title}</h3>
|
||||
<p className="mt-0.5 text-[12px] text-zinc-500">{description}</p>
|
||||
<h3 className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">{title}</h3>
|
||||
<p className="mt-0.5 text-[12px] text-[var(--color-text-muted)]">{description}</p>
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
@@ -554,7 +620,7 @@ function SectionHeader({
|
||||
function SectionAction({ label, onClick }: { label: string; onClick: () => void }) {
|
||||
return (
|
||||
<button
|
||||
className="flex items-center gap-1.5 rounded-lg bg-zinc-800 px-3 py-1.5 text-[13px] font-medium text-zinc-200 transition hover:bg-zinc-700"
|
||||
className="flex items-center gap-1.5 rounded-lg bg-[var(--color-surface-3)] px-3 py-1.5 text-[13px] font-medium text-[var(--color-text-primary)] transition-all duration-200 hover:bg-[var(--color-surface-3)]"
|
||||
onClick={onClick}
|
||||
type="button"
|
||||
>
|
||||
@@ -577,27 +643,27 @@ function ToolingListButton({
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
className="group flex w-full items-center gap-3 rounded-xl border border-transparent px-4 py-3 text-left transition hover:border-zinc-800 hover:bg-zinc-900"
|
||||
className="group flex w-full items-center gap-3 rounded-xl border border-transparent px-4 py-3 text-left transition-all duration-200 hover:border-[var(--color-border)] hover:bg-[var(--color-surface-1)]"
|
||||
onClick={onClick}
|
||||
type="button"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="truncate text-[13px] font-medium text-zinc-200">{label}</span>
|
||||
<span className="rounded-full bg-zinc-800 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-zinc-400">
|
||||
<span className="truncate text-[13px] font-medium text-[var(--color-text-primary)]">{label}</span>
|
||||
<span className="rounded-full bg-[var(--color-surface-3)] px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-[var(--color-text-secondary)]">
|
||||
{meta}
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-0.5 truncate text-[12px] text-zinc-500">{detail}</p>
|
||||
<p className="mt-0.5 truncate text-[12px] text-[var(--color-text-muted)]">{detail}</p>
|
||||
</div>
|
||||
<ChevronRight className="size-4 text-zinc-700 transition group-hover:text-zinc-500" />
|
||||
<ChevronRight className="size-4 text-[var(--color-text-muted)] transition-all duration-200 group-hover:text-[var(--color-text-muted)]" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function EmptyState({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<div className="rounded-xl border border-dashed border-zinc-800 bg-zinc-900/20 px-5 py-8 text-center text-[12px] leading-relaxed text-zinc-500">
|
||||
<div className="rounded-xl border border-dashed border-[var(--color-border)] bg-[var(--color-surface-1)]/20 px-5 py-8 text-center text-[12px] leading-relaxed text-[var(--color-text-muted)]">
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
@@ -607,68 +673,32 @@ function EmptyState({ children }: { children: ReactNode }) {
|
||||
|
||||
function DiscoveredMcpSection({
|
||||
discoveredUserTooling,
|
||||
discoveredProjectTooling,
|
||||
selectedProjectName,
|
||||
onRescanProjectConfigs,
|
||||
onResolveUserDiscoveredTooling,
|
||||
onResolveProjectDiscoveredTooling,
|
||||
}: {
|
||||
discoveredUserTooling: DiscoveredToolingState;
|
||||
discoveredProjectTooling?: ProjectDiscoveredTooling;
|
||||
selectedProjectName?: string;
|
||||
onRescanProjectConfigs?: () => void;
|
||||
onResolveUserDiscoveredTooling?: (serverIds: string[], resolution: 'accept' | 'dismiss') => void;
|
||||
onResolveProjectDiscoveredTooling?: (serverIds: string[], resolution: 'accept' | 'dismiss') => void;
|
||||
}) {
|
||||
const acceptedUser = listAcceptedDiscoveredMcpServers(discoveredUserTooling);
|
||||
const pendingUser = listPendingDiscoveredMcpServers(discoveredUserTooling);
|
||||
const acceptedProject = listAcceptedDiscoveredMcpServers(discoveredProjectTooling);
|
||||
const pendingProject = listPendingDiscoveredMcpServers(discoveredProjectTooling);
|
||||
|
||||
const hasAny = acceptedUser.length + pendingUser.length + acceptedProject.length + pendingProject.length > 0;
|
||||
const hasAny = acceptedUser.length + pendingUser.length > 0;
|
||||
|
||||
if (!hasAny) return null;
|
||||
|
||||
return (
|
||||
<div className="mt-8">
|
||||
<SectionHeader
|
||||
description="MCP servers discovered from project and user config files. Accepted servers are available for session tooling."
|
||||
description="MCP servers discovered from user config files. Accepted servers are available for session tooling."
|
||||
title="Discovered MCP Servers"
|
||||
>
|
||||
{onRescanProjectConfigs && (
|
||||
<button
|
||||
className="flex items-center gap-1.5 rounded-lg bg-zinc-800 px-3 py-1.5 text-[13px] font-medium text-zinc-200 transition hover:bg-zinc-700"
|
||||
onClick={onRescanProjectConfigs}
|
||||
title="Re-scan project config files"
|
||||
type="button"
|
||||
>
|
||||
<RefreshCw className="size-3.5" />
|
||||
Re-scan
|
||||
</button>
|
||||
)}
|
||||
</SectionHeader>
|
||||
/>
|
||||
|
||||
{/* User-level discovered */}
|
||||
{(acceptedUser.length > 0 || pendingUser.length > 0) && (
|
||||
<DiscoveredSubSection
|
||||
label="User-level"
|
||||
description="From ~/.copilot/mcp.json"
|
||||
accepted={acceptedUser}
|
||||
pending={pendingUser}
|
||||
onResolve={onResolveUserDiscoveredTooling}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Project-level discovered */}
|
||||
{(acceptedProject.length > 0 || pendingProject.length > 0) && (
|
||||
<DiscoveredSubSection
|
||||
label={selectedProjectName ? `Project: ${selectedProjectName}` : 'Project-level'}
|
||||
description="From .vscode/mcp.json, .mcp.json, or .copilot/mcp.json"
|
||||
accepted={acceptedProject}
|
||||
pending={pendingProject}
|
||||
onResolve={onResolveProjectDiscoveredTooling}
|
||||
/>
|
||||
)}
|
||||
<DiscoveredSubSection
|
||||
label="User-level"
|
||||
description="From ~/.copilot/mcp.json"
|
||||
accepted={acceptedUser}
|
||||
pending={pendingUser}
|
||||
onResolve={onResolveUserDiscoveredTooling}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -690,8 +720,8 @@ function DiscoveredSubSection({
|
||||
<div className="mb-4">
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<div>
|
||||
<span className="text-[12px] font-medium text-zinc-300">{label}</span>
|
||||
<p className="text-[11px] text-zinc-600">{description}</p>
|
||||
<span className="text-[12px] font-medium text-[var(--color-text-secondary)]">{label}</span>
|
||||
<p className="text-[11px] text-[var(--color-text-muted)]">{description}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
@@ -734,30 +764,30 @@ function DiscoveredServerRow({
|
||||
: server.url || 'No URL';
|
||||
|
||||
const statusBadge = status === 'accepted'
|
||||
? 'bg-emerald-500/10 text-emerald-400'
|
||||
: 'bg-amber-500/10 text-amber-400';
|
||||
? 'bg-[var(--color-status-success)]/10 text-[var(--color-status-success)]'
|
||||
: 'bg-[var(--color-status-warning)]/10 text-[var(--color-status-warning)]';
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-3 rounded-xl border border-transparent px-4 py-3 hover:border-zinc-800 hover:bg-zinc-900">
|
||||
<div className="flex items-center gap-3 rounded-xl border border-transparent px-4 py-3 hover:border-[var(--color-border)] hover:bg-[var(--color-surface-1)]">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="truncate text-[13px] font-medium text-zinc-200">{server.name}</span>
|
||||
<span className="rounded-full bg-zinc-800 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-zinc-400">
|
||||
<span className="truncate text-[13px] font-medium text-[var(--color-text-primary)]">{server.name}</span>
|
||||
<span className="rounded-full bg-[var(--color-surface-3)] px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-[var(--color-text-secondary)]">
|
||||
{server.transport}
|
||||
</span>
|
||||
<span className={`rounded-full px-2 py-0.5 text-[10px] font-medium ${statusBadge}`}>
|
||||
{status}
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-0.5 truncate text-[12px] text-zinc-500">
|
||||
<p className="mt-0.5 truncate text-[12px] text-[var(--color-text-muted)]">
|
||||
{detail}
|
||||
<span className="ml-2 text-zinc-700">· {server.sourceLabel}</span>
|
||||
<span className="ml-2 text-[var(--color-text-muted)]">· {server.sourceLabel}</span>
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
{onAccept && (
|
||||
<button
|
||||
className="rounded-lg px-2.5 py-1 text-[12px] font-medium text-emerald-400 transition hover:bg-emerald-500/10"
|
||||
className="rounded-lg px-2.5 py-1 text-[12px] font-medium text-[var(--color-status-success)] transition-all duration-200 hover:bg-[var(--color-status-success)]/10"
|
||||
onClick={onAccept}
|
||||
type="button"
|
||||
>
|
||||
@@ -766,7 +796,7 @@ function DiscoveredServerRow({
|
||||
)}
|
||||
{onDismiss && (
|
||||
<button
|
||||
className="rounded-lg px-2.5 py-1 text-[12px] font-medium text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300"
|
||||
className="rounded-lg px-2.5 py-1 text-[12px] font-medium text-[var(--color-text-muted)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]"
|
||||
onClick={onDismiss}
|
||||
type="button"
|
||||
>
|
||||
@@ -814,12 +844,12 @@ function TroubleshootingSection({
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mt-8 rounded-xl border border-red-500/20 bg-red-500/5 p-5">
|
||||
<div className="mt-8 rounded-xl border border-[var(--color-status-error)]/20 bg-[var(--color-status-error)]/5 p-5">
|
||||
<div className="flex items-start gap-3">
|
||||
<TriangleAlert className="mt-0.5 size-4 shrink-0 text-red-400" />
|
||||
<TriangleAlert className="mt-0.5 size-4 shrink-0 text-[var(--color-status-error)]" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<h4 className="text-[13px] font-semibold text-red-300">Reset Local Workspace</h4>
|
||||
<p className="mt-1 text-[12px] leading-relaxed text-zinc-400">
|
||||
<h4 className="text-[13px] font-semibold text-[var(--color-status-error)]">Reset Local Workspace</h4>
|
||||
<p className="mt-1 text-[12px] leading-relaxed text-[var(--color-text-secondary)]">
|
||||
Restore Aryx to its initial state. This permanently removes all sessions, custom patterns,
|
||||
MCP server definitions, LSP profiles, and scratchpad contents. Your GitHub Copilot sign-in
|
||||
is not affected.
|
||||
@@ -827,7 +857,7 @@ function TroubleshootingSection({
|
||||
|
||||
{!confirmingReset ? (
|
||||
<button
|
||||
className="mt-3 rounded-lg border border-red-500/30 bg-red-500/10 px-3.5 py-1.5 text-[13px] font-medium text-red-300 transition hover:border-red-500/50 hover:bg-red-500/20"
|
||||
className="mt-3 rounded-lg border border-[var(--color-status-error)]/30 bg-[var(--color-status-error)]/10 px-3.5 py-1.5 text-[13px] font-medium text-[var(--color-status-error)] transition-all duration-200 hover:border-[var(--color-status-error)]/50 hover:bg-[var(--color-status-error)]/20"
|
||||
onClick={() => setConfirmingReset(true)}
|
||||
type="button"
|
||||
>
|
||||
@@ -836,7 +866,7 @@ function TroubleshootingSection({
|
||||
) : (
|
||||
<div className="mt-3 flex items-center gap-2">
|
||||
<button
|
||||
className="rounded-lg bg-red-600 px-3.5 py-1.5 text-[13px] font-medium text-white transition hover:bg-red-500 disabled:opacity-50"
|
||||
className="rounded-lg bg-[var(--color-status-error)] px-3.5 py-1.5 text-[13px] font-medium text-white transition-all duration-200 hover:bg-[var(--color-status-error)] disabled:opacity-50"
|
||||
disabled={isResetting}
|
||||
onClick={() => void handleReset()}
|
||||
type="button"
|
||||
@@ -844,7 +874,7 @@ function TroubleshootingSection({
|
||||
{isResetting ? 'Resetting…' : 'Confirm reset'}
|
||||
</button>
|
||||
<button
|
||||
className="rounded-lg border border-[var(--color-border)] px-3.5 py-1.5 text-[13px] font-medium text-zinc-400 transition hover:bg-zinc-800 hover:text-zinc-200"
|
||||
className="rounded-lg border border-[var(--color-border)] px-3.5 py-1.5 text-[13px] font-medium text-[var(--color-text-secondary)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]"
|
||||
disabled={isResetting}
|
||||
onClick={() => setConfirmingReset(false)}
|
||||
type="button"
|
||||
@@ -873,16 +903,16 @@ function TroubleshootingAction({
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
className="group flex w-full items-center gap-3 rounded-xl border border-transparent px-4 py-3 text-left transition hover:border-zinc-800 hover:bg-zinc-900"
|
||||
className="group flex w-full items-center gap-3 rounded-xl border border-transparent px-4 py-3 text-left transition-all duration-200 hover:border-[var(--color-border)] hover:bg-[var(--color-surface-1)]"
|
||||
onClick={onClick}
|
||||
type="button"
|
||||
>
|
||||
<span className="text-zinc-500 transition group-hover:text-zinc-300">{icon}</span>
|
||||
<span className="text-[var(--color-text-muted)] transition-all duration-200 group-hover:text-[var(--color-text-secondary)]">{icon}</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<span className="text-[13px] font-medium text-zinc-200">{label}</span>
|
||||
<p className="mt-0.5 text-[12px] text-zinc-500">{description}</p>
|
||||
<span className="text-[13px] font-medium text-[var(--color-text-primary)]">{label}</span>
|
||||
<p className="mt-0.5 text-[12px] text-[var(--color-text-muted)]">{description}</p>
|
||||
</div>
|
||||
<ChevronRight className="size-4 text-zinc-700 transition group-hover:text-zinc-500" />
|
||||
<ChevronRight className="size-4 text-[var(--color-text-muted)] transition-all duration-200 group-hover:text-[var(--color-text-muted)]" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
RefreshCw,
|
||||
Search,
|
||||
Settings,
|
||||
Trash2,
|
||||
Users,
|
||||
X,
|
||||
type LucideIcon,
|
||||
@@ -41,22 +42,24 @@ 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;
|
||||
}
|
||||
|
||||
/* ── 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 ──────────────────────────────────── */
|
||||
@@ -80,7 +83,7 @@ function relativeTime(iso: string): string {
|
||||
function GitContextBadge({ git }: { git: ProjectGitContext }) {
|
||||
if (git.status === 'not-repository') {
|
||||
return (
|
||||
<span className="text-[10px] text-zinc-600" title="Not a git repository">
|
||||
<span className="text-[10px] text-[var(--color-text-muted)]" title="Not a git repository">
|
||||
no repo
|
||||
</span>
|
||||
);
|
||||
@@ -114,7 +117,7 @@ function GitContextBadge({ git }: { git: ProjectGitContext }) {
|
||||
if (git.behind) parts.push(`↓${git.behind}`);
|
||||
|
||||
return (
|
||||
<span className="flex items-center gap-1 text-[10px] text-zinc-500" title={parts.join(' · ') || branchLabel}>
|
||||
<span className="flex items-center gap-1 text-[10px] text-[var(--color-text-muted)]" title={parts.join(' · ') || branchLabel}>
|
||||
<GitBranch className="size-2.5 shrink-0" />
|
||||
<span className="max-w-[80px] truncate">{branchLabel}</span>
|
||||
{git.isDirty && <Circle className="size-1.5 shrink-0 fill-amber-500 text-amber-500" />}
|
||||
@@ -128,14 +131,16 @@ function ActionMenuItem({
|
||||
icon: Icon,
|
||||
label,
|
||||
onClick,
|
||||
className,
|
||||
}: {
|
||||
icon: LucideIcon;
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
className="flex w-full items-center gap-2 px-3 py-1.5 text-[12px] text-zinc-300 transition hover:bg-zinc-800"
|
||||
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"
|
||||
@@ -208,10 +213,10 @@ function SessionItem({
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`group relative flex w-full cursor-pointer items-start gap-2.5 rounded-lg px-2.5 py-2 text-left transition-all duration-150 ${
|
||||
className={`session-item-enter group relative flex w-full cursor-pointer items-start gap-2.5 rounded-lg px-2.5 py-2 text-left transition-all duration-200 ${
|
||||
isActive
|
||||
? 'bg-indigo-500/10 ring-1 ring-indigo-500/25'
|
||||
: 'hover:bg-zinc-800/60'
|
||||
? 'bg-[var(--color-accent-muted)] ring-1 ring-[var(--color-border-glow)]'
|
||||
: 'hover:bg-[var(--color-surface-2)]/60'
|
||||
} ${isRunning ? 'sidebar-running' : ''} ${session.isArchived ? 'opacity-50' : ''}`}
|
||||
onClick={isRenaming ? undefined : onSelect}
|
||||
role="button"
|
||||
@@ -220,19 +225,19 @@ function SessionItem({
|
||||
>
|
||||
{/* Running/approval left accent bar */}
|
||||
{isRunning && !hasPendingApproval && (
|
||||
<span className="absolute inset-y-1.5 left-0 w-[3px] rounded-full bg-blue-400 sidebar-pulse" />
|
||||
<span className="absolute inset-y-1.5 left-0 w-[3px] rounded-full accent-flow" />
|
||||
)}
|
||||
{hasPendingApproval && (
|
||||
<span className="absolute inset-y-1.5 left-0 w-[3px] rounded-full bg-amber-400" />
|
||||
<span className="absolute inset-y-1.5 left-0 w-[3px] rounded-full bg-[var(--color-status-warning)]" />
|
||||
)}
|
||||
|
||||
{/* Mode icon */}
|
||||
<span
|
||||
className={`mt-0.5 flex size-6 shrink-0 items-center justify-center rounded-md ${
|
||||
isActive ? 'bg-indigo-500/15' : 'bg-zinc-800/80'
|
||||
isActive ? 'bg-[var(--color-accent-muted)]' : 'bg-[var(--color-surface-2)]'
|
||||
}`}
|
||||
>
|
||||
<ModeIcon className={`size-3.5 ${isActive ? 'text-indigo-400' : visual.color}`} />
|
||||
<ModeIcon className={`size-3.5 ${isActive ? 'text-[var(--color-accent)]' : visual.color}`} />
|
||||
</span>
|
||||
|
||||
{/* Content */}
|
||||
@@ -242,7 +247,7 @@ function SessionItem({
|
||||
{isRenaming ? (
|
||||
<input
|
||||
ref={inputRef}
|
||||
className="w-full rounded bg-zinc-800 px-1.5 py-0.5 text-[13px] font-medium text-zinc-100 outline-none ring-1 ring-indigo-500/50"
|
||||
className="w-full rounded bg-[var(--color-surface-2)] px-1.5 py-0.5 text-[13px] font-medium text-[var(--color-text-primary)] outline-none ring-1 ring-[var(--color-border-glow)]"
|
||||
value={renameText}
|
||||
onChange={(e) => setRenameText(e.target.value)}
|
||||
onKeyDown={handleRenameKeyDown}
|
||||
@@ -252,7 +257,7 @@ function SessionItem({
|
||||
) : (
|
||||
<span
|
||||
className={`truncate text-[13px] font-medium leading-tight ${
|
||||
isActive ? 'text-indigo-100' : 'text-zinc-200 group-hover:text-zinc-100'
|
||||
isActive ? 'text-[var(--color-text-primary)]' : 'text-[var(--color-text-primary)] group-hover:text-[var(--color-text-primary)]'
|
||||
}`}
|
||||
>
|
||||
{session.title}
|
||||
@@ -262,36 +267,55 @@ function SessionItem({
|
||||
|
||||
<div className="mt-1 flex items-center gap-2">
|
||||
{agentCount > 1 && (
|
||||
<span className="inline-flex items-center gap-0.5 text-[10px] text-zinc-500">
|
||||
<span className="inline-flex items-center gap-0.5 text-[10px] text-[var(--color-text-muted)]">
|
||||
<Users className="size-2.5" />
|
||||
{agentCount}
|
||||
</span>
|
||||
)}
|
||||
{isRunning && !hasPendingApproval && (
|
||||
<span className="inline-flex items-center gap-1 text-[10px] font-medium text-blue-400">
|
||||
<span className="size-1.5 rounded-full bg-blue-400 sidebar-pulse" />
|
||||
<span className="inline-flex items-center gap-1 text-[10px] font-medium text-[var(--color-accent-sky)]">
|
||||
<span className="size-1.5 rounded-full bg-[var(--color-accent-sky)] sidebar-pulse" />
|
||||
Running
|
||||
</span>
|
||||
)}
|
||||
{hasPendingApproval && (
|
||||
<span className="inline-flex items-center gap-1 text-[10px] font-medium text-amber-400">
|
||||
<span className="size-1.5 rounded-full bg-amber-400 animate-pulse" />
|
||||
<span className="inline-flex items-center gap-1 text-[10px] font-medium text-[var(--color-status-warning)]">
|
||||
<span className="size-1.5 rounded-full bg-[var(--color-status-warning)] animate-pulse" />
|
||||
Awaiting approval{queuedCount > 0 && ` (+${queuedCount})`}
|
||||
</span>
|
||||
)}
|
||||
{isError && (
|
||||
<span className="inline-flex items-center gap-1 text-[10px] font-medium text-red-400">
|
||||
<span className="size-1.5 rounded-full bg-red-400" />
|
||||
<span className="inline-flex items-center gap-1 text-[10px] font-medium text-[var(--color-status-error)]">
|
||||
<span className="size-1.5 rounded-full bg-[var(--color-status-error)]" />
|
||||
Error
|
||||
</span>
|
||||
)}
|
||||
{session.isArchived && (
|
||||
<span className="inline-flex items-center gap-1 text-[10px] text-zinc-600">
|
||||
<span className="inline-flex items-center gap-1 text-[10px] text-[var(--color-text-muted)]">
|
||||
<Archive className="size-2.5" />
|
||||
Archived
|
||||
</span>
|
||||
)}
|
||||
<span className="ml-auto text-[10px] text-zinc-600 group-hover:text-zinc-500">
|
||||
{session.branchOrigin && (
|
||||
<span
|
||||
className="inline-flex items-center gap-0.5 text-[10px] text-[var(--color-text-muted)]"
|
||||
title={
|
||||
session.branchOrigin.action === 'regenerate'
|
||||
? 'Regenerated response'
|
||||
: session.branchOrigin.action === 'edit-and-resend'
|
||||
? 'Edited & resent'
|
||||
: 'Branched session'
|
||||
}
|
||||
>
|
||||
{session.branchOrigin.action === 'regenerate'
|
||||
? <RefreshCw className="size-2.5" />
|
||||
: session.branchOrigin.action === 'edit-and-resend'
|
||||
? <Pencil className="size-2.5" />
|
||||
: <GitBranch className="size-2.5" />
|
||||
}
|
||||
</span>
|
||||
)}
|
||||
<span className="ml-auto text-[10px] text-[var(--color-text-muted)] group-hover:text-[var(--color-text-secondary)]">
|
||||
{relativeTime(session.updatedAt)}
|
||||
</span>
|
||||
</div>
|
||||
@@ -300,7 +324,7 @@ function SessionItem({
|
||||
{/* Actions button (hidden during rename) */}
|
||||
{!isRenaming && (
|
||||
<button
|
||||
className="absolute right-1.5 top-1.5 flex size-6 items-center justify-center rounded-md text-zinc-600 opacity-0 transition hover:bg-zinc-700 hover:text-zinc-300 group-hover:opacity-100"
|
||||
className="absolute right-1.5 top-1.5 flex size-6 items-center justify-center rounded-md text-[var(--color-text-muted)] opacity-0 transition-all duration-150 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)] group-hover:opacity-100"
|
||||
onClick={(e) => { e.stopPropagation(); onOpenMenu(e); }}
|
||||
type="button"
|
||||
>
|
||||
@@ -324,6 +348,7 @@ function ProjectGroup({
|
||||
onRenameSubmit,
|
||||
onRenameCancel,
|
||||
onRefreshGitContext,
|
||||
onOpenProjectSettings,
|
||||
onNewSession,
|
||||
newSessionLabel,
|
||||
}: {
|
||||
@@ -337,6 +362,7 @@ function ProjectGroup({
|
||||
onRenameSubmit: (sessionId: string, title: string) => void;
|
||||
onRenameCancel: () => void;
|
||||
onRefreshGitContext?: (projectId: string) => void;
|
||||
onOpenProjectSettings?: (projectId: string) => void;
|
||||
onNewSession?: () => void;
|
||||
newSessionLabel?: string;
|
||||
}){
|
||||
@@ -369,19 +395,19 @@ function ProjectGroup({
|
||||
return (
|
||||
<div>
|
||||
<button
|
||||
className="group flex w-full items-center gap-2 rounded-lg px-2 py-2 text-left text-[13px] font-semibold text-zinc-400 transition hover:bg-zinc-800/40 hover:text-zinc-200"
|
||||
className="group flex w-full items-center gap-2 rounded-lg px-2 py-2 text-left text-[13px] font-semibold text-[var(--color-text-secondary)] transition-all duration-150 hover:bg-[var(--color-surface-2)]/40 hover:text-[var(--color-text-primary)]"
|
||||
onClick={() => setExpanded(!expanded)}
|
||||
type="button"
|
||||
>
|
||||
{expanded ? (
|
||||
<ChevronDown className="size-3 shrink-0 text-zinc-500" />
|
||||
<ChevronDown className="size-3 shrink-0 text-[var(--color-text-muted)]" />
|
||||
) : (
|
||||
<ChevronRight className="size-3 shrink-0 text-zinc-500" />
|
||||
<ChevronRight className="size-3 shrink-0 text-[var(--color-text-muted)]" />
|
||||
)}
|
||||
{isScratchpad ? (
|
||||
<MessageSquare className="size-3.5 shrink-0 text-zinc-500 transition group-hover:text-indigo-400" />
|
||||
<MessageSquare className="size-3.5 shrink-0 text-[var(--color-text-muted)] transition group-hover:text-[var(--color-accent)]" />
|
||||
) : (
|
||||
<FolderOpen className="size-3.5 shrink-0 text-zinc-500 transition group-hover:text-indigo-400" />
|
||||
<FolderOpen className="size-3.5 shrink-0 text-[var(--color-text-muted)] transition group-hover:text-[var(--color-accent)]" />
|
||||
)}
|
||||
<span className="truncate">{project.name}</span>
|
||||
|
||||
@@ -390,9 +416,22 @@ function ProjectGroup({
|
||||
)}
|
||||
|
||||
<div className="ml-auto flex items-center gap-1.5">
|
||||
{!isScratchpad && onOpenProjectSettings && (
|
||||
<span
|
||||
className="flex size-5 items-center justify-center rounded text-[var(--color-text-muted)] opacity-0 transition hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)] group-hover:opacity-100"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onOpenProjectSettings(project.id);
|
||||
}}
|
||||
role="button"
|
||||
title="Project settings"
|
||||
>
|
||||
<Settings className="size-3" />
|
||||
</span>
|
||||
)}
|
||||
{!isScratchpad && onRefreshGitContext && (
|
||||
<span
|
||||
className="flex size-5 items-center justify-center rounded text-zinc-600 opacity-0 transition hover:bg-zinc-700 hover:text-zinc-300 group-hover:opacity-100"
|
||||
className="flex size-5 items-center justify-center rounded text-[var(--color-text-muted)] opacity-0 transition hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)] group-hover:opacity-100"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onRefreshGitContext(project.id);
|
||||
@@ -404,27 +443,32 @@ function ProjectGroup({
|
||||
</span>
|
||||
)}
|
||||
{runningCount > 0 && (
|
||||
<span className="flex items-center gap-1 rounded-full bg-blue-500/10 px-1.5 py-0.5 text-[10px] font-medium text-blue-400">
|
||||
<span className="size-1.5 rounded-full bg-blue-400 sidebar-pulse" />
|
||||
<span className="flex items-center gap-1 rounded-full bg-[var(--color-accent-sky)]/10 px-1.5 py-0.5 text-[10px] font-medium text-[var(--color-accent-sky)]">
|
||||
<span className="size-1.5 rounded-full bg-[var(--color-accent-sky)] sidebar-pulse" />
|
||||
{runningCount}
|
||||
</span>
|
||||
)}
|
||||
{pendingDiscoveryCount > 0 && (
|
||||
<span
|
||||
className="flex items-center gap-1 rounded-full bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-medium text-amber-400"
|
||||
title={`${pendingDiscoveryCount} MCP server${pendingDiscoveryCount === 1 ? '' : 's'} discovered`}
|
||||
className="flex cursor-pointer items-center gap-1 rounded-full bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-medium text-amber-400 transition hover:bg-amber-500/20"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onOpenProjectSettings?.(project.id);
|
||||
}}
|
||||
role="button"
|
||||
title={`${pendingDiscoveryCount} MCP server${pendingDiscoveryCount === 1 ? '' : 's'} discovered — click to review`}
|
||||
>
|
||||
{pendingDiscoveryCount} new
|
||||
</span>
|
||||
)}
|
||||
<span className="rounded-full bg-zinc-800 px-1.5 py-0.5 text-[10px] font-medium text-zinc-500">
|
||||
<span className="rounded-full bg-[var(--color-surface-2)] px-1.5 py-0.5 text-[10px] font-medium text-[var(--color-text-muted)]">
|
||||
{visibleSessions.length}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{expanded && (
|
||||
<div className="ml-2 mt-0.5 space-y-0.5 border-l border-zinc-800/60 pl-2">
|
||||
<div className="ml-2 mt-0.5 space-y-0.5 border-l border-[var(--color-border-subtle)] pl-2">
|
||||
{visibleSessions.length > 0 &&
|
||||
visibleSessions.map((session) => (
|
||||
<SessionItem
|
||||
@@ -441,7 +485,7 @@ function ProjectGroup({
|
||||
))}
|
||||
{onNewSession ? (
|
||||
<button
|
||||
className="flex w-full items-center justify-center gap-1.5 rounded-md border border-dashed border-zinc-700/60 bg-zinc-800/20 px-2.5 py-1.5 text-[12px] font-medium text-zinc-500 transition hover:border-indigo-500/40 hover:bg-indigo-500/5 hover:text-indigo-300"
|
||||
className="flex w-full items-center justify-center gap-1.5 rounded-md border border-dashed border-[var(--color-border)] bg-[var(--color-surface-1)]/40 px-2.5 py-1.5 text-[12px] font-medium text-[var(--color-text-muted)] transition-all duration-200 hover:border-[var(--color-border-glow)] hover:bg-[var(--color-accent-muted)] hover:text-[var(--color-accent)]"
|
||||
onClick={onNewSession}
|
||||
type="button"
|
||||
>
|
||||
@@ -450,7 +494,7 @@ function ProjectGroup({
|
||||
</button>
|
||||
) : (
|
||||
visibleSessions.length === 0 && (
|
||||
<div className="px-3 py-3 text-center text-[12px] text-zinc-600">
|
||||
<div className="px-3 py-3 text-center text-[12px] text-[var(--color-text-muted)]">
|
||||
{isScratchpad ? 'No scratchpad chats yet' : 'No sessions yet'}
|
||||
</div>
|
||||
)
|
||||
@@ -471,10 +515,12 @@ export function Sidebar({
|
||||
onProjectSelect,
|
||||
onSessionSelect,
|
||||
onOpenSettings,
|
||||
onOpenProjectSettings,
|
||||
onRenameSession,
|
||||
onDuplicateSession,
|
||||
onSetSessionPinned,
|
||||
onSetSessionArchived,
|
||||
onDeleteSession,
|
||||
onRefreshGitContext,
|
||||
}: SidebarProps) {
|
||||
const scratchpadProject = workspace.projects.find((project) => isScratchpadProject(project));
|
||||
@@ -535,19 +581,19 @@ export function Sidebar({
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
{/* Header — extra top padding clears the title bar overlay zone */}
|
||||
<div className="drag-region flex items-center justify-between border-b border-[var(--color-border)] px-4 pb-3 pt-3">
|
||||
<div className="drag-region flex items-center justify-between border-b border-[var(--color-border-subtle)] px-4 pb-3 pt-3">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<img alt="aryx" className="size-8 rounded-xl" src={appIconUrl} />
|
||||
<div>
|
||||
<span className="text-sm font-semibold text-zinc-100">aryx</span>
|
||||
<span className="ml-1.5 rounded bg-zinc-800 px-1 py-0.5 text-[9px] font-medium text-zinc-500">
|
||||
<span className="font-display text-sm font-semibold text-[var(--color-text-primary)]">aryx</span>
|
||||
<span className="ml-1.5 rounded bg-[var(--color-surface-2)] px-1 py-0.5 text-[9px] font-medium text-[var(--color-text-muted)]">
|
||||
ALPHA
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
className="no-drag flex size-8 items-center justify-center rounded-lg text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300"
|
||||
className="no-drag flex size-8 items-center justify-center rounded-lg text-[var(--color-text-muted)] transition-all duration-150 hover:bg-[var(--color-surface-2)] hover:text-[var(--color-text-primary)]"
|
||||
onClick={onOpenSettings}
|
||||
title="Settings"
|
||||
type="button"
|
||||
@@ -560,16 +606,16 @@ export function Sidebar({
|
||||
{/* Search + Filters */}
|
||||
<div className="space-y-2 px-3 pt-3 pb-1">
|
||||
<div className="relative">
|
||||
<Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-zinc-500" />
|
||||
<Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-[var(--color-text-muted)]" />
|
||||
<input
|
||||
className="w-full rounded-lg border border-zinc-800 bg-zinc-900/60 py-1.5 pl-8 pr-8 text-[12px] text-zinc-200 placeholder-zinc-600 outline-none transition focus:border-zinc-700 focus:bg-zinc-900"
|
||||
className="w-full rounded-xl border border-[var(--color-border)] bg-[var(--color-surface-0)]/60 py-1.5 pl-8 pr-8 text-[12px] text-[var(--color-text-primary)] placeholder-[var(--color-text-muted)] outline-none transition-all duration-200 focus:border-[var(--color-border-glow)] focus:bg-[var(--color-surface-0)] focus:shadow-[0_0_12px_rgba(36,92,249,0.06)]"
|
||||
placeholder="Search sessions…"
|
||||
value={searchText}
|
||||
onChange={(e) => setSearchText(e.target.value)}
|
||||
/>
|
||||
{searchText && (
|
||||
<button
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-zinc-500 hover:text-zinc-300"
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-[var(--color-text-muted)] hover:text-[var(--color-text-primary)]"
|
||||
onClick={() => setSearchText('')}
|
||||
type="button"
|
||||
>
|
||||
@@ -588,11 +634,11 @@ export function Sidebar({
|
||||
{isQueryActive ? (
|
||||
/* ── Flat search / filter results ──────────────────────── */
|
||||
<div className="space-y-1">
|
||||
<div className="px-2 text-[10px] font-semibold uppercase tracking-[0.12em] text-zinc-600">
|
||||
<div className="px-2 text-[10px] font-semibold uppercase tracking-[0.12em] text-[var(--color-text-muted)]">
|
||||
Results ({queryResults.length})
|
||||
</div>
|
||||
{queryResults.length === 0 ? (
|
||||
<div className="px-3 py-6 text-center text-[12px] text-zinc-600">
|
||||
<div className="px-3 py-6 text-center text-[12px] text-[var(--color-text-muted)]">
|
||||
No sessions match your search
|
||||
</div>
|
||||
) : (
|
||||
@@ -616,7 +662,7 @@ export function Sidebar({
|
||||
<div className="space-y-3">
|
||||
{scratchpadProject && (
|
||||
<div className="space-y-1">
|
||||
<div className="px-2 text-[10px] font-semibold uppercase tracking-[0.12em] text-zinc-600">
|
||||
<div className="px-2 text-[10px] font-semibold uppercase tracking-[0.12em] text-[var(--color-text-muted)]">
|
||||
Scratchpad
|
||||
</div>
|
||||
<ProjectGroup
|
||||
@@ -639,21 +685,21 @@ export function Sidebar({
|
||||
{userProjects.length === 0 ? (
|
||||
<div className="flex flex-col items-center gap-4 px-4 py-8 text-center">
|
||||
<div className="relative">
|
||||
<div className="flex size-14 items-center justify-center rounded-2xl bg-zinc-800/50 ring-1 ring-zinc-700/50">
|
||||
<FolderOpen className="size-7 text-zinc-600" />
|
||||
<div className="flex size-14 items-center justify-center rounded-2xl bg-[var(--color-surface-2)] ring-1 ring-[var(--color-border)]">
|
||||
<FolderOpen className="size-7 text-[var(--color-text-muted)]" />
|
||||
</div>
|
||||
<div className="absolute -bottom-1 -right-1 flex size-6 items-center justify-center rounded-full bg-indigo-600 ring-2 ring-[var(--color-surface-1)]">
|
||||
<div className="absolute -bottom-1 -right-1 flex size-6 items-center justify-center rounded-full brand-gradient-bg ring-2 ring-[var(--color-surface-1)]">
|
||||
<Plus className="size-3 text-white" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-[13px] font-medium text-zinc-300">No projects yet</p>
|
||||
<p className="mt-1 text-[12px] leading-relaxed text-zinc-500">
|
||||
<p className="text-[13px] font-medium text-[var(--color-text-primary)]">No projects yet</p>
|
||||
<p className="mt-1 text-[12px] leading-relaxed text-[var(--color-text-muted)]">
|
||||
Use Scratchpad for ad-hoc chat or add a repo<br />to work against project files
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
className="rounded-lg bg-indigo-600 px-4 py-2 text-[13px] font-medium text-white transition hover:bg-indigo-500"
|
||||
className="rounded-lg brand-gradient-bg px-4 py-2 text-[13px] font-medium text-white shadow-[0_2px_12px_rgba(36,92,249,0.25)] transition-all duration-200 hover:shadow-[0_4px_20px_rgba(36,92,249,0.35)]"
|
||||
onClick={onAddProject}
|
||||
type="button"
|
||||
>
|
||||
@@ -662,7 +708,7 @@ export function Sidebar({
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
<div className="px-2 text-[10px] font-semibold uppercase tracking-[0.12em] text-zinc-600">
|
||||
<div className="px-2 text-[10px] font-semibold uppercase tracking-[0.12em] text-[var(--color-text-muted)]">
|
||||
Projects
|
||||
</div>
|
||||
{userProjects.map((project) => (
|
||||
@@ -673,6 +719,7 @@ export function Sidebar({
|
||||
onRenameSubmit={handleRenameSubmit}
|
||||
onRenameCancel={() => setRenamingSessionId(undefined)}
|
||||
onRefreshGitContext={onRefreshGitContext}
|
||||
onOpenProjectSettings={onOpenProjectSettings}
|
||||
renamingSessionId={renamingSessionId}
|
||||
patterns={workspace.patterns}
|
||||
project={project}
|
||||
@@ -689,9 +736,9 @@ export function Sidebar({
|
||||
|
||||
{/* Footer */}
|
||||
{userProjects.length > 0 && (
|
||||
<div className="border-t border-[var(--color-border)] px-3 py-2">
|
||||
<div className="border-t border-[var(--color-border-subtle)] px-3 py-2">
|
||||
<button
|
||||
className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-[12px] text-zinc-500 transition hover:bg-zinc-800/60 hover:text-zinc-300"
|
||||
className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-[12px] text-[var(--color-text-muted)] transition-all duration-150 hover:bg-[var(--color-surface-2)]/60 hover:text-[var(--color-text-primary)]"
|
||||
onClick={onAddProject}
|
||||
type="button"
|
||||
>
|
||||
@@ -706,7 +753,7 @@ export function Sidebar({
|
||||
<>
|
||||
<div className="fixed inset-0 z-40" onClick={closeMenu} onKeyDown={(e) => { if (e.key === 'Escape') closeMenu(); }} />
|
||||
<div
|
||||
className="fixed z-50 w-40 rounded-lg border border-zinc-700 bg-zinc-900 py-1 shadow-xl"
|
||||
className="fixed z-50 w-40 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] py-1 shadow-[0_8px_32px_rgba(0,0,0,0.4)]"
|
||||
role="menu"
|
||||
style={{ top: menuState.top, left: menuState.left }}
|
||||
>
|
||||
@@ -742,6 +789,15 @@ export function Sidebar({
|
||||
closeMenu();
|
||||
}}
|
||||
/>
|
||||
<ActionMenuItem
|
||||
className="text-[var(--color-status-error)] hover:bg-[var(--color-status-error)]/10"
|
||||
icon={Trash2}
|
||||
label="Delete"
|
||||
onClick={() => {
|
||||
onDeleteSession(menuState.sessionId);
|
||||
closeMenu();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { RotateCcw, Minus, X } from 'lucide-react';
|
||||
import { Terminal } from '@xterm/xterm';
|
||||
import { FitAddon } from '@xterm/addon-fit';
|
||||
import '@xterm/xterm/css/xterm.css';
|
||||
|
||||
import { getElectronApi } from '@renderer/lib/electronApi';
|
||||
import type { TerminalSnapshot } from '@shared/domain/terminal';
|
||||
import type { TerminalExitInfo } from '@shared/domain/terminal';
|
||||
|
||||
/* ── Theme ────────────────────────────────────────────────── */
|
||||
|
||||
const terminalTheme = {
|
||||
background: '#07080e',
|
||||
foreground: '#e8eaf0',
|
||||
cursor: '#245CF9',
|
||||
cursorAccent: '#07080e',
|
||||
selectionBackground: 'rgba(36, 92, 249, 0.2)',
|
||||
selectionForeground: '#e8eaf0',
|
||||
black: '#1e2233',
|
||||
red: '#f87171',
|
||||
green: '#4ade80',
|
||||
yellow: '#facc15',
|
||||
blue: '#248CFD',
|
||||
magenta: '#a855f7',
|
||||
cyan: '#22d3ee',
|
||||
white: '#e8eaf0',
|
||||
brightBlack: '#4e5368',
|
||||
brightRed: '#fca5a5',
|
||||
brightGreen: '#86efac',
|
||||
brightYellow: '#fde047',
|
||||
brightBlue: '#60a5fa',
|
||||
brightMagenta: '#c084fc',
|
||||
brightCyan: '#67e8f9',
|
||||
brightWhite: '#f8f9fc',
|
||||
};
|
||||
|
||||
/* ── Constants ────────────────────────────────────────────── */
|
||||
|
||||
const MIN_HEIGHT = 120;
|
||||
const MAX_HEIGHT_FRACTION = 0.7;
|
||||
const DEFAULT_HEIGHT = 280;
|
||||
|
||||
/* ── TerminalPanel ────────────────────────────────────────── */
|
||||
|
||||
interface TerminalPanelProps {
|
||||
height: number;
|
||||
onHeightChange: (height: number) => void;
|
||||
onClose: () => void;
|
||||
onMinimize: () => void;
|
||||
}
|
||||
|
||||
export function TerminalPanel({
|
||||
height,
|
||||
onHeightChange,
|
||||
onClose,
|
||||
onMinimize,
|
||||
}: TerminalPanelProps) {
|
||||
const api = getElectronApi();
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const terminalRef = useRef<Terminal | null>(null);
|
||||
const fitAddonRef = useRef<FitAddon | null>(null);
|
||||
const [snapshot, setSnapshot] = useState<TerminalSnapshot>();
|
||||
const [isRunning, setIsRunning] = useState(false);
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
const dragStartRef = useRef<{ y: number; height: number } | null>(null);
|
||||
|
||||
// Create or recover terminal on mount
|
||||
useEffect(() => {
|
||||
let disposed = false;
|
||||
|
||||
void api.describeTerminal().then((existing) => {
|
||||
if (disposed) return;
|
||||
if (existing) {
|
||||
setSnapshot(existing);
|
||||
setIsRunning(true);
|
||||
} else {
|
||||
void api.createTerminal().then((created) => {
|
||||
if (disposed) return;
|
||||
setSnapshot(created);
|
||||
setIsRunning(true);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
};
|
||||
}, [api]);
|
||||
|
||||
// Initialize xterm.js
|
||||
useEffect(() => {
|
||||
if (!containerRef.current) return;
|
||||
|
||||
const terminal = new Terminal({
|
||||
theme: terminalTheme,
|
||||
fontFamily: '"JetBrains Mono Variable", "JetBrains Mono", ui-monospace, "SF Mono", Menlo, monospace',
|
||||
fontSize: 13,
|
||||
lineHeight: 1.4,
|
||||
cursorBlink: true,
|
||||
cursorStyle: 'bar',
|
||||
scrollback: 5000,
|
||||
allowProposedApi: true,
|
||||
});
|
||||
const fitAddon = new FitAddon();
|
||||
terminal.loadAddon(fitAddon);
|
||||
terminal.open(containerRef.current);
|
||||
|
||||
terminalRef.current = terminal;
|
||||
fitAddonRef.current = fitAddon;
|
||||
|
||||
// Send keystrokes to the backend
|
||||
const dataDisposable = terminal.onData((data) => {
|
||||
api.writeTerminal(data);
|
||||
});
|
||||
|
||||
// Initial fit
|
||||
requestAnimationFrame(() => {
|
||||
fitAddon.fit();
|
||||
api.resizeTerminal({ cols: terminal.cols, rows: terminal.rows });
|
||||
});
|
||||
|
||||
return () => {
|
||||
dataDisposable.dispose();
|
||||
terminal.dispose();
|
||||
terminalRef.current = null;
|
||||
fitAddonRef.current = null;
|
||||
};
|
||||
}, [api]);
|
||||
|
||||
// Subscribe to terminal data and exit events
|
||||
useEffect(() => {
|
||||
const offData = api.onTerminalData((data) => {
|
||||
terminalRef.current?.write(data);
|
||||
});
|
||||
const offExit = api.onTerminalExit((_info: TerminalExitInfo) => {
|
||||
setIsRunning(false);
|
||||
terminalRef.current?.write('\r\n\x1b[90m[Process exited]\x1b[0m\r\n');
|
||||
});
|
||||
|
||||
return () => {
|
||||
offData();
|
||||
offExit();
|
||||
};
|
||||
}, [api]);
|
||||
|
||||
// Refit on height changes
|
||||
useEffect(() => {
|
||||
if (!fitAddonRef.current || !terminalRef.current) return;
|
||||
requestAnimationFrame(() => {
|
||||
fitAddonRef.current?.fit();
|
||||
const terminal = terminalRef.current;
|
||||
if (terminal) {
|
||||
api.resizeTerminal({ cols: terminal.cols, rows: terminal.rows });
|
||||
}
|
||||
});
|
||||
}, [height, api]);
|
||||
|
||||
// ResizeObserver for container width changes
|
||||
useEffect(() => {
|
||||
const container = containerRef.current;
|
||||
if (!container) return;
|
||||
|
||||
const observer = new ResizeObserver(() => {
|
||||
requestAnimationFrame(() => {
|
||||
fitAddonRef.current?.fit();
|
||||
const terminal = terminalRef.current;
|
||||
if (terminal) {
|
||||
api.resizeTerminal({ cols: terminal.cols, rows: terminal.rows });
|
||||
}
|
||||
});
|
||||
});
|
||||
observer.observe(container);
|
||||
return () => observer.disconnect();
|
||||
}, [api]);
|
||||
|
||||
// Drag-to-resize
|
||||
const handleDragStart = useCallback((e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
dragStartRef.current = { y: e.clientY, height };
|
||||
setIsDragging(true);
|
||||
|
||||
const handleDragMove = (moveEvent: MouseEvent) => {
|
||||
if (!dragStartRef.current) return;
|
||||
const maxHeight = window.innerHeight * MAX_HEIGHT_FRACTION;
|
||||
const delta = dragStartRef.current.y - moveEvent.clientY;
|
||||
const nextHeight = Math.max(MIN_HEIGHT, Math.min(maxHeight, dragStartRef.current.height + delta));
|
||||
onHeightChange(nextHeight);
|
||||
};
|
||||
|
||||
const handleDragEnd = () => {
|
||||
setIsDragging(false);
|
||||
dragStartRef.current = null;
|
||||
document.removeEventListener('mousemove', handleDragMove);
|
||||
document.removeEventListener('mouseup', handleDragEnd);
|
||||
};
|
||||
|
||||
document.addEventListener('mousemove', handleDragMove);
|
||||
document.addEventListener('mouseup', handleDragEnd);
|
||||
}, [height, onHeightChange]);
|
||||
|
||||
const handleRestart = useCallback(() => {
|
||||
void api.restartTerminal().then((restarted) => {
|
||||
setSnapshot(restarted);
|
||||
setIsRunning(true);
|
||||
terminalRef.current?.clear();
|
||||
});
|
||||
}, [api]);
|
||||
|
||||
const handleClose = useCallback(() => {
|
||||
void api.killTerminal();
|
||||
onClose();
|
||||
}, [api, onClose]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex flex-col border-t border-[var(--color-border)] bg-[var(--color-surface-0)]"
|
||||
style={{ height, minHeight: MIN_HEIGHT }}
|
||||
>
|
||||
{/* Resize handle */}
|
||||
<div
|
||||
className={`h-1 shrink-0 cursor-row-resize transition-colors ${isDragging ? 'bg-[var(--color-accent)]/40' : 'hover:bg-[var(--color-surface-3)]/60'}`}
|
||||
onMouseDown={handleDragStart}
|
||||
role="separator"
|
||||
aria-orientation="horizontal"
|
||||
aria-label="Resize terminal"
|
||||
tabIndex={0}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
onHeightChange(Math.min(window.innerHeight * MAX_HEIGHT_FRACTION, height + 20));
|
||||
} else if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
onHeightChange(Math.max(MIN_HEIGHT, height - 20));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Header bar */}
|
||||
<div className="flex h-7 shrink-0 items-center gap-2 border-b border-[var(--color-border)] px-3">
|
||||
<span className={`size-1.5 shrink-0 rounded-full ${isRunning ? 'bg-emerald-400' : 'bg-[var(--color-text-muted)]'}`} />
|
||||
<span className="min-w-0 flex-1 truncate font-mono text-[11px] text-[var(--color-text-muted)]">
|
||||
{snapshot ? `${snapshot.shell} — ${snapshot.cwd}` : 'Terminal'}
|
||||
</span>
|
||||
<div className="flex items-center gap-0.5">
|
||||
<button
|
||||
aria-label="Restart terminal"
|
||||
className="rounded p-0.5 text-[var(--color-text-muted)] transition hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]"
|
||||
onClick={handleRestart}
|
||||
type="button"
|
||||
>
|
||||
<RotateCcw className="size-3" />
|
||||
</button>
|
||||
<button
|
||||
aria-label="Minimize terminal"
|
||||
className="rounded p-0.5 text-[var(--color-text-muted)] transition hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]"
|
||||
onClick={onMinimize}
|
||||
type="button"
|
||||
>
|
||||
<Minus className="size-3" />
|
||||
</button>
|
||||
<button
|
||||
aria-label="Close terminal"
|
||||
className="rounded p-0.5 text-[var(--color-text-muted)] transition hover:bg-[var(--color-surface-3)] hover:text-red-400"
|
||||
onClick={handleClose}
|
||||
type="button"
|
||||
>
|
||||
<X className="size-3" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Terminal body */}
|
||||
<div
|
||||
className="min-h-0 flex-1 px-1 py-0.5"
|
||||
ref={containerRef}
|
||||
role="application"
|
||||
aria-label="Terminal"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export { DEFAULT_HEIGHT, MIN_HEIGHT };
|
||||
@@ -1,61 +1,218 @@
|
||||
import { MessageSquare, Plus, Settings } from 'lucide-react';
|
||||
import { CheckCircle2, Circle, FolderPlus, MessageSquarePlus, Settings, Zap } from 'lucide-react';
|
||||
import { motion } from 'motion/react';
|
||||
|
||||
import type { SidecarConnectionStatus } from '@shared/contracts/sidecar';
|
||||
import appIconUrl from '../../../assets/icons/icon.png';
|
||||
|
||||
interface WelcomePaneProps {
|
||||
hasProjects: boolean;
|
||||
connectionStatus?: SidecarConnectionStatus;
|
||||
onNewScratchpad: () => void;
|
||||
onAddProject: () => void;
|
||||
onOpenSettings: () => void;
|
||||
}
|
||||
|
||||
const fadeUp = (delay: number) =>
|
||||
({
|
||||
initial: { opacity: 0, y: 12 },
|
||||
animate: { opacity: 1, y: 0 },
|
||||
transition: { duration: 0.45, ease: [0.25, 0.46, 0.45, 0.94] as const, delay },
|
||||
}) as const;
|
||||
|
||||
interface ActionCardProps {
|
||||
icon: React.ReactNode;
|
||||
title: string;
|
||||
description: string;
|
||||
onClick: () => void;
|
||||
highlight?: boolean;
|
||||
}
|
||||
|
||||
function ActionCard({ icon, title, description, onClick, highlight }: ActionCardProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className={`group flex w-full cursor-pointer items-center gap-4 rounded-xl border px-5 py-4 text-left backdrop-blur-sm transition-all duration-200 ${
|
||||
highlight
|
||||
? 'border-[var(--color-border-glow)] bg-[var(--color-accent-muted)] shadow-[0_0_24px_rgba(36,92,249,0.1)] hover:shadow-[0_0_32px_rgba(36,92,249,0.15)]'
|
||||
: 'border-[var(--color-glass-border)] bg-[var(--color-glass)] hover:border-[var(--color-border-glow)] hover:shadow-[0_0_20px_rgba(36,92,249,0.08),0_4px_12px_rgba(0,0,0,0.2)]'
|
||||
}`}
|
||||
>
|
||||
<div className="brand-gradient-bg flex size-9 shrink-0 items-center justify-center rounded-full">
|
||||
{icon}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<span className="block text-[13px] font-medium text-[var(--color-text-primary)]">
|
||||
{title}
|
||||
</span>
|
||||
<span className="block text-[12px] leading-relaxed text-[var(--color-text-muted)]">
|
||||
{description}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
interface SetupStepProps {
|
||||
label: string;
|
||||
done: boolean;
|
||||
active?: boolean;
|
||||
}
|
||||
|
||||
function SetupStep({ label, done, active }: SetupStepProps) {
|
||||
return (
|
||||
<div className={`flex items-center gap-2 text-[12px] ${active ? 'text-[var(--color-text-primary)]' : 'text-[var(--color-text-muted)]'}`}>
|
||||
{done
|
||||
? <CheckCircle2 className="size-3.5 text-[var(--color-status-success)]" />
|
||||
: <Circle className={`size-3.5 ${active ? 'text-[var(--color-accent)]' : 'text-[var(--color-text-muted)]'}`} />
|
||||
}
|
||||
<span className={done ? 'line-through opacity-60' : ''}>{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function WelcomePane({
|
||||
hasProjects,
|
||||
connectionStatus,
|
||||
onNewScratchpad,
|
||||
onAddProject,
|
||||
onOpenSettings,
|
||||
}: WelcomePaneProps) {
|
||||
const isConnected = connectionStatus === 'ready';
|
||||
const isFirstRun = !hasProjects;
|
||||
|
||||
// Determine setup progress
|
||||
const steps = [
|
||||
{ label: 'GitHub Copilot connected', done: isConnected },
|
||||
{ label: 'First project added', done: hasProjects },
|
||||
];
|
||||
const completedSteps = steps.filter((s) => s.done).length;
|
||||
const allDone = completedSteps === steps.length;
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center px-8">
|
||||
<div className="flex flex-col items-center gap-6 text-center">
|
||||
<div className="flex size-16 items-center justify-center rounded-2xl bg-indigo-600/10">
|
||||
<MessageSquare className="size-8 text-indigo-400" />
|
||||
</div>
|
||||
<div className="relative flex h-full flex-col items-center justify-center overflow-hidden px-8">
|
||||
{/* Ambient nebula glow */}
|
||||
<div
|
||||
className="pointer-events-none absolute inset-0"
|
||||
aria-hidden="true"
|
||||
style={{
|
||||
background: [
|
||||
'radial-gradient(ellipse 50% 40% at 50% 45%, rgba(36, 92, 249, 0.07) 0%, transparent 70%)',
|
||||
'radial-gradient(ellipse 40% 35% at 55% 50%, rgba(138, 41, 230, 0.05) 0%, transparent 65%)',
|
||||
'radial-gradient(ellipse 60% 50% at 45% 48%, rgba(54, 21, 207, 0.04) 0%, transparent 60%)',
|
||||
].join(', '),
|
||||
}}
|
||||
/>
|
||||
|
||||
<div>
|
||||
<h1 className="text-base font-semibold text-zinc-100">Welcome to aryx</h1>
|
||||
<p className="mt-2 max-w-md text-[13px] leading-relaxed text-zinc-500">
|
||||
Start a scratchpad conversation for ad-hoc questions or connect a project to work with
|
||||
repo-aware Copilot agents.
|
||||
<div className="relative z-10 flex w-full max-w-sm flex-col items-center gap-6 text-center">
|
||||
{/* Icon */}
|
||||
<motion.div {...fadeUp(0)}>
|
||||
<img
|
||||
src={appIconUrl}
|
||||
alt="aryx"
|
||||
width={64}
|
||||
height={64}
|
||||
className="drop-shadow-[0_0_24px_rgba(36,92,249,0.3)]"
|
||||
/>
|
||||
</motion.div>
|
||||
|
||||
{/* Heading */}
|
||||
<motion.div {...fadeUp(0.08)}>
|
||||
<h1 className="font-display brand-gradient-text text-2xl font-bold tracking-tight">
|
||||
{isFirstRun ? 'Welcome to Aryx' : 'aryx'}
|
||||
</h1>
|
||||
<p className="mt-2 max-w-sm text-[13px] leading-relaxed text-[var(--color-text-secondary)]">
|
||||
{isFirstRun
|
||||
? 'Your AI workspace powered by GitHub Copilot. Start a scratchpad for quick questions or connect a project for full agent support.'
|
||||
: 'Start a scratchpad conversation for ad-hoc questions or connect a project to work with repo-aware Copilot agents.'
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<button
|
||||
className="flex items-center gap-2 rounded-lg bg-indigo-600 px-5 py-2.5 text-[13px] font-medium text-white transition hover:bg-indigo-500"
|
||||
onClick={onNewScratchpad}
|
||||
type="button"
|
||||
>
|
||||
<Plus className="size-4" />
|
||||
New Scratchpad
|
||||
</button>
|
||||
{!hasProjects && (
|
||||
<button
|
||||
className="flex items-center gap-2 rounded-lg px-4 py-2 text-[13px] text-zinc-500 transition hover:bg-zinc-900 hover:text-zinc-300"
|
||||
onClick={onAddProject}
|
||||
type="button"
|
||||
>
|
||||
<Plus className="size-3.5" />
|
||||
Add Your First Project
|
||||
</button>
|
||||
{/* Setup progress — only for first-run */}
|
||||
{isFirstRun && !allDone && (
|
||||
<motion.div {...fadeUp(0.12)} className="w-full rounded-xl border border-[var(--color-border)] bg-[var(--color-surface-1)]/60 p-4">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<span className="text-[11px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
|
||||
Getting started
|
||||
</span>
|
||||
<span className="text-[11px] text-[var(--color-text-muted)]">
|
||||
{completedSteps}/{steps.length}
|
||||
</span>
|
||||
</div>
|
||||
{/* Progress bar */}
|
||||
<div className="mb-3 h-1 overflow-hidden rounded-full bg-[var(--color-surface-3)]">
|
||||
<motion.div
|
||||
className="h-full rounded-full bg-gradient-to-r from-[var(--color-accent)] to-[var(--color-accent-purple)]"
|
||||
initial={{ width: 0 }}
|
||||
animate={{ width: `${(completedSteps / steps.length) * 100}%` }}
|
||||
transition={{ duration: 0.6, ease: 'easeOut', delay: 0.3 }}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{steps.map((step, i) => (
|
||||
<SetupStep
|
||||
key={step.label}
|
||||
label={step.label}
|
||||
done={step.done}
|
||||
active={!step.done && steps.slice(0, i).every((s) => s.done)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* Action cards */}
|
||||
<motion.div {...fadeUp(isFirstRun && !allDone ? 0.2 : 0.16)} className="flex w-full flex-col gap-2.5">
|
||||
{/* Primary CTA adapts to state */}
|
||||
{!isConnected && (
|
||||
<ActionCard
|
||||
icon={<Zap className="size-4 text-white" />}
|
||||
title="Connect GitHub Copilot"
|
||||
description="Check connection status and configure your CLI"
|
||||
onClick={onOpenSettings}
|
||||
highlight
|
||||
/>
|
||||
)}
|
||||
<button
|
||||
className="flex items-center gap-2 rounded-lg px-4 py-2 text-[13px] text-zinc-500 transition hover:bg-zinc-900 hover:text-zinc-300"
|
||||
|
||||
<ActionCard
|
||||
icon={<MessageSquarePlus className="size-4 text-white" />}
|
||||
title={isFirstRun ? 'Try a Quick Scratchpad' : 'New Scratchpad'}
|
||||
description={isFirstRun ? 'Start a conversation — no setup needed' : 'Ask anything without a project context'}
|
||||
onClick={onNewScratchpad}
|
||||
highlight={isConnected && isFirstRun}
|
||||
/>
|
||||
|
||||
{!hasProjects && (
|
||||
<ActionCard
|
||||
icon={<FolderPlus className="size-4 text-white" />}
|
||||
title="Add Your First Project"
|
||||
description="Connect a repo for full agent support"
|
||||
onClick={onAddProject}
|
||||
/>
|
||||
)}
|
||||
|
||||
<ActionCard
|
||||
icon={<Settings className="size-4 text-white" />}
|
||||
title="Manage Patterns"
|
||||
description="Customize agent behaviors and workflows"
|
||||
onClick={onOpenSettings}
|
||||
type="button"
|
||||
>
|
||||
<Settings className="size-3.5" />
|
||||
Manage patterns
|
||||
</button>
|
||||
</div>
|
||||
/>
|
||||
</motion.div>
|
||||
|
||||
{/* Keyboard shortcut hints for returning users */}
|
||||
{!isFirstRun && (
|
||||
<motion.div {...fadeUp(0.24)} className="flex items-center gap-4 text-[11px] text-[var(--color-text-muted)]">
|
||||
<span>
|
||||
<kbd className="rounded border border-[var(--color-border)] px-1.5 py-0.5 font-mono text-[10px]">Ctrl+N</kbd>
|
||||
{' '}new session
|
||||
</span>
|
||||
<span>
|
||||
<kbd className="rounded border border-[var(--color-border)] px-1.5 py-0.5 font-mono text-[10px]">Ctrl+K</kbd>
|
||||
{' '}commands
|
||||
</span>
|
||||
</motion.div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { useState } from 'react';
|
||||
import { Bot, Check, ChevronDown, Loader2, ShieldAlert, ShieldCheck, X } from 'lucide-react';
|
||||
import { Bot, Check, ChevronDown, Loader2, ShieldAlert, ShieldBan, ShieldCheck, X } from 'lucide-react';
|
||||
|
||||
import { MarkdownContent } from '@renderer/components/MarkdownContent';
|
||||
import { permissionDetailSummary, PermissionDetailView } from '@renderer/components/chat/PermissionDetailView';
|
||||
import { resolveApprovalToolKey } from '@shared/domain/approval';
|
||||
import type { ApprovalDecision, PendingApprovalRecord } from '@shared/domain/approval';
|
||||
import { resolveToolLabel } from '@shared/domain/tooling';
|
||||
|
||||
/* ── ApprovalBanner ────────────────────────────────────────── */
|
||||
|
||||
@@ -14,7 +17,7 @@ export function ApprovalBanner({
|
||||
total,
|
||||
}: {
|
||||
approval: PendingApprovalRecord;
|
||||
onResolve: (decision: ApprovalDecision) => void;
|
||||
onResolve: (decision: ApprovalDecision, alwaysApprove?: boolean) => void;
|
||||
isResolving: boolean;
|
||||
position?: number;
|
||||
total?: number;
|
||||
@@ -22,50 +25,55 @@ export function ApprovalBanner({
|
||||
const kindLabel = approval.kind === 'final-response' ? 'Final response review' : 'Tool call approval';
|
||||
const hasMessages = approval.messages && approval.messages.length > 0;
|
||||
const showPosition = position !== undefined && total !== undefined && total > 1;
|
||||
const approvalToolKey = resolveApprovalToolKey(approval.toolName, approval.permissionKind);
|
||||
const canAlwaysApprove = approval.kind === 'tool-call' && !!approvalToolKey;
|
||||
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.detail && (
|
||||
<p className="mt-1.5 text-[12px] leading-relaxed text-zinc-400">{approval.detail}</p>
|
||||
)}
|
||||
{approval.permissionDetail
|
||||
? <PermissionDetailView detail={approval.permissionDetail} />
|
||||
: approval.detail && (
|
||||
<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>
|
||||
@@ -76,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"
|
||||
@@ -84,8 +92,21 @@ export function ApprovalBanner({
|
||||
{isResolving ? <Loader2 className="size-3 animate-spin" /> : <Check className="size-3" />}
|
||||
Approve
|
||||
</button>
|
||||
{canAlwaysApprove && (
|
||||
<button
|
||||
aria-label={`Always approve ${approvalToolLabel}`}
|
||||
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`}
|
||||
type="button"
|
||||
>
|
||||
<ShieldBan className="size-3" />
|
||||
Always approve
|
||||
</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"
|
||||
@@ -94,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>
|
||||
)}
|
||||
@@ -109,40 +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">{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">
|
||||
<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-[var(--color-surface-2)] px-1.5 py-0.5 text-[8px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
|
||||
{kindLabel}
|
||||
</span>
|
||||
{approval.toolName && (
|
||||
<span className="shrink-0 text-[10px] text-zinc-500">{approval.toolName}</span>
|
||||
<span className="shrink-0 text-[10px] text-[var(--color-text-muted)]">{approval.toolName}</span>
|
||||
)}
|
||||
{approval.agentName && (
|
||||
<span className="shrink-0 text-[10px] text-zinc-600">{approval.agentName}</span>
|
||||
<span className="shrink-0 text-[10px] text-[var(--color-text-muted)]">{approval.agentName}</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
import { useState, useMemo } from 'react';
|
||||
import { ChevronRight, FileCode2, FilePlus2 } from 'lucide-react';
|
||||
|
||||
import type { ToolCallFileChangePreview } from '@shared/contracts/sidecar';
|
||||
|
||||
/* ── Diff stat helpers ─────────────────────────────────────── */
|
||||
|
||||
interface DiffStats {
|
||||
additions: number;
|
||||
deletions: number;
|
||||
}
|
||||
|
||||
function parseDiffStats(diff: string | undefined): DiffStats {
|
||||
if (!diff) return { additions: 0, deletions: 0 };
|
||||
let additions = 0;
|
||||
let deletions = 0;
|
||||
for (const line of diff.split('\n')) {
|
||||
if (line.startsWith('+') && !line.startsWith('+++')) additions++;
|
||||
else if (line.startsWith('-') && !line.startsWith('---')) deletions++;
|
||||
}
|
||||
return { additions, deletions };
|
||||
}
|
||||
|
||||
function fileBaseName(path: string): string {
|
||||
const normalized = path.replace(/\\/g, '/');
|
||||
const lastSlash = normalized.lastIndexOf('/');
|
||||
return lastSlash >= 0 ? normalized.slice(lastSlash + 1) : normalized;
|
||||
}
|
||||
|
||||
function fileDir(path: string): string {
|
||||
const normalized = path.replace(/\\/g, '/');
|
||||
const lastSlash = normalized.lastIndexOf('/');
|
||||
return lastSlash > 0 ? normalized.slice(0, lastSlash + 1) : '';
|
||||
}
|
||||
|
||||
/* ── Mini diff-stats bar (GitHub-style) ────────────────────── */
|
||||
|
||||
function DiffStatsBar({ additions, deletions }: DiffStats) {
|
||||
const total = additions + deletions;
|
||||
if (total === 0) return null;
|
||||
const blocks = 5;
|
||||
const addBlocks = Math.max(additions > 0 ? 1 : 0, Math.round((additions / total) * blocks));
|
||||
const delBlocks = blocks - addBlocks;
|
||||
|
||||
return (
|
||||
<span className="inline-flex gap-px" aria-label={`${additions} additions, ${deletions} deletions`}>
|
||||
{Array.from({ length: addBlocks }, (_, i) => (
|
||||
<span key={`a${i}`} className="size-1.5 rounded-[1px] bg-[var(--color-status-success)]" />
|
||||
))}
|
||||
{Array.from({ length: delBlocks }, (_, i) => (
|
||||
<span key={`d${i}`} className="size-1.5 rounded-[1px] bg-[var(--color-status-error)]" />
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/* ── Diff line renderer ────────────────────────────────────── */
|
||||
|
||||
function DiffLine({ line }: { line: string }) {
|
||||
let textClass = 'text-[var(--color-text-secondary)]';
|
||||
let bgClass = '';
|
||||
|
||||
if (line.startsWith('+') && !line.startsWith('+++')) {
|
||||
textClass = 'text-[var(--color-status-success)]';
|
||||
bgClass = 'bg-[var(--color-status-success)]/[0.06]';
|
||||
} else if (line.startsWith('-') && !line.startsWith('---')) {
|
||||
textClass = 'text-[var(--color-status-error)]';
|
||||
bgClass = 'bg-[var(--color-status-error)]/[0.06]';
|
||||
} else if (line.startsWith('@@')) {
|
||||
textClass = 'text-[var(--color-accent-sky)]';
|
||||
} else if (line.startsWith('diff ') || line.startsWith('index ') || line.startsWith('---') || line.startsWith('+++')) {
|
||||
textClass = 'text-[var(--color-text-muted)]';
|
||||
}
|
||||
|
||||
return <div className={`${textClass} ${bgClass} -mx-3 px-3`}>{line || '\u00A0'}</div>;
|
||||
}
|
||||
|
||||
/* ── Individual file entry ─────────────────────────────────── */
|
||||
|
||||
function FileChangeEntry({ file }: { file: ToolCallFileChangePreview }) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const isNewFile = !file.diff && !!file.newFileContents;
|
||||
const stats = useMemo(() => parseDiffStats(file.diff), [file.diff]);
|
||||
const hasContent = !!file.diff || !!file.newFileContents;
|
||||
const dir = fileDir(file.path);
|
||||
const base = fileBaseName(file.path);
|
||||
|
||||
return (
|
||||
<div className="border-b border-[var(--color-border-subtle)] last:border-b-0">
|
||||
<button
|
||||
className="flex w-full items-center gap-1.5 px-2 py-[5px] text-left text-[10px] transition-colors duration-150 hover:bg-[var(--color-surface-3)]/40 disabled:cursor-default"
|
||||
disabled={!hasContent}
|
||||
onClick={hasContent ? () => setExpanded(!expanded) : undefined}
|
||||
type="button"
|
||||
aria-expanded={hasContent ? expanded : undefined}
|
||||
>
|
||||
{hasContent ? (
|
||||
<ChevronRight
|
||||
className={`size-2.5 shrink-0 text-[var(--color-text-muted)] transition-transform duration-150 ${expanded ? 'rotate-90' : ''}`}
|
||||
/>
|
||||
) : (
|
||||
<span className="w-2.5 shrink-0" />
|
||||
)}
|
||||
|
||||
{isNewFile
|
||||
? <FilePlus2 className="size-3 shrink-0 text-[var(--color-status-success)]" />
|
||||
: <FileCode2 className="size-3 shrink-0 text-[var(--color-accent-sky)]" />}
|
||||
|
||||
<span className="min-w-0 flex-1 truncate font-mono">
|
||||
{dir && <span className="text-[var(--color-text-muted)]">{dir}</span>}
|
||||
<span className="text-[var(--color-text-primary)]">{base}</span>
|
||||
</span>
|
||||
|
||||
{isNewFile ? (
|
||||
<span className="shrink-0 rounded px-1 py-px text-[8px] font-semibold uppercase tracking-wider bg-[var(--color-status-success)]/10 text-[var(--color-status-success)]">
|
||||
new
|
||||
</span>
|
||||
) : (stats.additions > 0 || stats.deletions > 0) ? (
|
||||
<span className="flex items-center gap-1.5 shrink-0">
|
||||
<span className="flex items-center gap-0.5 font-mono">
|
||||
{stats.additions > 0 && <span className="text-[var(--color-status-success)]">+{stats.additions}</span>}
|
||||
{stats.deletions > 0 && <span className="text-[var(--color-status-error)]">−{stats.deletions}</span>}
|
||||
</span>
|
||||
<DiffStatsBar additions={stats.additions} deletions={stats.deletions} />
|
||||
</span>
|
||||
) : null}
|
||||
</button>
|
||||
|
||||
{expanded && (
|
||||
<div className="border-t border-[var(--color-border-subtle)]">
|
||||
<pre className="max-h-64 overflow-auto bg-[var(--color-surface-0)] px-3 py-1.5 font-mono text-[10px] leading-relaxed">
|
||||
{file.diff
|
||||
? file.diff.split('\n').map((line, i) => <DiffLine key={i} line={line} />)
|
||||
: file.newFileContents!.split('\n').map((line, i) => (
|
||||
<div key={i} className="text-[var(--color-text-secondary)]">{line || '\u00A0'}</div>
|
||||
))}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ── Main export ───────────────────────────────────────────── */
|
||||
|
||||
interface FileChangePreviewProps {
|
||||
fileChanges: ToolCallFileChangePreview[];
|
||||
}
|
||||
|
||||
export function FileChangePreview({ fileChanges }: FileChangePreviewProps) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
const totalStats = useMemo(() => {
|
||||
let additions = 0;
|
||||
let deletions = 0;
|
||||
let newFiles = 0;
|
||||
for (const fc of fileChanges) {
|
||||
if (!fc.diff && fc.newFileContents) {
|
||||
newFiles++;
|
||||
} else {
|
||||
const s = parseDiffStats(fc.diff);
|
||||
additions += s.additions;
|
||||
deletions += s.deletions;
|
||||
}
|
||||
}
|
||||
return { additions, deletions, newFiles };
|
||||
}, [fileChanges]);
|
||||
|
||||
const fileWord = fileChanges.length === 1 ? 'file' : 'files';
|
||||
|
||||
return (
|
||||
<div className="mt-1 overflow-hidden rounded-md border border-[var(--color-border-subtle)] bg-[var(--color-surface-1)]/60">
|
||||
<button
|
||||
className="flex w-full items-center gap-1.5 px-2 py-1 text-left text-[10px] font-medium text-[var(--color-text-muted)] transition-colors duration-150 hover:bg-[var(--color-surface-2)]/40 hover:text-[var(--color-text-secondary)]"
|
||||
onClick={() => setExpanded(!expanded)}
|
||||
type="button"
|
||||
aria-expanded={expanded}
|
||||
aria-label={`${fileChanges.length} file changes`}
|
||||
>
|
||||
<ChevronRight
|
||||
className={`size-2.5 shrink-0 transition-transform duration-150 ${expanded ? 'rotate-90' : ''}`}
|
||||
/>
|
||||
<span>{fileChanges.length} {fileWord} changed</span>
|
||||
|
||||
{(totalStats.additions > 0 || totalStats.deletions > 0) && (
|
||||
<span className="ml-auto flex shrink-0 items-center gap-1.5 font-mono">
|
||||
{totalStats.additions > 0 && (
|
||||
<span className="text-[var(--color-status-success)]">+{totalStats.additions}</span>
|
||||
)}
|
||||
{totalStats.deletions > 0 && (
|
||||
<span className="text-[var(--color-status-error)]">−{totalStats.deletions}</span>
|
||||
)}
|
||||
<DiffStatsBar additions={totalStats.additions} deletions={totalStats.deletions} />
|
||||
</span>
|
||||
)}
|
||||
{totalStats.newFiles > 0 && (
|
||||
<span className={`shrink-0 rounded px-1 py-px text-[8px] font-semibold uppercase tracking-wider bg-[var(--color-status-success)]/10 text-[var(--color-status-success)] ${totalStats.additions === 0 && totalStats.deletions === 0 ? 'ml-auto' : ''}`}>
|
||||
{totalStats.newFiles} new
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{expanded && (
|
||||
<div className="border-t border-[var(--color-border-subtle)]">
|
||||
{fileChanges.map((fc) => (
|
||||
<FileChangeEntry file={fc} key={fc.path} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import { useState } from 'react';
|
||||
import { ChevronDown, Sparkles } from 'lucide-react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { ChevronDown, ChevronRight, Loader2, Minus, Search, Sparkles, TerminalSquare } from 'lucide-react';
|
||||
|
||||
import { ProviderIcon } from '@renderer/components/ProviderIcons';
|
||||
import { PopoverToggleRow } from '@renderer/components/ui';
|
||||
import { useClickOutside } from '@renderer/hooks/useClickOutside';
|
||||
import type { ApprovalToolDefinition, ApprovalToolKind, LspProfileDefinition, McpServerDefinition, SessionToolingSelection } from '@shared/domain/tooling';
|
||||
import type { ApprovalToolDefinition, LspProfileDefinition, McpServerDefinition, SessionToolingSelection, WorkspaceToolingSettings } from '@shared/domain/tooling';
|
||||
import { groupApprovalToolsByProvider, type ApprovalToolGroup } from '@shared/domain/tooling';
|
||||
import { findModel, inferProvider, providerMeta, type ModelDefinition } from '@shared/domain/models';
|
||||
import { reasoningEffortOptions, type ReasoningEffort } from '@shared/domain/pattern';
|
||||
import { RotateCcw, Server, ShieldCheck } from 'lucide-react';
|
||||
@@ -14,9 +15,9 @@ import { RotateCcw, Server, ShieldCheck } from 'lucide-react';
|
||||
function TierBadge({ tier }: { tier: ModelDefinition['tier'] }) {
|
||||
if (!tier) return null;
|
||||
const styles = {
|
||||
premium: 'bg-amber-500/10 text-amber-400',
|
||||
standard: 'bg-zinc-700/50 text-zinc-500',
|
||||
fast: 'bg-emerald-500/10 text-emerald-400',
|
||||
premium: 'bg-[var(--color-status-warning)]/10 text-[var(--color-status-warning)]',
|
||||
standard: 'bg-[var(--color-surface-3)]/50 text-[var(--color-text-muted)]',
|
||||
fast: 'bg-[var(--color-status-success)]/10 text-[var(--color-status-success)]',
|
||||
};
|
||||
return (
|
||||
<span className={`ml-auto rounded px-1.5 py-0.5 text-[9px] font-medium ${styles[tier]}`}>
|
||||
@@ -63,10 +64,10 @@ export function InlineModelPill({
|
||||
<button
|
||||
aria-expanded={open}
|
||||
aria-haspopup="listbox"
|
||||
className={`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-pill font-medium transition ${
|
||||
className={`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-pill font-medium transition-all duration-200 ${
|
||||
open
|
||||
? 'border-indigo-500/40 bg-indigo-500/10 text-indigo-300'
|
||||
: 'border-zinc-700/60 bg-zinc-800/40 text-zinc-400 hover:border-zinc-600 hover:text-zinc-300'
|
||||
? 'border-[var(--color-border-glow)] bg-[var(--color-accent-muted)] text-[var(--color-text-accent)]'
|
||||
: 'border-[var(--color-border-subtle)] bg-[var(--color-surface-2)]/40 text-[var(--color-text-secondary)] hover:border-[var(--color-border)] hover:text-[var(--color-text-primary)]'
|
||||
} disabled:cursor-not-allowed disabled:opacity-50`}
|
||||
disabled={disabled}
|
||||
onClick={() => setOpen(!open)}
|
||||
@@ -78,19 +79,19 @@ export function InlineModelPill({
|
||||
</button>
|
||||
|
||||
{open && !disabled && (
|
||||
<div className="absolute bottom-full right-0 z-40 mb-1.5 max-h-72 w-64 overflow-y-auto rounded-lg border border-zinc-700 bg-zinc-900 py-1 shadow-2xl" role="listbox">
|
||||
<div className="absolute bottom-full right-0 z-40 mb-1.5 max-h-72 w-64 overflow-y-auto rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] py-1 shadow-2xl" role="listbox">
|
||||
{groupedModels.map((pg) => (
|
||||
<div key={pg.id}>
|
||||
<div className="flex items-center gap-2 px-3 pb-1 pt-2.5">
|
||||
<ProviderIcon provider={pg.id} className="size-3.5" />
|
||||
<span className="text-[10px] font-semibold uppercase tracking-wider text-zinc-500">
|
||||
<span className="text-[10px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
|
||||
{pg.label}
|
||||
</span>
|
||||
</div>
|
||||
{pg.models.map((model) => (
|
||||
<button
|
||||
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-[13px] transition hover:bg-zinc-800 ${
|
||||
model.id === value ? 'bg-indigo-500/10 text-indigo-200' : 'text-zinc-300'
|
||||
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-[13px] transition-all duration-200 hover:bg-[var(--color-surface-3)] ${
|
||||
model.id === value ? 'bg-[var(--color-accent-muted)] text-[var(--color-text-accent)]' : 'text-[var(--color-text-primary)]'
|
||||
}`}
|
||||
key={model.id}
|
||||
onClick={() => { onChange(model.id); setOpen(false); }}
|
||||
@@ -106,13 +107,13 @@ export function InlineModelPill({
|
||||
))}
|
||||
{otherModels.length > 0 && (
|
||||
<div>
|
||||
<div className="px-3 pb-1 pt-2.5 text-[10px] font-semibold uppercase tracking-wider text-zinc-500">
|
||||
<div className="px-3 pb-1 pt-2.5 text-[10px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
|
||||
Other
|
||||
</div>
|
||||
{otherModels.map((model) => (
|
||||
<button
|
||||
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-[13px] transition hover:bg-zinc-800 ${
|
||||
model.id === value ? 'bg-indigo-500/10 text-indigo-200' : 'text-zinc-300'
|
||||
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-[13px] transition-all duration-200 hover:bg-[var(--color-surface-3)] ${
|
||||
model.id === value ? 'bg-[var(--color-accent-muted)] text-[var(--color-text-accent)]' : 'text-[var(--color-text-primary)]'
|
||||
}`}
|
||||
key={model.id}
|
||||
onClick={() => { onChange(model.id); setOpen(false); }}
|
||||
@@ -154,7 +155,7 @@ export function InlineThinkingPill({
|
||||
|
||||
if (supportedEfforts && supportedEfforts.length === 0) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 rounded border border-zinc-800/40 bg-zinc-800/20 px-1.5 py-0.5 text-pill text-zinc-600">
|
||||
<span className="inline-flex items-center gap-1 rounded border border-[var(--color-border-subtle)] bg-[var(--color-surface-2)]/20 px-1.5 py-0.5 text-pill text-[var(--color-text-muted)]">
|
||||
<Sparkles className="size-2.5" />
|
||||
N/A
|
||||
</span>
|
||||
@@ -168,10 +169,10 @@ export function InlineThinkingPill({
|
||||
<button
|
||||
aria-expanded={open}
|
||||
aria-haspopup="listbox"
|
||||
className={`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-pill font-medium transition ${
|
||||
className={`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-pill font-medium transition-all duration-200 ${
|
||||
open
|
||||
? 'border-indigo-500/40 bg-indigo-500/10 text-indigo-300'
|
||||
: 'border-zinc-700/60 bg-zinc-800/40 text-zinc-400 hover:border-zinc-600 hover:text-zinc-300'
|
||||
? 'border-[var(--color-border-glow)] bg-[var(--color-accent-muted)] text-[var(--color-text-accent)]'
|
||||
: 'border-[var(--color-border-subtle)] bg-[var(--color-surface-2)]/40 text-[var(--color-text-secondary)] hover:border-[var(--color-border)] hover:text-[var(--color-text-primary)]'
|
||||
} disabled:cursor-not-allowed disabled:opacity-50`}
|
||||
disabled={disabled}
|
||||
onClick={() => setOpen(!open)}
|
||||
@@ -183,11 +184,11 @@ export function InlineThinkingPill({
|
||||
</button>
|
||||
|
||||
{open && !disabled && (
|
||||
<div className="absolute bottom-full right-0 z-40 mb-1.5 w-36 overflow-hidden rounded-lg border border-zinc-700 bg-zinc-900 py-1 shadow-2xl" role="listbox">
|
||||
<div className="absolute bottom-full right-0 z-40 mb-1.5 w-36 overflow-hidden rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] py-1 shadow-2xl" role="listbox">
|
||||
{options.map((option) => (
|
||||
<button
|
||||
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-[13px] transition hover:bg-zinc-800 ${
|
||||
option.value === value ? 'bg-indigo-500/10 text-indigo-200' : 'text-zinc-300'
|
||||
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-[13px] transition-all duration-200 hover:bg-[var(--color-surface-3)] ${
|
||||
option.value === value ? 'bg-[var(--color-accent-muted)] text-[var(--color-text-accent)]' : 'text-[var(--color-text-primary)]'
|
||||
}`}
|
||||
key={option.value}
|
||||
onClick={() => { onChange(option.value); setOpen(false); }}
|
||||
@@ -234,10 +235,10 @@ export function InlineToolsPill({
|
||||
<button
|
||||
aria-expanded={open}
|
||||
aria-haspopup="listbox"
|
||||
className={`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-pill font-medium transition ${
|
||||
className={`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-pill font-medium transition-all duration-200 ${
|
||||
open
|
||||
? 'border-indigo-500/40 bg-indigo-500/10 text-indigo-300'
|
||||
: 'border-zinc-700/60 bg-zinc-800/40 text-zinc-400 hover:border-zinc-600 hover:text-zinc-300'
|
||||
? 'border-[var(--color-border-glow)] bg-[var(--color-accent-muted)] text-[var(--color-text-accent)]'
|
||||
: 'border-[var(--color-border-subtle)] bg-[var(--color-surface-2)]/40 text-[var(--color-text-secondary)] hover:border-[var(--color-border)] hover:text-[var(--color-text-primary)]'
|
||||
} disabled:cursor-not-allowed disabled:opacity-50`}
|
||||
disabled={disabled}
|
||||
onClick={() => setOpen(!open)}
|
||||
@@ -249,7 +250,7 @@ export function InlineToolsPill({
|
||||
</button>
|
||||
|
||||
{open && !disabled && (
|
||||
<div className="absolute bottom-full left-0 z-40 mb-1.5 w-64 overflow-y-auto rounded-lg border border-zinc-700 bg-zinc-900 py-1 shadow-2xl">
|
||||
<div className="absolute bottom-full left-0 z-40 mb-1.5 w-64 overflow-y-auto rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] py-1 shadow-2xl">
|
||||
{workspaceMcpServers.length > 0 && (
|
||||
<McpServerGroup
|
||||
label="Workspace MCP"
|
||||
@@ -276,7 +277,7 @@ export function InlineToolsPill({
|
||||
)}
|
||||
{lspProfiles.length > 0 && (
|
||||
<div>
|
||||
<div className="px-3 pb-1 pt-2 text-[9px] font-semibold uppercase tracking-wider text-zinc-600">
|
||||
<div className="px-3 pb-1 pt-2 text-[9px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
|
||||
Language Servers
|
||||
</div>
|
||||
{lspProfiles.map((profile) => (
|
||||
@@ -314,7 +315,7 @@ function McpServerGroup({
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<div className="px-3 pb-1 pt-2 text-[9px] font-semibold uppercase tracking-wider text-zinc-600">
|
||||
<div className="px-3 pb-1 pt-2 text-[9px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
|
||||
{label}
|
||||
</div>
|
||||
{servers.map((server) => (
|
||||
@@ -337,29 +338,64 @@ function McpServerGroup({
|
||||
|
||||
/* ── InlineApprovalPill ────────────────────────────────────── */
|
||||
|
||||
const approvalKindOrder: ApprovalToolKind[] = ['builtin', 'mcp', 'lsp', 'mixed'];
|
||||
const approvalKindLabels: Record<ApprovalToolKind, string> = {
|
||||
builtin: 'Built-in',
|
||||
mcp: 'MCP Servers',
|
||||
lsp: 'Language Servers',
|
||||
mixed: 'Other',
|
||||
};
|
||||
const SEARCH_THRESHOLD = 10;
|
||||
|
||||
export function InlineApprovalPill({
|
||||
approvalTools,
|
||||
toolingSettings,
|
||||
effectiveAutoApproved,
|
||||
effectiveAutoApprovedCount,
|
||||
isOverridden,
|
||||
disabled,
|
||||
mcpProbingServerIds,
|
||||
onUpdate,
|
||||
}: {
|
||||
approvalTools: ApprovalToolDefinition[];
|
||||
toolingSettings: WorkspaceToolingSettings;
|
||||
effectiveAutoApproved: Set<string>;
|
||||
effectiveAutoApprovedCount: number;
|
||||
isOverridden: boolean;
|
||||
disabled: boolean;
|
||||
mcpProbingServerIds?: string[];
|
||||
onUpdate: (settings: { autoApprovedToolNames?: string[] }) => void;
|
||||
}) {
|
||||
}){
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useClickOutside<HTMLDivElement>(() => setOpen(false), open);
|
||||
const [search, setSearch] = useState('');
|
||||
const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());
|
||||
const ref = useClickOutside<HTMLDivElement>(() => { setOpen(false); setSearch(''); }, open);
|
||||
|
||||
const probingSet = useMemo(
|
||||
() => new Set(mcpProbingServerIds ?? []),
|
||||
[mcpProbingServerIds],
|
||||
);
|
||||
const isProbingAny = probingSet.size > 0;
|
||||
|
||||
const groups = useMemo(
|
||||
() => groupApprovalToolsByProvider(approvalTools, toolingSettings),
|
||||
[approvalTools, toolingSettings],
|
||||
);
|
||||
|
||||
const totalItemCount = groups.reduce(
|
||||
(sum, g) => sum + Math.max(g.tools.length, g.serverApprovalKey ? 1 : 0),
|
||||
0,
|
||||
);
|
||||
const showSearch = totalItemCount > SEARCH_THRESHOLD;
|
||||
const searchLower = search.toLowerCase().trim();
|
||||
|
||||
const filteredGroups = useMemo(() => {
|
||||
if (!searchLower) return groups;
|
||||
return groups
|
||||
.map((group) => ({
|
||||
...group,
|
||||
tools: group.tools.filter(
|
||||
(t) =>
|
||||
t.label.toLowerCase().includes(searchLower)
|
||||
|| t.id.toLowerCase().includes(searchLower)
|
||||
|| group.label.toLowerCase().includes(searchLower),
|
||||
),
|
||||
}))
|
||||
.filter((g) => g.tools.length > 0 || g.label.toLowerCase().includes(searchLower));
|
||||
}, [groups, searchLower]);
|
||||
|
||||
function toggleTool(toolId: string) {
|
||||
const next = new Set(effectiveAutoApproved);
|
||||
@@ -371,79 +407,288 @@ export function InlineApprovalPill({
|
||||
onUpdate({ autoApprovedToolNames: [...next] });
|
||||
}
|
||||
|
||||
const groups = approvalKindOrder
|
||||
.map((kind) => ({ kind, tools: approvalTools.filter((t) => t.kind === kind) }))
|
||||
.filter((g) => g.tools.length > 0);
|
||||
const showHeaders = groups.length > 1;
|
||||
function toggleGroup(group: ApprovalToolGroup) {
|
||||
const next = new Set(effectiveAutoApproved);
|
||||
|
||||
if (group.serverApprovalKey) {
|
||||
// MCP servers use server-level approval key
|
||||
if (next.has(group.serverApprovalKey)) {
|
||||
next.delete(group.serverApprovalKey);
|
||||
} else {
|
||||
next.add(group.serverApprovalKey);
|
||||
}
|
||||
// Also remove individual tool entries when toggling server-level
|
||||
for (const tool of group.tools) {
|
||||
next.delete(tool.id);
|
||||
}
|
||||
} else {
|
||||
// Non-MCP groups: toggle individual tools
|
||||
const allApproved = group.tools.every((t) => next.has(t.id));
|
||||
for (const tool of group.tools) {
|
||||
if (allApproved) {
|
||||
next.delete(tool.id);
|
||||
} else {
|
||||
next.add(tool.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onUpdate({ autoApprovedToolNames: [...next] });
|
||||
}
|
||||
|
||||
function isGroupApproved(group: ApprovalToolGroup): 'all' | 'some' | 'none' {
|
||||
if (group.serverApprovalKey && effectiveAutoApproved.has(group.serverApprovalKey)) {
|
||||
return 'all';
|
||||
}
|
||||
if (group.tools.length === 0) return 'none';
|
||||
const approvedCount = group.tools.filter((t) => effectiveAutoApproved.has(t.id)).length;
|
||||
if (approvedCount === group.tools.length) return 'all';
|
||||
if (approvedCount > 0) return 'some';
|
||||
return 'none';
|
||||
}
|
||||
|
||||
function isGroupProbing(group: ApprovalToolGroup): boolean {
|
||||
if (group.kind !== 'mcp') return false;
|
||||
const serverId = group.id.replace(/^mcp:/, '');
|
||||
return probingSet.has(serverId);
|
||||
}
|
||||
|
||||
function toggleExpanded(groupId: string) {
|
||||
setExpandedGroups((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(groupId)) {
|
||||
next.delete(groupId);
|
||||
} else {
|
||||
next.add(groupId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
function isGroupExpanded(groupId: string): boolean {
|
||||
if (searchLower) return true;
|
||||
return expandedGroups.has(groupId);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative" ref={ref}>
|
||||
<button
|
||||
aria-expanded={open}
|
||||
aria-haspopup="listbox"
|
||||
className={`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-pill font-medium transition ${
|
||||
className={`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-pill font-medium transition-all duration-200 ${
|
||||
open
|
||||
? 'border-indigo-500/40 bg-indigo-500/10 text-indigo-300'
|
||||
? 'border-[var(--color-border-glow)] bg-[var(--color-accent-muted)] text-[var(--color-text-accent)]'
|
||||
: isOverridden
|
||||
? 'border-amber-500/30 bg-amber-500/5 text-amber-400 hover:border-amber-500/50'
|
||||
: 'border-zinc-700/60 bg-zinc-800/40 text-zinc-400 hover:border-zinc-600 hover:text-zinc-300'
|
||||
? 'border-[var(--color-status-warning)]/30 bg-[var(--color-status-warning)]/5 text-[var(--color-status-warning)] hover:border-[var(--color-status-warning)]/50'
|
||||
: 'border-[var(--color-border-subtle)] bg-[var(--color-surface-2)]/40 text-[var(--color-text-secondary)] hover:border-[var(--color-border)] hover:text-[var(--color-text-primary)]'
|
||||
} disabled:cursor-not-allowed disabled:opacity-50`}
|
||||
disabled={disabled}
|
||||
onClick={() => setOpen(!open)}
|
||||
type="button"
|
||||
>
|
||||
<ShieldCheck className="size-2.5" />
|
||||
<span>{effectiveAutoApproved.size}/{approvalTools.length} auto-approved</span>
|
||||
{isProbingAny ? (
|
||||
<Loader2 className="size-2.5 animate-spin" aria-label="Probing MCP servers" />
|
||||
) : (
|
||||
<ShieldCheck className="size-2.5" />
|
||||
)}
|
||||
<span>
|
||||
{effectiveAutoApprovedCount}/{totalItemCount} auto-approved
|
||||
{isProbingAny && <span className="text-[var(--color-text-muted)]"> · probing…</span>}
|
||||
</span>
|
||||
<ChevronDown className={`size-2.5 transition ${open ? 'rotate-180' : ''}`} />
|
||||
</button>
|
||||
|
||||
{open && !disabled && (
|
||||
<div className="absolute bottom-full left-0 z-40 mb-1.5 max-h-80 w-72 overflow-y-auto rounded-lg border border-zinc-700 bg-zinc-900 shadow-2xl">
|
||||
<div className="flex items-center gap-2 border-b border-zinc-800 px-3 py-2">
|
||||
<span className={`rounded-full px-2 py-0.5 text-[9px] font-semibold uppercase tracking-wider ${
|
||||
isOverridden
|
||||
? 'bg-amber-500/15 text-amber-400'
|
||||
: 'bg-zinc-800 text-zinc-500'
|
||||
}`}>
|
||||
{isOverridden ? 'Session override' : 'Pattern defaults'}
|
||||
</span>
|
||||
{isOverridden && (
|
||||
<button
|
||||
className="flex items-center gap-1 rounded-full px-2 py-0.5 text-[9px] font-medium text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300"
|
||||
onClick={() => onUpdate({})}
|
||||
type="button"
|
||||
>
|
||||
<RotateCcw className="size-2.5" />
|
||||
Reset
|
||||
</button>
|
||||
<div className="absolute bottom-full left-0 z-40 mb-1.5 max-h-[28rem] w-80 overflow-y-auto rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] shadow-2xl">
|
||||
{/* Header: session override / pattern defaults */}
|
||||
<div className="sticky top-0 z-10 border-b border-[var(--color-border)] bg-[var(--color-surface-1)]">
|
||||
<div className="flex items-center gap-2 px-3 py-2">
|
||||
<span className={`rounded-full px-2 py-0.5 text-[9px] font-semibold uppercase tracking-wider ${
|
||||
isOverridden
|
||||
? 'bg-[var(--color-status-warning)]/15 text-[var(--color-status-warning)]'
|
||||
: 'bg-[var(--color-surface-2)] text-[var(--color-text-muted)]'
|
||||
}`}>
|
||||
{isOverridden ? 'Session override' : 'Pattern defaults'}
|
||||
</span>
|
||||
{isOverridden && (
|
||||
<button
|
||||
className="flex items-center gap-1 rounded-full px-2 py-0.5 text-[9px] font-medium text-[var(--color-text-muted)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]"
|
||||
onClick={() => onUpdate({})}
|
||||
type="button"
|
||||
>
|
||||
<RotateCcw className="size-2.5" />
|
||||
Reset
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Search */}
|
||||
{showSearch && (
|
||||
<div className="border-t border-[var(--color-border-subtle)] px-3 py-1.5">
|
||||
<div className="flex items-center gap-2 rounded border border-[var(--color-border)] bg-[var(--color-surface-2)]/30 px-2 py-1">
|
||||
<Search className="size-3 shrink-0 text-[var(--color-text-muted)]" />
|
||||
<input
|
||||
autoFocus
|
||||
className="w-full bg-transparent text-[12px] text-[var(--color-text-primary)] placeholder-[var(--color-text-muted)] outline-none"
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="Filter tools…"
|
||||
type="text"
|
||||
value={search}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Tool groups */}
|
||||
<div className="py-1">
|
||||
{groups.map((group, i) => (
|
||||
<div key={group.kind}>
|
||||
{showHeaders && (
|
||||
<div className={`px-3 pb-1 ${i > 0 ? 'pt-2' : 'pt-1'} text-[9px] font-semibold uppercase tracking-wider text-zinc-600`}>
|
||||
{approvalKindLabels[group.kind]}
|
||||
</div>
|
||||
)}
|
||||
{group.tools.map((tool) => {
|
||||
const detail = tool.description || (tool.providerNames.length > 0 ? tool.providerNames.join(', ') : undefined);
|
||||
return (
|
||||
<PopoverToggleRow
|
||||
detail={detail}
|
||||
enabled={effectiveAutoApproved.has(tool.id)}
|
||||
key={tool.id}
|
||||
label={tool.label}
|
||||
onToggle={() => toggleTool(tool.id)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{filteredGroups.map((group, groupIdx) => {
|
||||
const isBuiltin = group.kind === 'builtin';
|
||||
const isCollapsible = !isBuiltin;
|
||||
const expanded = isBuiltin || isGroupExpanded(group.id);
|
||||
const probing = isGroupProbing(group);
|
||||
const groupState = isGroupApproved(group);
|
||||
const allApproved = groupState === 'all';
|
||||
const someApproved = groupState === 'some';
|
||||
const approvedLabel = group.serverApprovalKey && allApproved
|
||||
? 'all'
|
||||
: `${group.tools.filter((t) => effectiveAutoApproved.has(t.id)).length}/${group.tools.length}`;
|
||||
|
||||
return (
|
||||
<div key={group.id}>
|
||||
{/* Group header */}
|
||||
{isBuiltin ? (
|
||||
<div className={`px-3 pb-1 ${groupIdx > 0 ? 'pt-2.5' : 'pt-1'} text-[9px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]`}>
|
||||
{group.label}
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className={`flex w-full cursor-pointer items-center gap-1.5 px-2.5 py-1.5 text-left transition-all duration-200 hover:bg-[var(--color-surface-3)]/60 ${groupIdx > 0 ? 'mt-0.5' : ''}`}
|
||||
onClick={() => toggleExpanded(group.id)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggleExpanded(group.id); } }}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
>
|
||||
{probing ? (
|
||||
<Loader2 className="size-3 shrink-0 animate-spin text-[var(--color-text-accent)]" aria-label="Probing server" />
|
||||
) : group.tools.length > 0 ? (
|
||||
<ChevronRight className={`size-3 shrink-0 text-[var(--color-text-muted)] transition ${expanded ? 'rotate-90' : ''}`} />
|
||||
) : (
|
||||
<Server className="size-3 shrink-0 text-[var(--color-text-muted)]" />
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate text-[12px] font-medium text-[var(--color-text-primary)]">{group.label}</span>
|
||||
{probing ? (
|
||||
<span className="shrink-0 rounded-full bg-[var(--color-accent-muted)] px-1.5 py-px text-[9px] font-medium text-[var(--color-text-accent)]">
|
||||
probing…
|
||||
</span>
|
||||
) : (
|
||||
<span className="shrink-0 rounded-full bg-[var(--color-surface-2)]/80 px-1.5 py-px text-[9px] font-medium tabular-nums text-[var(--color-text-muted)]">
|
||||
{approvedLabel}
|
||||
</span>
|
||||
)}
|
||||
{!probing && (
|
||||
<GroupToggle
|
||||
allApproved={allApproved}
|
||||
someApproved={someApproved}
|
||||
onToggle={(e) => { e.stopPropagation(); toggleGroup(group); }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Group tools */}
|
||||
{expanded && group.tools.map((tool) => {
|
||||
const detail = tool.description || (
|
||||
!isBuiltin && tool.providerNames.length > 1
|
||||
? tool.providerNames.join(', ')
|
||||
: undefined
|
||||
);
|
||||
return (
|
||||
<div key={tool.id} className={isCollapsible ? 'pl-3' : ''}>
|
||||
<PopoverToggleRow
|
||||
detail={detail}
|
||||
enabled={effectiveAutoApproved.has(tool.id)}
|
||||
label={tool.label}
|
||||
onToggle={() => toggleTool(tool.id)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{filteredGroups.length === 0 && searchLower && (
|
||||
<div className="px-3 py-4 text-center text-[12px] text-[var(--color-text-muted)]">
|
||||
No tools match "{search}"
|
||||
</div>
|
||||
))}
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function GroupToggle({
|
||||
allApproved,
|
||||
someApproved,
|
||||
onToggle,
|
||||
}: {
|
||||
allApproved: boolean;
|
||||
someApproved: boolean;
|
||||
onToggle: (e: React.MouseEvent) => void;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
aria-pressed={allApproved}
|
||||
className={`relative inline-flex h-[16px] w-[28px] shrink-0 items-center rounded-full transition-colors ${
|
||||
allApproved ? 'bg-[var(--color-accent)]' : someApproved ? 'bg-[var(--color-surface-3)]' : 'bg-[var(--color-surface-3)]'
|
||||
}`}
|
||||
onClick={onToggle}
|
||||
type="button"
|
||||
>
|
||||
{someApproved ? (
|
||||
<Minus className="absolute left-1/2 size-2 -translate-x-1/2 text-[var(--color-text-primary)]" strokeWidth={3} />
|
||||
) : (
|
||||
<span
|
||||
className={`inline-block size-[12px] rounded-full bg-white shadow transition-transform ${
|
||||
allApproved ? 'translate-x-[13px]' : 'translate-x-[2px]'
|
||||
}`}
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/* ── InlineTerminalPill ────────────────────────────────────── */
|
||||
|
||||
export function InlineTerminalPill({
|
||||
disabled,
|
||||
isRunning,
|
||||
isOpen,
|
||||
onToggle,
|
||||
}: {
|
||||
disabled: boolean;
|
||||
isRunning: boolean;
|
||||
isOpen: boolean;
|
||||
onToggle: () => void;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
aria-pressed={isOpen}
|
||||
className={`inline-flex items-center gap-1 rounded-lg px-2 py-1 text-[11px] font-medium transition-all duration-200 ${
|
||||
isOpen
|
||||
? 'bg-[var(--color-accent-muted)] text-[var(--color-text-accent)] hover:bg-[var(--color-accent)]/20'
|
||||
: 'text-[var(--color-text-muted)] hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]'
|
||||
} disabled:cursor-not-allowed disabled:opacity-50`}
|
||||
disabled={disabled}
|
||||
onClick={onToggle}
|
||||
type="button"
|
||||
>
|
||||
{isRunning && <span className="size-1.5 shrink-0 rounded-full bg-[var(--color-status-success)]" />}
|
||||
<TerminalSquare className="size-3" />
|
||||
<span>Terminal</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { ArrowUp, FileText, X } from 'lucide-react';
|
||||
|
||||
import { useClickOutside } from '@renderer/hooks/useClickOutside';
|
||||
import type { ProjectPromptFile, ProjectPromptVariable } from '@shared/domain/projectCustomization';
|
||||
|
||||
const promptVariablePattern = /\$\{input:([a-zA-Z0-9_-]+):[^}]+\}/g;
|
||||
|
||||
function resolvePromptTemplate(template: string, values: Record<string, string>): string {
|
||||
return template.replace(promptVariablePattern, (_match, name: string) => {
|
||||
return values[name] ?? '';
|
||||
});
|
||||
}
|
||||
|
||||
export function InlinePromptPill({
|
||||
promptFiles,
|
||||
disabled,
|
||||
onSubmit,
|
||||
}: {
|
||||
promptFiles: ReadonlyArray<ProjectPromptFile>;
|
||||
disabled: boolean;
|
||||
onSubmit: (resolvedContent: string) => void;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [selectedPrompt, setSelectedPrompt] = useState<ProjectPromptFile | null>(null);
|
||||
const [variableValues, setVariableValues] = useState<Record<string, string>>({});
|
||||
const ref = useClickOutside<HTMLDivElement>(() => handleClose(), open);
|
||||
|
||||
const handleClose = useCallback(() => {
|
||||
setOpen(false);
|
||||
setSelectedPrompt(null);
|
||||
setVariableValues({});
|
||||
}, []);
|
||||
|
||||
const handleSelectPrompt = useCallback((prompt: ProjectPromptFile) => {
|
||||
if (prompt.variables.length === 0) {
|
||||
onSubmit(prompt.template.trim());
|
||||
handleClose();
|
||||
} else {
|
||||
setSelectedPrompt(prompt);
|
||||
setVariableValues({});
|
||||
}
|
||||
}, [onSubmit, handleClose]);
|
||||
|
||||
const handleSubmitWithVariables = useCallback(() => {
|
||||
if (!selectedPrompt) return;
|
||||
const resolved = resolvePromptTemplate(selectedPrompt.template, variableValues).trim();
|
||||
if (!resolved) return;
|
||||
onSubmit(resolved);
|
||||
handleClose();
|
||||
}, [selectedPrompt, variableValues, onSubmit, handleClose]);
|
||||
|
||||
const handleVariableChange = useCallback((name: string, value: string) => {
|
||||
setVariableValues((prev) => ({ ...prev, [name]: value }));
|
||||
}, []);
|
||||
|
||||
const allVariablesFilled = useMemo(() => {
|
||||
if (!selectedPrompt) return false;
|
||||
return selectedPrompt.variables.every((v) => (variableValues[v.name] ?? '').trim().length > 0);
|
||||
}, [selectedPrompt, variableValues]);
|
||||
|
||||
if (promptFiles.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="relative" ref={ref}>
|
||||
<button
|
||||
aria-expanded={open}
|
||||
aria-haspopup="listbox"
|
||||
className="inline-flex items-center gap-1 rounded-lg px-2 py-1 text-[11px] font-medium text-[var(--color-text-muted)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]"
|
||||
disabled={disabled}
|
||||
onClick={() => setOpen(!open)}
|
||||
type="button"
|
||||
>
|
||||
<FileText className="size-3" />
|
||||
Prompts
|
||||
<span className="text-[var(--color-text-muted)]">({promptFiles.length})</span>
|
||||
</button>
|
||||
|
||||
{open && !disabled && (
|
||||
<div
|
||||
className="absolute bottom-full left-0 z-40 mb-1.5 w-80 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] shadow-xl"
|
||||
role="listbox"
|
||||
>
|
||||
{selectedPrompt ? (
|
||||
<PromptVariableForm
|
||||
onBack={() => {
|
||||
setSelectedPrompt(null);
|
||||
setVariableValues({});
|
||||
}}
|
||||
onSubmit={handleSubmitWithVariables}
|
||||
onVariableChange={handleVariableChange}
|
||||
prompt={selectedPrompt}
|
||||
submitDisabled={!allVariablesFilled}
|
||||
values={variableValues}
|
||||
/>
|
||||
) : (
|
||||
<PromptList
|
||||
onSelect={handleSelectPrompt}
|
||||
promptFiles={promptFiles}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PromptList({
|
||||
promptFiles,
|
||||
onSelect,
|
||||
}: {
|
||||
promptFiles: ReadonlyArray<ProjectPromptFile>;
|
||||
onSelect: (prompt: ProjectPromptFile) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="max-h-64 overflow-y-auto py-1">
|
||||
<div className="px-3 py-2 text-[10px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
|
||||
Prompt files
|
||||
</div>
|
||||
{promptFiles.map((prompt) => (
|
||||
<button
|
||||
key={prompt.id}
|
||||
className="flex w-full items-start gap-2.5 px-3 py-2 text-left transition-all duration-200 hover:bg-[var(--color-surface-3)]"
|
||||
onClick={() => onSelect(prompt)}
|
||||
role="option"
|
||||
type="button"
|
||||
>
|
||||
<FileText className="mt-0.5 size-3.5 shrink-0 text-[var(--color-text-muted)]" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-[12px] font-medium text-[var(--color-text-primary)]">
|
||||
{prompt.name}
|
||||
</div>
|
||||
{prompt.description && (
|
||||
<div className="mt-0.5 truncate text-[11px] text-[var(--color-text-muted)]">
|
||||
{prompt.description}
|
||||
</div>
|
||||
)}
|
||||
{prompt.variables.length > 0 && (
|
||||
<div className="mt-1 flex flex-wrap gap-1">
|
||||
{prompt.variables.map((v) => (
|
||||
<span
|
||||
key={v.name}
|
||||
className="rounded bg-[var(--color-surface-2)] px-1.5 py-0.5 text-[10px] text-[var(--color-text-muted)]"
|
||||
>
|
||||
{v.name}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PromptVariableForm({
|
||||
prompt,
|
||||
values,
|
||||
submitDisabled,
|
||||
onVariableChange,
|
||||
onSubmit,
|
||||
onBack,
|
||||
}: {
|
||||
prompt: ProjectPromptFile;
|
||||
values: Record<string, string>;
|
||||
submitDisabled: boolean;
|
||||
onVariableChange: (name: string, value: string) => void;
|
||||
onSubmit: () => void;
|
||||
onBack: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="p-3">
|
||||
<div className="mb-3 flex items-center gap-2">
|
||||
<button
|
||||
className="flex size-5 items-center justify-center rounded text-[var(--color-text-muted)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]"
|
||||
onClick={onBack}
|
||||
type="button"
|
||||
aria-label="Back to prompt list"
|
||||
>
|
||||
<X className="size-3" />
|
||||
</button>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-[12px] font-medium text-[var(--color-text-primary)]">
|
||||
{prompt.name}
|
||||
</div>
|
||||
{prompt.description && (
|
||||
<div className="truncate text-[10px] text-[var(--color-text-muted)]">{prompt.description}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2.5">
|
||||
{prompt.variables.map((variable) => (
|
||||
<PromptVariableInput
|
||||
key={variable.name}
|
||||
onChange={(value) => onVariableChange(variable.name, value)}
|
||||
onSubmit={!submitDisabled ? onSubmit : undefined}
|
||||
value={values[variable.name] ?? ''}
|
||||
variable={variable}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<button
|
||||
className={`mt-3 flex w-full items-center justify-center gap-1.5 rounded-lg px-3 py-2 text-[12px] font-medium transition-all duration-200 ${
|
||||
submitDisabled
|
||||
? 'bg-[var(--color-surface-2)] text-[var(--color-text-muted)]'
|
||||
: 'brand-gradient-bg text-white hover:brightness-110'
|
||||
}`}
|
||||
disabled={submitDisabled}
|
||||
onClick={onSubmit}
|
||||
type="button"
|
||||
>
|
||||
<ArrowUp className="size-3.5" />
|
||||
Send prompt
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PromptVariableInput({
|
||||
variable,
|
||||
value,
|
||||
onChange,
|
||||
onSubmit,
|
||||
}: {
|
||||
variable: ProjectPromptVariable;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
onSubmit?: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<label className="mb-1 block text-[11px] font-medium text-[var(--color-text-secondary)]">
|
||||
{variable.name}
|
||||
</label>
|
||||
<input
|
||||
className="w-full rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-2)] px-2.5 py-1.5 text-[12px] text-[var(--color-text-primary)] placeholder-[var(--color-text-muted)] transition-all duration-200 focus:border-[var(--color-border-glow)] focus:outline-none"
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && onSubmit) {
|
||||
e.preventDefault();
|
||||
onSubmit();
|
||||
}
|
||||
}}
|
||||
placeholder={variable.placeholder}
|
||||
type="text"
|
||||
value={value}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { useCallback } from 'react';
|
||||
import { KeyRound, Loader2, X } from 'lucide-react';
|
||||
|
||||
import type { PendingMcpAuthRecord } from '@shared/domain/mcpAuth';
|
||||
|
||||
export function McpAuthBanner({
|
||||
mcpAuth,
|
||||
onAuthenticate,
|
||||
onDismiss,
|
||||
}: {
|
||||
mcpAuth: PendingMcpAuthRecord;
|
||||
onAuthenticate: () => void;
|
||||
onDismiss: () => void;
|
||||
}) {
|
||||
const handleAuthenticate = useCallback(() => {
|
||||
onAuthenticate();
|
||||
}, [onAuthenticate]);
|
||||
|
||||
const handleDismiss = useCallback(() => {
|
||||
onDismiss();
|
||||
}, [onDismiss]);
|
||||
|
||||
const isAuthenticating = mcpAuth.status === 'authenticating';
|
||||
const hasFailed = mcpAuth.status === 'failed';
|
||||
|
||||
return (
|
||||
<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-[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-[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-[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"
|
||||
>
|
||||
<X className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p className="mt-2 text-[13px] leading-relaxed text-[var(--color-text-primary)]">
|
||||
The MCP server{' '}
|
||||
<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-[var(--color-text-muted)]">{mcpAuth.serverUrl}</p>
|
||||
|
||||
{hasFailed && mcpAuth.errorMessage && (
|
||||
<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="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"
|
||||
>
|
||||
{isAuthenticating ? (
|
||||
<>
|
||||
<Loader2 className="size-3.5 animate-spin" />
|
||||
Authenticating…
|
||||
</>
|
||||
) : hasFailed ? (
|
||||
'Retry authentication'
|
||||
) : (
|
||||
'Authenticate in browser'
|
||||
)}
|
||||
</button>
|
||||
<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.'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 & 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 & 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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
AlertTriangle,
|
||||
BookOpen,
|
||||
ChevronDown,
|
||||
ExternalLink,
|
||||
FileEdit,
|
||||
FileText,
|
||||
Globe,
|
||||
Server,
|
||||
Terminal,
|
||||
} from 'lucide-react';
|
||||
|
||||
import type { PermissionDetail } from '@shared/contracts/sidecar';
|
||||
|
||||
export function PermissionDetailView({ detail }: { detail: PermissionDetail }) {
|
||||
switch (detail.kind) {
|
||||
case 'shell':
|
||||
return <ShellDetail detail={detail} />;
|
||||
case 'write':
|
||||
return <WriteDetail detail={detail} />;
|
||||
case 'read':
|
||||
return <ReadDetail detail={detail} />;
|
||||
case 'mcp':
|
||||
return <McpDetail detail={detail} />;
|
||||
case 'url':
|
||||
return <UrlDetail detail={detail} />;
|
||||
case 'memory':
|
||||
return <MemoryDetail detail={detail} />;
|
||||
case 'custom-tool':
|
||||
return <CustomToolDetail detail={detail} />;
|
||||
case 'hook':
|
||||
return <HookDetail detail={detail} />;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function permissionDetailSummary(detail: PermissionDetail): string | undefined {
|
||||
switch (detail.kind) {
|
||||
case 'shell':
|
||||
return detail.command ? truncate(detail.command, 80) : undefined;
|
||||
case 'write':
|
||||
return detail.fileName;
|
||||
case 'read':
|
||||
return detail.path;
|
||||
case 'url':
|
||||
return detail.url;
|
||||
case 'mcp':
|
||||
return detail.serverName
|
||||
? `${detail.serverName} → ${detail.toolTitle ?? ''}`
|
||||
: detail.toolTitle;
|
||||
case 'memory':
|
||||
return detail.subject;
|
||||
case 'custom-tool':
|
||||
return detail.toolDescription ? truncate(detail.toolDescription, 80) : undefined;
|
||||
case 'hook':
|
||||
return detail.hookMessage ? truncate(detail.hookMessage, 80) : undefined;
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Kind-specific renderers ────────────────────────────────── */
|
||||
|
||||
function ShellDetail({ detail }: { detail: PermissionDetail }) {
|
||||
return (
|
||||
<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-[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>
|
||||
)}
|
||||
{detail.command && <CommandBlock text={detail.command} />}
|
||||
{detail.possiblePaths && detail.possiblePaths.length > 0 && (
|
||||
<MetaList label="Paths" items={detail.possiblePaths} />
|
||||
)}
|
||||
{detail.possibleUrls && detail.possibleUrls.length > 0 && (
|
||||
<MetaList label="URLs" items={detail.possibleUrls} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WriteDetail({ detail }: { detail: PermissionDetail }) {
|
||||
return (
|
||||
<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-[var(--color-text-primary)]">
|
||||
<FileEdit className="size-3 shrink-0 text-[var(--color-text-muted)]" />
|
||||
<code className="font-mono">{detail.fileName}</code>
|
||||
</div>
|
||||
)}
|
||||
{detail.diff && <DiffBlock text={detail.diff} />}
|
||||
{!detail.diff && detail.newFileContents && (
|
||||
<CollapsibleCode label="New file contents" text={detail.newFileContents} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ReadDetail({ detail }: { detail: PermissionDetail }) {
|
||||
return (
|
||||
<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-[var(--color-text-primary)]">
|
||||
<FileText className="size-3 shrink-0 text-[var(--color-text-muted)]" />
|
||||
<code className="font-mono">{detail.path}</code>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function McpDetail({ detail }: { detail: PermissionDetail }) {
|
||||
return (
|
||||
<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-[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-[var(--color-text-primary)]">{detail.toolTitle}</span>}
|
||||
{detail.readOnly && (
|
||||
<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)} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function UrlDetail({ detail }: { detail: PermissionDetail }) {
|
||||
return (
|
||||
<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-[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-[var(--color-text-muted)]" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MemoryDetail({ detail }: { detail: PermissionDetail }) {
|
||||
return (
|
||||
<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-[var(--color-text-muted)]" />
|
||||
<span className="font-medium text-[var(--color-text-primary)]">{detail.subject}</span>
|
||||
</div>
|
||||
)}
|
||||
{detail.fact && (
|
||||
<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-[var(--color-text-muted)]">
|
||||
Source: <span className="text-[var(--color-text-secondary)]">{detail.citations}</span>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CustomToolDetail({ detail }: { detail: PermissionDetail }) {
|
||||
return (
|
||||
<div className="mt-2.5 space-y-2">
|
||||
{detail.toolDescription && (
|
||||
<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)} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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-[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)} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ── Shared primitives ──────────────────────────────────────── */
|
||||
|
||||
function IntentionLine({ text }: { text: string }) {
|
||||
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-[var(--color-surface-1)] px-3 py-2 font-mono text-[11px] leading-relaxed text-[var(--color-status-success)]">
|
||||
{text}
|
||||
</pre>
|
||||
);
|
||||
}
|
||||
|
||||
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-[var(--color-surface-1)] px-3 py-2 font-mono text-[10px] leading-relaxed">
|
||||
{lines.map((line, i) => {
|
||||
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}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</pre>
|
||||
</CollapsibleCode>
|
||||
);
|
||||
}
|
||||
|
||||
function CollapsibleCode({
|
||||
label,
|
||||
text,
|
||||
children,
|
||||
defaultExpanded = false,
|
||||
}: {
|
||||
label: string;
|
||||
text: string;
|
||||
children?: React.ReactNode;
|
||||
defaultExpanded?: boolean;
|
||||
}) {
|
||||
const [expanded, setExpanded] = useState(defaultExpanded);
|
||||
|
||||
return (
|
||||
<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-[var(--color-text-muted)] transition-all duration-200 hover:text-[var(--color-text-secondary)]"
|
||||
onClick={() => setExpanded(!expanded)}
|
||||
type="button"
|
||||
>
|
||||
<ChevronDown
|
||||
className={`size-2.5 transition-transform ${expanded ? 'rotate-180' : ''}`}
|
||||
/>
|
||||
{label}
|
||||
</button>
|
||||
{expanded && (
|
||||
<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-[var(--color-text-primary)]">
|
||||
{text}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MetaList({ label, items }: { label: string; items: string[] }) {
|
||||
return (
|
||||
<div className="text-[10px] text-[var(--color-text-muted)]">
|
||||
<span className="font-medium">{label}:</span>{' '}
|
||||
<span className="text-[var(--color-text-secondary)]">{items.join(', ')}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function truncate(text: string, maxLength: number): string {
|
||||
return text.length <= maxLength ? text : `${text.slice(0, maxLength)}…`;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user